pax_global_header00006660000000000000000000000064137117730400014515gustar00rootroot0000000000000052 comment=7fdafb0e9937ae92f4d703387ee75c8264ee67ae iotjs-1.0+715/000077500000000000000000000000001371177304000130155ustar00rootroot00000000000000iotjs-1.0+715/.clang-format000066400000000000000000000055101371177304000153710ustar00rootroot00000000000000# 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 ... iotjs-1.0+715/.eslintignore000066400000000000000000000000401371177304000155120ustar00rootroot00000000000000/build/** /deps/** /src/js/ble* iotjs-1.0+715/.eslintrc.js000066400000000000000000000045041371177304000152570ustar00rootroot00000000000000/* 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 es6 = { 'generator-star-spacing': [2, 'after'], 'no-var': 2, 'prefer-rest-params': 2, 'prefer-spread': 2, 'rest-spread-spacing': 2, 'yield-star-spacing': [2, 'after'], } var eslintRecommended = { 'no-console': 0, 'no-empty': 0, // TODO: remove this feature 'no-constant-condition': [2, { 'checkLoops': false }] } var style = { 'no-multi-spaces': 2, 'no-multi-str': 2, 'array-bracket-spacing': [2, 'never'], 'block-spacing': [2, 'never'], 'brace-style': 2, 'comma-dangle': [2, 'always-multiline'], 'comma-spacing': 2, 'comma-style': 2, 'computed-property-spacing': 2, 'eol-last': 2, 'func-call-spacing': 2, 'key-spacing': 2, 'keyword-spacing': 2, 'linebreak-style': 2, 'no-multiple-empty-lines': [2, {max: 2}], 'no-tabs': 2, 'no-trailing-spaces': 2, 'semi-spacing': 2, 'space-before-blocks': 2, 'space-before-function-paren': [2, { anonymous: 'never', named: 'never', }], 'spaced-comment': [2, 'always'], 'switch-colon-spacing': 2, 'quotes': [2, 'single'], } var syntax = { 'no-plusplus': 0, 'guard-for-in': 2, 'no-caller': 2, 'no-extend-native': 2, 'no-new-wrappers': 2, 'new-cap': [2, { 'capIsNew': false, 'newIsCapExceptions': ['native'] }], 'no-array-constructor': 2, 'no-new-object': 2, 'semi': 2, } module.exports = { 'extends': 'eslint:recommended', 'env': { 'node': true, 'es6': false, }, 'globals': { 'native': true, }, 'rules': Object.assign( eslintRecommended, style, syntax, { // Optional rules 'max-len': [2, { code: 80, tabWidth: 2, ignoreUrls: true, ignoreTemplateLiterals: true, ignoreRegExpLiterals: true }], }), } iotjs-1.0+715/.gitignore000066400000000000000000000013011371177304000150000ustar00rootroot00000000000000# Produced files /build /build/* /src/iotjs_js.h /src/iotjs_js.c /src/iotjs_string_ext.inl.h /src/iotjs_module_inl.h /test/tmp/* /test/dynamicmodule/build/* /tools/module_generator/output /test/module_generator/test_c/*.a /test/module_generator/test_c/*.o /test/module_generator/test_cpp/*.a /test/module_generator/test_cpp/*.o eslint.log # IDE related files nbproject **.sublime-project **.sublime-workspace .idea # Random Trash *.swp *.swo *~ core vgcore.* **.orig **.directory **.patch .tags* cscope.* *.pyc # Dependency directories node_modules/ iotjs_modules/ # Coverage directory used by tools like istanbul coverage # ctags and ID database tags ID TAGS # config files *.config !build.config iotjs-1.0+715/.gitmodules000066400000000000000000000010011371177304000151620ustar00rootroot00000000000000[submodule "deps/jerry"] path = deps/jerry url = https://github.com/jerryscript-project/jerryscript.git ignore = untracked [submodule "deps/http-parser"] path = deps/http-parser url = https://github.com/Samsung/http-parser.git ignore = untracked [submodule "deps/libtuv"] path = deps/libtuv url = https://github.com/Samsung/libtuv.git ignore = untracked [submodule "deps/mbedtls"] path = deps/mbedtls url = https://github.com/ARMmbed/mbedtls.git ignore = untracked iotjs-1.0+715/.travis.yml000066400000000000000000000055301371177304000151310ustar00rootroot00000000000000language: c os: linux dist: trusty services: - docker script: tools/travis_script.py matrix: include: - name: "Linux/x86-64 Build & Correctness Tests" env: - OPTS="host-linux" - name: "Mock Linux Build & Correctness Tests" env: - OPTS="mock-linux" - name: "Linux/x86-64 Build with N-API support & Correctness Tests" env: - OPTS="n-api" install: - npm install - name: "Raspberry Pi 2 Build Test" env: - OPTS="rpi2" - name: "STM32f4 Discovery with Nuttx Build Test" env: - OPTS="stm32f4dis" - name: "Tizen Build Test" env: - OPTS="tizen" - name: "ECMAScript 2015 features Build & Correctness Tests" env: - OPTS="es2015" - name: "External modules Build & Correctness Tests" env: - OPTS="external-modules" - name: "Linux/x86-64 without snapshot Build & Correctness Tests" env: - OPTS="no-snapshot" - name: "Misc checks (e.g. style checker)" env: - OPTS="misc" addons: apt: packages: [clang-format-3.9, npm, valgrind] install: - npm install eslint - name: "OSX/x86-64 Build & Correctness Tests" env: - OPTS="host-darwin" os: osx addons: homebrew: packages: [cmake] - name: "ASAN Tests" env: - OPTS="asan" - name: "UBSAN Tests" env: - OPTS="ubsan" - name: "Coverity Scan" env: - OPTS="coverity" # Declaration of the encrypted COVERITY_SCAN_TOKEN, created via the # "travis encrypt" command using the project repo's public key. - secure: "qbQASyP3/OzpzAp8xRFL2uOAHhMbO0jVRJFg9i8UcPurHUXj1Erk0hOmS3gxkkv7g2BU1mwsMz2SLwKtAEzEwES5rEmAbJ8Jf/zWEPqjXA1taOfCKRyuGGxIdQD1AcU3dIUbYd+CJ9JwmfLcb5XIcoEQVfd0etl7bkJu43bqTptc0lnT6HAsl+QZ9y3tJH4qklTg9lJI6hp2aVtvT/liTJgqfZlXs0SsgDmZZ9C6B1ienhRFQZLezEVCRrjIbUfcHH5IWkXkIjfCdMXfYLqLhTZVHU7lxCcZhOIpMSVX0W85Ov2YTAaKyhTmHCETjjVFw0RK2t42lm7C5l7j0peF+PCG2Qw/w/KMfNKWf8CBcZX/IquOUu7/EFtWE/rc7qi4bKhLwOYtqTAroJjkX6YsPaQlsryAbtsIMlkFvW8oI7TxzJ9HE7co70/rgEj7Qka/7SLptVWyUxVWtJRQqBCE/piUzyAe/GYsmX4Qje+fY+b5spWWvFscxsBP3J5qA2zhV4nJQvJmnRNhz1wMmfh5tKO9Hifeof6JeISlGFRGqSX/RtVriRtI60FyEsHk6lZQqtW+INSVTHjoewC29kIdttbH1qjJ8L5+PmsiZRrm4ER38tnOrH1cGz1PdcTQJGoqVcB446f5Uc9G76q23xR7wkfkqb3P6zlF379C2rE41ps=" addons: coverity_scan: project: name: "jerryscript-project/iotjs" description: "Platform for Internet of Things with JavaScript" notification_email: haesik.jun@samsung.com build_command: "tools/travis_script.py" branch_pattern: master - name: "SonarQube" addons: sonarcloud: organization: "pando-project" script: ./tools/check_sonarqube.sh cache: directories: - '$HOME/.sonar/cache' fast_finish: true iotjs-1.0+715/CMakeLists.txt000066400000000000000000000157561371177304000155730ustar00rootroot00000000000000# 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. cmake_minimum_required(VERSION 2.8) include(CheckCCompilerFlag) project(IOTJS C) set(IOTJS_VERSION_MAJOR 1) set(IOTJS_VERSION_MINOR 0) if(NOT DEFINED TARGET_OS) string(TOLOWER ${CMAKE_SYSTEM_NAME} TARGET_OS) message( "TARGET_OS not specified, using '${TARGET_OS}' from CMAKE_SYSTEM_NAME") endif() if(NOT CMAKE_BUILD_TYPE) message("CMAKE_BUILD_TYPE was not set! Configuring for Debug build!") set(CMAKE_BUILD_TYPE Debug) elseif("${CMAKE_BUILD_TYPE}" STREQUAL "Release") message("CMAKE_BUILD_TYPE was set to Release, switching to MinSizeRel") set(CMAKE_BUILD_TYPE MinSizeRel) endif() if(NOT DEFINED BUILD_LIB_ONLY) set(BUILD_LIB_ONLY OFF) endif() if(NOT DEFINED ENABLE_SNAPSHOT) message("Snapshot mode force enabled") set(ENABLE_SNAPSHOT ON) endif() if(NOT DEFINED ENABLE_LTO) message("LTO force disabled") set(ENABLE_LTO OFF) endif() macro(iotjs_add_flags VAR) foreach(_flag ${ARGN}) set(${VAR} "${${VAR}} ${_flag}") endforeach() endmacro() macro(iotjs_add_compile_flags) iotjs_add_flags(CMAKE_C_FLAGS ${ARGV}) endmacro() macro(iotjs_add_link_flags) iotjs_add_flags(IOTJS_LINKER_FLAGS ${ARGV}) endmacro() macro(build_lib_name LIB_VAR NAME) set(${LIB_VAR} ${CMAKE_STATIC_LIBRARY_PREFIX}${NAME}${CMAKE_STATIC_LIBRARY_SUFFIX}) endmacro() if(CMAKE_C_COMPILER_ID MATCHES "MSVC") set(USING_MSVC 1) set(CONFIG_TYPE $<$:Debug>$<$:Release>) # disable warning C4820: 'x' bytes padding added after construct 'membername' iotjs_add_compile_flags(-wd4820) # disable warning C4668: 'symbol' is not defined as preprocessor macro, # replacing with '0' for 'directives' # some windows headers reports these warnings iotjs_add_compile_flags(-wd4668) # disable warning C4100: unreferenced formal parameter iotjs_add_compile_flags(-wd4100) endif() CHECK_C_COMPILER_FLAG(-no-pie HAS_NO_PIE) # Add buildtype-related flags if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") iotjs_add_compile_flags(-DDEBUG -DENABLE_DEBUG_LOG) if(HAS_NO_PIE AND NOT "${TARGET_OS}" STREQUAL "darwin") iotjs_add_link_flags(-no-pie) endif() else() iotjs_add_compile_flags(-fPIE) if("${TARGET_OS}" STREQUAL "darwin") iotjs_add_link_flags(-Wl,-pie) else() iotjs_add_link_flags(-pie) endif() endif() if (CREATE_SHARED_LIB) iotjs_add_compile_flags(-fPIC) endif() if(EXPERIMENTAL) iotjs_add_compile_flags(-DEXPERIMENTAL) endif() # Add arch-dependant flags if(NOT DEFINED TARGET_ARCH) message(WARNING "Use generic flags since TARGET_ARCH is not defined") set(TARGET_ARCH "noarch") endif() if("${TARGET_ARCH}" STREQUAL "arm") iotjs_add_compile_flags(-D__arm__ -mthumb -fno-short-enums -mlittle-endian) elseif("${TARGET_ARCH}" STREQUAL "i686") iotjs_add_compile_flags(-D__i686__ -D__x86__) if(NOT USING_MSVC) iotjs_add_compile_flags(-march=i686 -m32) endif() elseif("${TARGET_ARCH}" STREQUAL "x86_64") iotjs_add_compile_flags(-D__x86_64__) elseif("${TARGET_ARCH}" STREQUAL "mips") message("MIPS support is experimental!") if(NOT EXPERIMENTAL) message(FATAL_ERROR "Missing --experimental build option for MIPS!") endif() if(ENABLE_SNAPSHOT) message(FATAL_ERROR "Cross endian snapshots are not supported. " "Please disable snapshot mode for mips!") endif() elseif("${TARGET_ARCH}" STREQUAL "noarch") else() message(WARNING "Unknown target arch: ${TARGET_ARCH}.") endif() # Add board-dependant flags if(NOT DEFINED TARGET_BOARD) set(TARGET_BOARD "generic") endif() iotjs_add_compile_flags(-DTARGET_BOARD=${TARGET_BOARD}) string(TOUPPER ${TARGET_BOARD} TARGET_BOARD_UPPER) string(CONCAT TARGET_BOARD_SYMBOL "TARGET_BOARD_" ${TARGET_BOARD_UPPER}) iotjs_add_compile_flags(-D${TARGET_BOARD_SYMBOL}=1) if("${TARGET_BOARD}" STREQUAL "artik05x") iotjs_add_compile_flags(-mcpu=cortex-r4 -mfpu=vfp3) elseif("${TARGET_BOARD}" STREQUAL "artik10") iotjs_add_compile_flags(-mcpu=cortex-a7 -mfpu=neon-vfpv4 -mfloat-abi=softfp) elseif("${TARGET_BOARD}" STREQUAL "rpi2") iotjs_add_compile_flags(-mcpu=cortex-a7 -mfpu=neon-vfpv4) elseif("${TARGET_BOARD}" STREQUAL "rpi3") if("${TARGET_OS}" STREQUAL "tizen") iotjs_add_compile_flags(-mfpu=neon-vfpv4 -mfloat-abi=softfp) endif() elseif("${TARGET_BOARD}" STREQUAL "stm32f4dis") iotjs_add_compile_flags(-mcpu=cortex-m4 -march=armv7e-m -mfpu=fpv4-sp-d16) iotjs_add_compile_flags(-mfloat-abi=hard) elseif("${TARGET_BOARD}" STREQUAL "stm32f7nucleo") iotjs_add_compile_flags(-mcpu=cortex-m7) iotjs_add_compile_flags(-mfloat-abi=hard) endif() # Add os-dependant flags if("${TARGET_OS}" STREQUAL "darwin") iotjs_add_compile_flags(-D__DARWIN__ -fno-builtin) elseif("${TARGET_OS}" STREQUAL "linux") iotjs_add_compile_flags(-D__LINUX__ -fno-builtin) iotjs_add_link_flags(-pthread -rdynamic) iotjs_add_flags(EXTERNAL_LIBS m rt) elseif("${TARGET_OS}" STREQUAL "nuttx") iotjs_add_compile_flags(-D__NUTTX__ -Os -fno-strict-aliasing) iotjs_add_compile_flags(-fno-strength-reduce -fomit-frame-pointer) elseif("${TARGET_OS}" STREQUAL "tizen") iotjs_add_compile_flags(-D__TIZEN__ -fno-builtin) iotjs_add_link_flags(-pthread -rdynamic) iotjs_add_flags(EXTERNAL_LIBS m rt) elseif("${TARGET_OS}" STREQUAL "tizenrt") iotjs_add_compile_flags(-D__TIZENRT__ -Os -fno-strict-aliasing) iotjs_add_compile_flags(-fno-strength-reduce -fomit-frame-pointer) elseif("${TARGET_OS}" STREQUAL "windows") message("Windows support is experimental!") if(NOT EXPERIMENTAL) message(FATAL_ERROR "Missing --experimental build option for Windows!") endif() elseif("${TARGET_OS}" STREQUAL "openwrt") message("OpenWrt support is experimental!") if(NOT EXPERIMENTAL) message(FATAL_ERROR "Missing --experimental build option for OpenWrt!") endif() iotjs_add_compile_flags(-D__OPENWRT__ -D_GNU_SOURCE) iotjs_add_link_flags(-pthread) else() message(WARNING "Unknown target os: ${TARGET_OS}.") endif() # Add external options if(DEFINED EXTERNAL_COMPILE_FLAGS) iotjs_add_compile_flags(${EXTERNAL_COMPILE_FLAGS}) endif() if(DEFINED EXTERNAL_LINKER_FLAGS) iotjs_add_link_flags(${EXTERNAL_LINKER_FLAGS}) endif() string(TOUPPER "${TARGET_OS}" TARGET_OS) set(ROOT_DIR ${CMAKE_SOURCE_DIR}) set(ARCHIVE_DIR ${CMAKE_BINARY_DIR}/lib) include(ExternalProject) if(NOT ${EXTERNAL_LIBC_INTERFACE} STREQUAL "") iotjs_add_compile_flags(-isystem ${EXTERNAL_LIBC_INTERFACE}) endif() # Include external projects include(cmake/jerry.cmake) include(cmake/http-parser.cmake) include(cmake/libtuv.cmake) include(cmake/iotjs.cmake) iotjs-1.0+715/LICENSE000066400000000000000000000274601371177304000140330ustar00rootroot00000000000000Copyright 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. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS -------- 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/node/node repository: iotjs-1.0+715/README.md000066400000000000000000000120071371177304000142740ustar00rootroot00000000000000# IoT.js: Platform for Internet of Things with JavaScript [![License](https://img.shields.io/badge/licence-Apache%202.0-brightgreen.svg?style=flat)](LICENSE) [![Build Status](https://travis-ci.org/jerryscript-project/iotjs.svg?branch=master)](https://travis-ci.org/jerryscript-project/iotjs) [![Coverity Scan Build Status](https://scan.coverity.com/projects/12140/badge.svg)](https://scan.coverity.com/projects/samsung-iotjs) [![SonarCloud Status](https://sonarcloud.io/api/project_badges/measure?project=pando-project_iotjs&metric=alert_status)](https://sonarcloud.io/dashboard?id=pando-project_iotjs) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2FSamsung%2Fiotjs.svg?type=shield)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2FSamsung%2Fiotjs?ref=badge_shield) [![IRC Channel](https://img.shields.io/badge/chat-on%20freenode-brightgreen.svg)](https://kiwiirc.com/client/irc.freenode.net/#iotjs) You can find project details on our [project page](http://jerryscript-project.github.io/iotjs/) and [wiki](https://github.com/jerryscript-project/iotjs/wiki). Memory usage and Binary footprint are measured at [here](https://jerryscript-project.github.io/iotjs-test-results) with real target daily. The following table shows the latest results on the devices: | Raspberry Pi 3 | [![Remote Testrunner](https://firebasestorage.googleapis.com/v0/b/jsremote-testrunner.appspot.com/o/status%2Fiotjs%2Frpi3.svg?alt=media&token=1)](https://jerryscript-project.github.io/iotjs-test-results/?view=rpi3) | | :---: | :---: | | **Raspberry Pi 2** | [![Remote Testrunner](https://firebasestorage.googleapis.com/v0/b/jsremote-testrunner.appspot.com/o/status%2Fiotjs%2Frpi2.svg?alt=media&token=1)](https://jerryscript-project.github.io/iotjs-test-results/?view=rpi2) | | **STM32F4-Discovery** | [![Remote Testrunner](https://firebasestorage.googleapis.com/v0/b/jsremote-testrunner.appspot.com/o/status%2Fiotjs%2Fstm32f4dis.svg?alt=media&token=1)](https://jerryscript-project.github.io/iotjs-test-results/?view=stm32f4dis) | 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/jerryscript-project/iotjs.git cd iotjs ``` ### How to Build ```bash tools/build.py ``` ### How to Test ```bash tools/testrunner.py build/x86_64-linux/debug/bin/iotjs ``` ### Trying out with a REPL ```bash build/x86_64-linux/debug/bin/iotjs tools/repl.js ``` For Additional information see [Getting Started](docs/Getting-Started.md). ## Documentation - [Getting Started](docs/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. [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2FSamsung%2Fiotjs.svg?type=large)](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: iotjs-1.0+715/appveyor.yml000066400000000000000000000016021371177304000154040ustar00rootroot00000000000000version: "{build}" branches: except: - coverity_scan - gh_pages skip_tags: true image: - Visual Studio 2017 configuration: - Debug - Release platform: - Win32 - x64 init: - cmd: | if "%PLATFORM%"=="Win32" set SYS_ARCH=i686 if "%PLATFORM%"=="x64" set SYS_ARCH=x86_64 cmake -version install: - ps: | Install-Product node 10.15.3 artifacts: - path: build\%SYS_ARCH%-windows\$(configuration)\bin\$(configuration)\ name: IoTjsbinary before_build: - cmd: | tools\build.py --experimental --buildtype=%CONFIGURATION% --target-arch=%SYS_ARCH% --jerry-profile=es2015-subset --n-api build: project: build\%SYS_ARCH%-windows\%CONFIGURATION%\IOTJS.sln parallel: true verbosity: minimal before_test: - cmd: npm install test_script: - cmd: | tools\testrunner.py build\%SYS_ARCH%-windows\%CONFIGURATION%\bin\%CONFIGURATION%\iotjs.exe iotjs-1.0+715/build.config000066400000000000000000000011021371177304000152750ustar00rootroot00000000000000{ "builddir": "", "buildlib": false, "buildtype": "debug", "clean": false, "config": "", "cmake-param": [], "compile-flag": [], "external-include-dir": [], "external-lib": [], "jerry-cmake-param": [], "jerry-compile-flag": [], "jerry-heaplimit": 256, "jerry-link-flag": [], "jerry-lto": false, "jerry-memstat": false, "link-flag": [], "no-check-tidy": false, "no-init-submodule": false, "no-parallel-build": false, "no-snapshot": false, "run-test": false, "sysroot": "", "target-arch": "", "target-os": "", "target-board": "" } iotjs-1.0+715/cmake/000077500000000000000000000000001371177304000140755ustar00rootroot00000000000000iotjs-1.0+715/cmake/JSONParser.cmake000066400000000000000000000231671371177304000170360ustar00rootroot00000000000000# 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. # # The MIT License (MIT) # # Copyright (c) 2015 Stefan Bellus # # 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. cmake_minimum_required(VERSION 2.8) if (DEFINED JSonParserGuard) return() endif() set(JSonParserGuard yes) macro(sbeParseJson prefix jsonString) cmake_policy(PUSH) set(json_string "${${jsonString}}") string(LENGTH "${json_string}" json_jsonLen) set(json_index 0) set(json_AllVariables ${prefix}) set(json_ArrayNestingLevel 0) set(json_MaxArrayNestingLevel 0) _sbeParse(${prefix}) unset(json_index) unset(json_AllVariables) unset(json_jsonLen) unset(json_string) unset(json_value) unset(json_inValue) unset(json_name) unset(json_inName) unset(json_newPrefix) unset(json_reservedWord) unset(json_arrayIndex) unset(json_char) unset(json_end) unset(json_ArrayNestingLevel) foreach(json_nestingLevel RANGE ${json_MaxArrayNestingLevel}) unset(json_${json_nestingLevel}_arrayIndex) endforeach() unset(json_nestingLevel) unset(json_MaxArrayNestingLevel) cmake_policy(POP) endmacro() macro(sbeClearJson prefix) foreach(json_var ${${prefix}}) unset(${json_var}) endforeach() unset(${prefix}) unset(json_var) endmacro() macro(sbePrintJson prefix) foreach(json_var ${${prefix}}) message("${json_var} = ${${json_var}}") endforeach() endmacro() macro(_sbeParse prefix) while(${json_index} LESS ${json_jsonLen}) string(SUBSTRING "${json_string}" ${json_index} 1 json_char) if("\"" STREQUAL "${json_char}") _sbeParseNameValue(${prefix}) elseif("{" STREQUAL "${json_char}") _sbeMoveToNextNonEmptyCharacter() _sbeParseObject(${prefix}) elseif("[" STREQUAL "${json_char}") _sbeMoveToNextNonEmptyCharacter() _sbeParseArray(${prefix}) endif() if(${json_index} LESS ${json_jsonLen}) string(SUBSTRING "${json_string}" ${json_index} 1 json_char) else() break() endif() if ("}" STREQUAL "${json_char}" OR "]" STREQUAL "${json_char}") break() endif() _sbeMoveToNextNonEmptyCharacter() endwhile() endmacro() macro(_sbeParseNameValue prefix) set(json_name "") set(json_inName no) while(${json_index} LESS ${json_jsonLen}) string(SUBSTRING "${json_string}" ${json_index} 1 json_char) # check if name ends if("\"" STREQUAL ${json_char} AND json_inName) set(json_inName no) _sbeMoveToNextNonEmptyCharacter() if(NOT ${json_index} LESS ${json_jsonLen}) break() endif() string(SUBSTRING "${json_string}" ${json_index} 1 json_char) set(json_newPrefix ${prefix}.${json_name}) set(json_name "") if(":" STREQUAL "${json_char}") _sbeMoveToNextNonEmptyCharacter() if(NOT ${json_index} LESS ${json_jsonLen}) break() endif() string(SUBSTRING "${json_string}" ${json_index} 1 json_char) if("\"" STREQUAL "${json_char}") _sbeParseValue(${json_newPrefix}) break() elseif("{" STREQUAL "${json_char}") _sbeMoveToNextNonEmptyCharacter() _sbeParseObject(${json_newPrefix}) break() elseif("[" STREQUAL "${json_char}") _sbeMoveToNextNonEmptyCharacter() _sbeParseArray(${json_newPrefix}) break() else() # reserved word starts _sbeParseReservedWord(${json_newPrefix}) break() endif() else() # name without value list(APPEND ${json_AllVariables} ${json_newPrefix}) set(${json_newPrefix} "") break() endif() endif() if(json_inName) # remove escapes if("\\" STREQUAL ${json_char}) math(EXPR json_index "${json_index} + 1") if(NOT ${json_index} LESS ${json_jsonLen}) break() endif() string(SUBSTRING "${json_string}" ${json_index} 1 json_char) endif() set(json_name "${json_name}${json_char}") endif() # check if name starts if("\"" STREQUAL ${json_char} AND NOT json_inName) set(json_inName yes) endif() _sbeMoveToNextNonEmptyCharacter() endwhile() endmacro() macro(_sbeParseReservedWord prefix) set(json_reservedWord "") set(json_end no) while(${json_index} LESS ${json_jsonLen} AND NOT json_end) string(SUBSTRING "${json_string}" ${json_index} 1 json_char) if("," STREQUAL "${json_char}" OR "}" STREQUAL "${json_char}" OR "]" STREQUAL "${json_char}") set(json_end yes) else() set(json_reservedWord "${json_reservedWord}${json_char}") math(EXPR json_index "${json_index} + 1") endif() endwhile() list(APPEND ${json_AllVariables} ${prefix}) string(STRIP "${json_reservedWord}" json_reservedWord) set(${prefix} ${json_reservedWord}) endmacro() macro(_sbeParseValue prefix) set(json_value "") set(json_inValue no) while(${json_index} LESS ${json_jsonLen}) string(SUBSTRING "${json_string}" ${json_index} 1 json_char) # check if json_value ends, it is ended by " if("\"" STREQUAL ${json_char} AND json_inValue) set(json_inValue no) set(${prefix} ${json_value}) list(APPEND ${json_AllVariables} ${prefix}) _sbeMoveToNextNonEmptyCharacter() break() endif() if(json_inValue) # if " is escaped consume if("\\" STREQUAL ${json_char}) math(EXPR json_index "${json_index} + 1") if(NOT ${json_index} LESS ${json_jsonLen}) break() endif() string(SUBSTRING "${json_string}" ${json_index} 1 json_char) if(NOT "\"" STREQUAL "${json_char}") # if it is not " then copy also escape character set(json_char "\\${json_char}") endif() endif() set(json_value "${json_value}${json_char}") endif() # check if value starts if("\"" STREQUAL ${json_char} AND NOT json_inValue) set(json_inValue yes) endif() math(EXPR json_index "${json_index} + 1") endwhile() endmacro() macro(_sbeParseObject prefix) _sbeParse(${prefix}) _sbeMoveToNextNonEmptyCharacter() endmacro() macro(_sbeParseArray prefix) math(EXPR json_ArrayNestingLevel "${json_ArrayNestingLevel} + 1") set(json_${json_ArrayNestingLevel}_arrayIndex 0) set(${prefix} "") list(APPEND ${json_AllVariables} ${prefix}) while(${json_index} LESS ${json_jsonLen}) string(SUBSTRING "${json_string}" ${json_index} 1 json_char) if("\"" STREQUAL "${json_char}") # simple value list(APPEND ${prefix} ${json_${json_ArrayNestingLevel}_arrayIndex}) _sbeParseValue(${prefix}_${json_${json_ArrayNestingLevel}_arrayIndex}) elseif("{" STREQUAL "${json_char}") # object _sbeMoveToNextNonEmptyCharacter() list(APPEND ${prefix} ${json_${json_ArrayNestingLevel}_arrayIndex}) _sbeParseObject(${prefix}_${json_${json_ArrayNestingLevel}_arrayIndex}) else() list(APPEND ${prefix} ${json_${json_ArrayNestingLevel}_arrayIndex}) _sbeParseReservedWord( ${prefix}_${json_${json_ArrayNestingLevel}_arrayIndex}) endif() if(NOT ${json_index} LESS ${json_jsonLen}) break() endif() string(SUBSTRING "${json_string}" ${json_index} 1 json_char) if("]" STREQUAL "${json_char}") _sbeMoveToNextNonEmptyCharacter() break() elseif("," STREQUAL "${json_char}") math(EXPR json_${json_ArrayNestingLevel}_arrayIndex "${json_${json_ArrayNestingLevel}_arrayIndex} + 1") endif() _sbeMoveToNextNonEmptyCharacter() endwhile() if(${json_MaxArrayNestingLevel} LESS ${json_ArrayNestingLevel}) set(json_MaxArrayNestingLevel ${json_ArrayNestingLevel}) endif() math(EXPR json_ArrayNestingLevel "${json_ArrayNestingLevel} - 1") endmacro() macro(_sbeMoveToNextNonEmptyCharacter) math(EXPR json_index "${json_index} + 1") if(${json_index} LESS ${json_jsonLen}) string(SUBSTRING "${json_string}" ${json_index} 1 json_char) while(${json_char} MATCHES "[ \t\n\r]" AND ${json_index} LESS ${json_jsonLen}) math(EXPR json_index "${json_index} + 1") if(${json_index} LESS ${json_jsonLen}) string(SUBSTRING "${json_string}" ${json_index} 1 json_char) endif() endwhile() endif() endmacro() iotjs-1.0+715/cmake/config/000077500000000000000000000000001371177304000153425ustar00rootroot00000000000000iotjs-1.0+715/cmake/config/arm-linux.cmake000066400000000000000000000014001371177304000202530ustar00rootroot00000000000000# 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. set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCESSOR armv7l) set(CMAKE_C_COMPILER arm-linux-gnueabihf-gcc) set(CMAKE_C_COMPILER_WORKS TRUE) iotjs-1.0+715/cmake/config/arm-nuttx.cmake000066400000000000000000000013721371177304000203060ustar00rootroot00000000000000# 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. set(CMAKE_SYSTEM_NAME Nuttx) set(CMAKE_SYSTEM_PROCESSOR armv7l) set(CMAKE_C_COMPILER arm-none-eabi-gcc) set(CMAKE_C_COMPILER_WORKS TRUE) iotjs-1.0+715/cmake/config/arm-tizen.cmake000066400000000000000000000020741371177304000202550ustar00rootroot00000000000000# 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. set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCESSOR armv7l) # Only set the compiler if not provided already 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() iotjs-1.0+715/cmake/config/arm-tizenrt.cmake000066400000000000000000000013741371177304000206250ustar00rootroot00000000000000# 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. set(CMAKE_SYSTEM_NAME Tizenrt) set(CMAKE_SYSTEM_PROCESSOR armv7l) set(CMAKE_C_COMPILER arm-none-eabi-gcc) set(CMAKE_C_COMPILER_WORKS TRUE) iotjs-1.0+715/cmake/config/i686-linux.cmake000066400000000000000000000012561371177304000202010ustar00rootroot00000000000000# 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. set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCESSOR i686) iotjs-1.0+715/cmake/config/i686-windows.cmake000066400000000000000000000013571371177304000205360ustar00rootroot00000000000000# 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. set(CMAKE_SYSTEM_NAME Windows) set(CMAKE_SYSTEM_PROCESSOR i686) set(CMAKE_C_COMPILER CL.exe) set(CMAKE_C_COMPILER_WORKS TRUE) iotjs-1.0+715/cmake/config/mips-openwrt.cmake000066400000000000000000000014001371177304000210030ustar00rootroot00000000000000# Copyright 2018-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. set(CMAKE_SYSTEM_NAME Openwrt) set(CMAKE_SYSTEM_PROCESSOR mips) set(CMAKE_C_COMPILER mips-openwrt-linux-gcc) set(CMAKE_C_COMPILER_WORKS TRUE) iotjs-1.0+715/cmake/config/noarch-linux.cmake000066400000000000000000000012151371177304000207520ustar00rootroot00000000000000# Copyright 2018-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. set(CMAKE_SYSTEM_NAME Linux) iotjs-1.0+715/cmake/config/noarch-tizen.cmake000066400000000000000000000012521371177304000207450ustar00rootroot00000000000000# Copyright 2018-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 Tizen) iotjs-1.0+715/cmake/config/x86_64-darwin.cmake000066400000000000000000000012611371177304000205640ustar00rootroot00000000000000# 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. set(CMAKE_SYSTEM_NAME Darwin) set(CMAKE_SYSTEM_PROCESSOR x86_64) iotjs-1.0+715/cmake/config/x86_64-linux.cmake000066400000000000000000000012601371177304000204360ustar00rootroot00000000000000# 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. set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCESSOR x86_64) iotjs-1.0+715/cmake/config/x86_64-mock.cmake000066400000000000000000000012641371177304000202340ustar00rootroot00000000000000# Copyright 2018-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. set(CMAKE_SYSTEM_NAME MockLinux) set(CMAKE_SYSTEM_PROCESSOR x86_64) iotjs-1.0+715/cmake/config/x86_64-windows.cmake000066400000000000000000000013561371177304000207770ustar00rootroot00000000000000# 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. set(CMAKE_SYSTEM_NAME Windows) set(CMAKE_SYSTEM_PROCESSOR x64) set(CMAKE_C_COMPILER CL.exe) set(CMAKE_C_COMPILER_WORKS TRUE) iotjs-1.0+715/cmake/http-parser.cmake000066400000000000000000000034101371177304000173460ustar00rootroot00000000000000# 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. cmake_minimum_required(VERSION 2.8) if("${TARGET_OS}" MATCHES "NUTTX|TIZENRT") set(HTTPPARSER_NUTTX_ARG -DNUTTX_HOME=${TARGET_SYSTEMROOT}) endif() build_lib_name(HTTPPARSER_NAME httpparser) set(DEPS_HTTPPARSER deps/http-parser) set(DEPS_HTTPPARSER_SRC ${ROOT_DIR}/${DEPS_HTTPPARSER}/) ExternalProject_Add(http-parser PREFIX ${DEPS_HTTPPARSER} SOURCE_DIR ${DEPS_HTTPPARSER_SRC} BUILD_IN_SOURCE 0 BINARY_DIR ${DEPS_HTTPPARSER} INSTALL_COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_BINARY_DIR}/${DEPS_HTTPPARSER}/${CONFIG_TYPE}/ ${CMAKE_BINARY_DIR}/lib/ CMAKE_ARGS -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE} -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS} -DOS=${TARGET_OS} ${HTTPPARSER_NUTTX_ARG} -DENABLE_MEMORY_CONSTRAINTS=ON ) add_library(libhttp-parser STATIC IMPORTED) add_dependencies(libhttp-parser http-parser) set_property(TARGET libhttp-parser PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/lib/${HTTPPARSER_NAME}) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${CMAKE_BINARY_DIR}/lib/${HTTPPARSER_NAME}) set(HTTPPARSER_INCLUDE_DIR ${DEPS_HTTPPARSER_SRC}) iotjs-1.0+715/cmake/iotjs.cmake000066400000000000000000000470111371177304000162320ustar00rootroot00000000000000# 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. cmake_minimum_required(VERSION 2.8) if(NOT DEFINED PYTHON) set(PYTHON "python") endif() include(${CMAKE_CURRENT_LIST_DIR}/JSONParser.cmake) set(IOTJS_SOURCE_DIR ${CMAKE_SOURCE_DIR}/src) # Platform configuration # Look for files under src/platform// string(TOLOWER ${CMAKE_SYSTEM_NAME} IOTJS_SYSTEM_OS) set(PLATFORM_OS_DIR "${IOTJS_SOURCE_DIR}/platform/${IOTJS_SYSTEM_OS}") file(GLOB IOTJS_PLATFORM_SRC "${PLATFORM_OS_DIR}/iotjs_*.c") # Module configuration - listup all possible native C modules function(getListOfVars prefix pattern varResult) set(moduleNames) get_cmake_property(vars VARIABLES) string(REPLACE "." "\\." prefix ${prefix}) foreach(var ${vars}) string(REGEX MATCH "(^|;)${prefix}${pattern}($|;)" matchedVar "${var}") if(matchedVar) list(APPEND moduleNames ${CMAKE_MATCH_2}) endif() endforeach() list(REMOVE_DUPLICATES moduleNames) set(${varResult} ${moduleNames} PARENT_SCOPE) endfunction() function(addModuleDependencies module varResult) string(TOUPPER ${module} MODULE) set(moduleDefines) set(MODULE_PREFIX ${IOTJS_MODULE_${MODULE}_JSON}.modules.${module}) if(NOT "${${MODULE_PREFIX}.require}" STREQUAL "") foreach(idx ${${MODULE_PREFIX}.require}) set(dependency ${${MODULE_PREFIX}.require_${idx}}) string(TOUPPER ${dependency} DEPENDENCY) if(NOT ${ENABLE_MODULE_${DEPENDENCY}}) list(APPEND moduleDefines ENABLE_MODULE_${DEPENDENCY}) addModuleDependencies(${dependency} deps) list(APPEND varResult ${deps}) list(REMOVE_DUPLICATES varResult) endif() endforeach() endif() set(PLATFORM_REQUIRE_PREFIX ${MODULE_PREFIX}.platforms.${IOTJS_SYSTEM_OS}) foreach(idx ${${PLATFORM_REQUIRE_PREFIX}.require}) set(dependency ${${PLATFORM_REQUIRE_PREFIX}.require_${idx}}) string(TOUPPER ${dependency} DEPENDENCY) if (NOT ${ENABLE_MODULE_${DEPENDENCY}}) list(APPEND moduleDefines ENABLE_MODULE_${DEPENDENCY}) addModuleDependencies(${dependency} deps) list(APPEND varResult ${deps}) list(REMOVE_DUPLICATES varResult) endif() endforeach() set(${varResult} ${moduleDefines} PARENT_SCOPE) endfunction() # Set the default profile if not specified set(IOTJS_PROFILE "${CMAKE_SOURCE_DIR}/profiles/default.profile" CACHE STRING "Path to profile.") if(NOT IS_ABSOLUTE ${IOTJS_PROFILE}) set(IOTJS_PROFILE "${CMAKE_SOURCE_DIR}/${IOTJS_PROFILE}") endif() # Enable the modules defined by the profile if(EXISTS ${IOTJS_PROFILE}) file(READ "${IOTJS_PROFILE}" PROFILE_SETTINGS) string(REGEX REPLACE "^#.*$" "" PROFILE_SETTINGS "${PROFILE_SETTINGS}") string(REGEX REPLACE "[\r|\n]" ";" PROFILE_SETTINGS "${PROFILE_SETTINGS}") foreach(module_define ${PROFILE_SETTINGS}) set(${module_define} ON CACHE BOOL "ON/OFF") endforeach() else() message(FATAL_ERROR "Profile file: '${IOTJS_PROFILE}' doesn't exist!") endif() set(IOTJS_MODULES) set(MODULES_INCLUDE_DIR) # Add the basic descriptor file (src/modules.json) list(APPEND EXTERNAL_MODULES ${IOTJS_SOURCE_DIR}) set(iotjs_module_idx 0) foreach(module_descriptor ${EXTERNAL_MODULES}) get_filename_component(MODULE_DIR ${module_descriptor} ABSOLUTE) if(NOT EXISTS "${MODULE_DIR}/modules.json") message(FATAL_ERROR "The modules.json file doesn't exist in ${MODULE_DIR}") endif() list(APPEND MODULES_INCLUDE_DIR ${MODULE_DIR}) list(APPEND IOTJS_MODULES_JSONS "${iotjs_module_idx}") set(CURR_JSON "IOTJS_MODULES_JSON_${iotjs_module_idx}") set(${CURR_JSON}_PATH ${MODULE_DIR}) file(READ "${MODULE_DIR}/modules.json" IOTJS_MODULES_JSON_FILE) sbeParseJson(${CURR_JSON} IOTJS_MODULES_JSON_FILE) getListOfVars("${CURR_JSON}.modules." "([A-Za-z0-9_]+)[A-Za-z0-9_.]*" _IOTJS_MODULES) list(APPEND IOTJS_MODULES ${_IOTJS_MODULES}) foreach(module ${_IOTJS_MODULES}) string(TOUPPER ${module} MODULE) set(IOTJS_MODULE_${MODULE}_JSON ${CURR_JSON}) endforeach() math(EXPR iotjs_module_idx "${iotjs_module_idx} + 1") endforeach(module_descriptor) list(REMOVE_DUPLICATES IOTJS_MODULES) # Turn off the other modules foreach(module ${IOTJS_MODULES}) string(TOUPPER ${module} MODULE) set(ENABLE_MODULE_${MODULE} OFF CACHE BOOL "ON/OFF") endforeach() # Resolve the dependencies and set the ENABLE_MODULE_[NAME] variables foreach(module ${IOTJS_MODULES}) string(TOUPPER ${module} MODULE) if(${ENABLE_MODULE_${MODULE}}) addModuleDependencies(${module} deps) foreach(module_define ${deps}) set(${module_define} ON) endforeach() unset(deps) endif() endforeach() set(IOTJS_JS_MODULES) set(IOTJS_JS_MODULE_SRC) set(IOTJS_NATIVE_MODULES) set(IOTJS_NATIVE_MODULE_SRC) set(IOTJS_MODULE_DEFINES) message("IoT.js module configuration:") getListOfVars("ENABLE_MODULE_" "([A-Za-z0-9_]+)" IOTJS_ENABLED_MODULES) foreach(MODULE ${IOTJS_ENABLED_MODULES}) set(MODULE_DEFINE_VAR "ENABLE_MODULE_${MODULE}") message(STATUS "${MODULE_DEFINE_VAR} = ${${MODULE_DEFINE_VAR}}") # Set the defines for build if(${MODULE_DEFINE_VAR}) list(APPEND IOTJS_MODULE_DEFINES "-D${MODULE_DEFINE_VAR}=1") else() list(APPEND IOTJS_MODULE_DEFINES "-D${MODULE_DEFINE_VAR}=0") endif() endforeach() set(EXTRA_CMAKE_FILES) # Collect the files of enabled modules foreach(MODULE ${IOTJS_ENABLED_MODULES}) if(${ENABLE_MODULE_${MODULE}}) string(TOLOWER ${MODULE} module) set(IOTJS_MODULES_JSON ${IOTJS_MODULE_${MODULE}_JSON}) set(MODULE_BASE_DIR ${${IOTJS_MODULES_JSON}_PATH}) set(MODULE_PREFIX ${IOTJS_MODULES_JSON}.modules.${module}.) # Add js source set(MODULE_JS_FILE ${${MODULE_PREFIX}js_file}) if(NOT "${MODULE_JS_FILE}" STREQUAL "") set(JS_PATH "${MODULE_BASE_DIR}/${MODULE_JS_FILE}") if(EXISTS "${JS_PATH}") list(APPEND IOTJS_JS_MODULES "${module}=${JS_PATH}") list(APPEND IOTJS_JS_MODULE_SRC ${JS_PATH}) else() message(FATAL_ERROR "JS file doesn't exist: ${JS_PATH}") endif() endif() # Check extra cmake file set(EXTRA_CMAKE_FILE ${${MODULE_PREFIX}cmakefile}) if(NOT "${EXTRA_CMAKE_FILE}" STREQUAL "") set(EXTRA_CMAKE_FILE_PATH "${MODULE_BASE_DIR}/${EXTRA_CMAKE_FILE}") if(EXISTS "${EXTRA_CMAKE_FILE_PATH}") list(APPEND EXTRA_CMAKE_FILES "${EXTRA_CMAKE_FILE_PATH}") else() message(FATAL_ERROR "CMake file doesn't exists: ${EXTRA_CMAKE_FILE_PATH}") endif() endif() # Add platform-related native source if(NOT "${${MODULE_PREFIX}native_files}" STREQUAL "" AND NOT "${${MODULE_PREFIX}init}" STREQUAL "") list(APPEND IOTJS_NATIVE_MODULES "${MODULE}") endif() # Add common native source foreach(idx ${${MODULE_PREFIX}native_files}) set(MODULE_C_FILE ${${MODULE_PREFIX}native_files_${idx}}) set(MODULE_C_FILE "${MODULE_BASE_DIR}/${MODULE_C_FILE}") if(EXISTS "${MODULE_C_FILE}") list(APPEND IOTJS_NATIVE_MODULE_SRC ${MODULE_C_FILE}) else() message(FATAL_ERROR "C file doesn't exist: ${MODULE_C_FILE}") endif() endforeach() # Add external libraries foreach(idx ${${MODULE_PREFIX}external_libs}) list(APPEND EXTERNAL_LIBS ${${MODULE_PREFIX}external_libs_${idx}}) endforeach() getListOfVars("${MODULE_PREFIX}" "([A-Za-z0-9_]+[A-Za-z])[A-Za-z0-9_.]*" MODULE_KEYS) list(FIND MODULE_KEYS "platforms" PLATFORMS_KEY) set(PLATFORMS_PREFIX ${MODULE_PREFIX}platforms.) if(${PLATFORMS_KEY} GREATER -1) getListOfVars("${PLATFORMS_PREFIX}" "([A-Za-z0-9_]+[A-Za-z])[A-Za-z0-9_.]*" MODULE_PLATFORMS) list(FIND MODULE_PLATFORMS ${IOTJS_SYSTEM_OS} PLATFORM_NATIVES) # Add plaform-dependant information if(${PLATFORM_NATIVES} GREATER -1) # native source if exists... foreach(idx ${${PLATFORMS_PREFIX}${IOTJS_SYSTEM_OS}.native_files}) set(MODULE_PLATFORM_FILE ${${PLATFORMS_PREFIX}${IOTJS_SYSTEM_OS}.native_files_${idx}}) set(MODULE_PLATFORM_FILE "${MODULE_BASE_DIR}/${MODULE_PLATFORM_FILE}") if(EXISTS "${MODULE_PLATFORM_FILE}") list(APPEND IOTJS_NATIVE_MODULE_SRC ${MODULE_PLATFORM_FILE}) else() message(FATAL_ERROR "C file doesn't exist: ${MODULE_PLATFORM_FILE}") endif() endforeach() # external libraries.... foreach(idx ${${PLATFORMS_PREFIX}${IOTJS_SYSTEM_OS}.external_libs}) list(APPEND EXTERNAL_LIBS ${${PLATFORMS_PREFIX}${IOTJS_SYSTEM_OS}.external_libs_${idx}}) endforeach() # ...otherwise from 'undefined' section. else() # add native files foreach(idx ${${PLATFORMS_PREFIX}undefined.native_files}) set(MODULE_UNDEFINED_FILE "${${MODULE_PREFIX}undefined.native_files_${idx}}") set(MODULE_UNDEFINED_FILE "${MODULE_BASE_DIR}/${MODULE_UNDEFINED_FILE}") if(EXISTS "${MODULE_UNDEFINED_FILE}") list(APPEND IOTJS_NATIVE_MODULE_SRC ${MODULE_UNDEFINED_FILE}) else() message(FATAL_ERROR "${MODULE_UNDEFINED_FILE} does not exists.") endif() endforeach() # external libraries.... foreach(idx ${${PLATFORMS_PREFIX}undefined.external_libs}) list(APPEND EXTERNAL_LIBS ${${PLATFORMS_PREFIX}undefined.external_libs_${idx}}) endforeach() endif() endif() endif() endforeach(MODULE) list(APPEND IOTJS_JS_MODULES "iotjs=${IOTJS_SOURCE_DIR}/js/iotjs.js") # Generate src/iotjs_module_inl.h # Build up init function prototypes set(IOTJS_MODULE_INITIALIZERS "") foreach(MODULE ${IOTJS_NATIVE_MODULES}) set(IOTJS_MODULES_JSON ${IOTJS_MODULE_${MODULE}_JSON}) string(TOLOWER ${MODULE} module) set(IOTJS_MODULE_INITIALIZERS "${IOTJS_MODULE_INITIALIZERS} extern jerry_value_t ${${IOTJS_MODULES_JSON}.modules.${module}.init}(void);") endforeach() # Build up module entries set(IOTJS_MODULE_ENTRIES "") set(IOTJS_MODULE_OBJECTS "") foreach(MODULE ${IOTJS_NATIVE_MODULES}) set(IOTJS_MODULES_JSON ${IOTJS_MODULE_${MODULE}_JSON}) string(TOLOWER ${MODULE} module) set(INIT_FUNC ${${IOTJS_MODULES_JSON}.modules.${module}.init}) set(IOTJS_MODULE_ENTRIES "${IOTJS_MODULE_ENTRIES} { \"${module}\", ${INIT_FUNC} },") set(IOTJS_MODULE_OBJECTS "${IOTJS_MODULE_OBJECTS} { 0 },") endforeach() # Build up the contents of src/iotjs_module_inl.h list(LENGTH IOTJS_NATIVE_MODULES IOTJS_MODULE_COUNT) set(IOTJS_MODULE_INL_H "/* File generated via iotjs.cmake */ ${IOTJS_MODULE_INITIALIZERS} const unsigned iotjs_module_count = ${IOTJS_MODULE_COUNT}; const iotjs_module_ro_data_t iotjs_module_ro_data[${IOTJS_MODULE_COUNT}] = { ${IOTJS_MODULE_ENTRIES} }; iotjs_module_rw_data_t iotjs_module_rw_data[${IOTJS_MODULE_COUNT}] = { ${IOTJS_MODULE_OBJECTS} }; ") file(WRITE ${IOTJS_SOURCE_DIR}/iotjs_module_inl.h "${IOTJS_MODULE_INL_H}") # Cleanup unset(IOTJS_MODULE_INL_H) unset(IOTJS_MODULES_JSON_FILE) foreach(idx ${IOTJS_MODULES_JSONS}) sbeClearJson(IOTJS_MODULES_JSON_${idx}) unset(IOTJS_MODULES_JSON_${idx}_PATH) endforeach() foreach(module ${IOTJS_MODULES}) string(TOUPPER ${module} MODULE) unset(IOTJS_MODULE_${MODULE}_JSON) endforeach() # Common compile flags iotjs_add_compile_flags(-Wall) if(NOT USING_MSVC) iotjs_add_compile_flags(-Wextra -Werror -Wno-unused-parameter) iotjs_add_compile_flags(-Wsign-conversion -std=gnu99) endif() if(ENABLE_SNAPSHOT) set(JS2C_SNAPSHOT_ARG --snapshot-tool=${JERRY_HOST_SNAPSHOT}) iotjs_add_compile_flags(-DENABLE_SNAPSHOT) endif() if (EXPOSE_GC) iotjs_add_compile_flags(-DEXPOSE_GC) endif() # Run js2c set(JS2C_RUN_MODE "release") if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") set(JS2C_RUN_MODE "debug") endif() if(USING_MSVC) set(JS2C_PREPROCESS_ARGS /EP /d1PP) else() set(JS2C_PREPROCESS_ARGS -E -dD) endif() string (REPLACE ";" "," IOTJS_JS_MODULES_STR "${IOTJS_JS_MODULES}") add_custom_command( OUTPUT ${IOTJS_SOURCE_DIR}/iotjs_js.c ${IOTJS_SOURCE_DIR}/iotjs_js.h COMMAND ${CMAKE_C_COMPILER} ${JS2C_PREPROCESS_ARGS} ${IOTJS_MODULE_DEFINES} ${IOTJS_SOURCE_DIR}/iotjs_magic_strings.h > ${IOTJS_SOURCE_DIR}/iotjs_magic_strings.in COMMAND ${PYTHON} ${ROOT_DIR}/tools/js2c.py ARGS --buildtype=${JS2C_RUN_MODE} --modules "${IOTJS_JS_MODULES_STR}" ${JS2C_SNAPSHOT_ARG} COMMAND ${CMAKE_COMMAND} -E remove -f ${IOTJS_SOURCE_DIR}/iotjs_magic_strings.in DEPENDS ${ROOT_DIR}/tools/js2c.py jerry-snapshot ${IOTJS_JS_MODULE_SRC} ) # Load all external module cmake files foreach(MODULE_EXTRA_CMAKE_FILE ${EXTRA_CMAKE_FILES}) message("Using CMake file: ${MODULE_EXTRA_CMAKE_FILE}") set(MODULE_BINARY_DIR ${CMAKE_BINARY_DIR}/external/) set(MODULE_LIBS) get_filename_component(MODULE_DIR ${MODULE_EXTRA_CMAKE_FILE} DIRECTORY) # Variables which should be used by the external module(s): # - MODULE_DIR - the modules root directory # - MODULE_BINARY_DIR - the build directory for the current module # - MODULE_LIBS - list of libraries to use during linking (set this) include(${MODULE_EXTRA_CMAKE_FILE}) if (NOT MODULE_NAME) message(FATAL_ERROR "MODULE_NAME was not specified in ${MODULE_EXTRA_CMAKE_FILE}") endif() list(APPEND EXTERNAL_LIBS ${MODULE_LIBS}) # Just to make sure it will always be unset unset(MODULE_NAME) # This is usually set by the included cmake file unset(MODULE_BINARY_DIR) unset(MODULE_LIBS) endforeach() # Collect all sources into LIB_IOTJS_SRC file(GLOB LIB_IOTJS_SRC ${IOTJS_SOURCE_DIR}/*.c) list(APPEND LIB_IOTJS_SRC ${IOTJS_SOURCE_DIR}/iotjs_js.c ${IOTJS_SOURCE_DIR}/iotjs_js.h ${IOTJS_NATIVE_MODULE_SRC} ${IOTJS_PLATFORM_SRC} ) separate_arguments(EXTERNAL_INCLUDE_DIR) separate_arguments(EXTERNAL_LIBS) set(IOTJS_INCLUDE_DIRS ${EXTERNAL_INCLUDE_DIR} ${ROOT_DIR}/include ${IOTJS_SOURCE_DIR} ${MODULES_INCLUDE_DIR} ${PLATFORM_OS_DIR} ${JERRY_PORT_DIR}/include ${JERRY_EXT_DIR}/include ${JERRY_INCLUDE_DIR} ${HTTPPARSER_INCLUDE_DIR} ${MBEDTLS_INCLUDE_DIR} ${TUV_INCLUDE_DIR} ) if(NOT BUILD_LIB_ONLY) if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin") iotjs_add_link_flags("-Xlinker -map -Xlinker iotjs.map") elseif(USING_MSVC) iotjs_add_link_flags("/MAP:iotjs.map") else() iotjs_add_link_flags("-Xlinker -Map -Xlinker iotjs.map") endif() endif() # Print out some configs message("IoT.js configured with:") message(STATUS "BUILD_LIB_ONLY ${BUILD_LIB_ONLY}") message(STATUS "CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE}") message(STATUS "CMAKE_C_FLAGS ${CMAKE_C_FLAGS}") message(STATUS "CMAKE_TOOLCHAIN_FILE ${CMAKE_TOOLCHAIN_FILE}") message(STATUS "ENABLE_LTO ${ENABLE_LTO}") message(STATUS "ENABLE_SNAPSHOT ${ENABLE_SNAPSHOT}") message(STATUS "EXPOSE_GC ${EXPOSE_GC}") message(STATUS "EXTERNAL_INCLUDE_DIR ${EXTERNAL_INCLUDE_DIR}") message(STATUS "EXTERNAL_LIBC_INTERFACE ${EXTERNAL_LIBC_INTERFACE}") message(STATUS "EXTERNAL_LIBS ${EXTERNAL_LIBS}") message(STATUS "EXTERNAL_MODULES ${EXTERNAL_MODULES}") message(STATUS "IOTJS_LINKER_FLAGS ${IOTJS_LINKER_FLAGS}") message(STATUS "IOTJS_PROFILE ${IOTJS_PROFILE}") message(STATUS "JERRY_DEBUGGER ${JERRY_DEBUGGER}") message(STATUS "JERRY_GLOBAL_HEAP_SIZE ${JERRY_GLOBAL_HEAP_SIZE}") message(STATUS "JERRY_MEM_STATS ${JERRY_MEM_STATS}") message(STATUS "JERRY_PROFILE ${JERRY_PROFILE}") message(STATUS "TARGET_ARCH ${TARGET_ARCH}") message(STATUS "TARGET_BOARD ${TARGET_BOARD}") message(STATUS "TARGET_OS ${TARGET_OS}") message(STATUS "TARGET_SYSTEMROOT ${TARGET_SYSTEMROOT}") iotjs_add_compile_flags(${IOTJS_MODULE_DEFINES}) if(JERRY_DEBUGGER) iotjs_add_compile_flags("-DJERRY_DEBUGGER") endif() file(GLOB IOTJS_HEADERS "${ROOT_DIR}/src/*.h") file(GLOB JERRY_HEADERS "${ROOT_DIR}/deps/jerry/jerry-core/include/*.h") file(GLOB LIBUV_HEADERS "${ROOT_DIR}/deps/libtuv/include/*.h") set(IOTJS_PUBLIC_HEADERS "include/iotjs.h" "include/node_api.h" "include/node_api_types.h" ${IOTJS_HEADERS} ${JERRY_HEADERS} ${LIBUV_HEADERS} ) # Configure the libiotjs set(TARGET_LIB_IOTJS libiotjs) if(CREATE_SHARED_LIB) add_library(${TARGET_LIB_IOTJS} SHARED ${LIB_IOTJS_SRC}) else() add_library(${TARGET_LIB_IOTJS} STATIC ${LIB_IOTJS_SRC}) # FIXME: module specific condition should not be in the main cmake if(${ENABLE_MODULE_NAPI}) # Some tests require the GC to be exposed iotjs_add_compile_flags(-DEXPOSE_GC) # Force symbols to be entered in the output file as undefined symbols. file(READ "${IOTJS_SOURCE_DIR}/napi/node_symbols.txt" NODE_SYMBOLS) string(REGEX REPLACE "[\r|\n]" ";" NODE_SYMBOLS "${NODE_SYMBOLS}") if(USING_MSVC) set(NODE_SYMBOL_SEPARATOR " /INCLUDE:") if("${TARGET_ARCH}" STREQUAL "i686") set(NODE_SYMBOL_SEPARATOR "${NODE_SYMBOL_SEPARATOR}_") endif() else() set(NODE_SYMBOLS_LINK_FLAGS "-Wl") set(NODE_SYMBOL_SEPARATOR ",-u,") endif() foreach(NODE_SYMBOL ${NODE_SYMBOLS}) set(NODE_SYMBOLS_LINK_FLAGS "${NODE_SYMBOLS_LINK_FLAGS}${NODE_SYMBOL_SEPARATOR}${NODE_SYMBOL}") endforeach() iotjs_add_link_flags(${NODE_SYMBOLS_LINK_FLAGS}) endif() endif(CREATE_SHARED_LIB) add_dependencies(${TARGET_LIB_IOTJS} ${JERRY_LIBS} ${TUV_LIBS} libhttp-parser ${MBEDTLS_LIBS} ) set_target_properties(${TARGET_LIB_IOTJS} PROPERTIES OUTPUT_NAME iotjs ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" PUBLIC_HEADER "${IOTJS_PUBLIC_HEADERS}" ) target_include_directories(${TARGET_LIB_IOTJS} PRIVATE ${IOTJS_INCLUDE_DIRS}) target_link_libraries(${TARGET_LIB_IOTJS} ${CMAKE_DL_LIBS} ${JERRY_LIBS} ${TUV_LIBS} libhttp-parser ${MBEDTLS_LIBS} ${EXTERNAL_LIBS} ) if("${LIB_INSTALL_DIR}" STREQUAL "") set(LIB_INSTALL_DIR "lib") endif() if("${BIN_INSTALL_DIR}" STREQUAL "") set(BIN_INSTALL_DIR "bin") endif() # Configure the iotjs executable if(NOT BUILD_LIB_ONLY) set(TARGET_IOTJS iotjs) message(STATUS "CMAKE_BINARY_DIR ${CMAKE_BINARY_DIR}") message(STATUS "BINARY_INSTALL_DIR ${INSTALL_PREFIX}/bin") message(STATUS "LIBRARY_INSTALL_DIR ${INSTALL_PREFIX}/lib") add_executable(${TARGET_IOTJS} ${ROOT_DIR}/src/platform/linux/iotjs_linux.c) set_target_properties(${TARGET_IOTJS} PROPERTIES LINK_FLAGS "${IOTJS_LINKER_FLAGS}" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" ) target_include_directories(${TARGET_IOTJS} PRIVATE ${IOTJS_INCLUDE_DIRS}) target_link_libraries(${TARGET_IOTJS} ${TARGET_LIB_IOTJS}) install(TARGETS ${TARGET_IOTJS} RUNTIME DESTINATION "${INSTALL_PREFIX}/bin" LIBRARY DESTINATION "${INSTALL_PREFIX}/lib" PUBLIC_HEADER DESTINATION "${INSTALL_PREFIX}/include/iotjs") if(CREATE_SHARED_LIB) install(TARGETS ${TARGET_LIB_IOTJS} RUNTIME DESTINATION "${INSTALL_PREFIX}/bin" LIBRARY DESTINATION "${INSTALL_PREFIX}/lib" PUBLIC_HEADER DESTINATION "${INSTALL_PREFIX}/include/iotjs") endif() else() install(TARGETS ${TARGET_LIB_IOTJS} DESTINATION ${LIB_INSTALL_DIR}) endif() iotjs-1.0+715/cmake/jerry.cmake000066400000000000000000000147301371177304000162370ustar00rootroot00000000000000# 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. cmake_minimum_required(VERSION 2.8) # Host jerry for snapshot generation set(DEPS_HOST_JERRY deps/jerry-host) ExternalProject_Add(hostjerry PREFIX ${DEPS_HOST_JERRY} SOURCE_DIR ${ROOT_DIR}/deps/jerry/ BUILD_IN_SOURCE 0 BINARY_DIR ${DEPS_HOST_JERRY} CMAKE_ARGS -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/${DEPS_HOST_JERRY} -DENABLE_ALL_IN_ONE=ON -DENABLE_LTO=${ENABLE_LTO} -DJERRY_CMDLINE=OFF -DJERRY_CMDLINE_SNAPSHOT=ON -DJERRY_EXT=ON -DJERRY_LOGGING=ON -DJERRY_ERROR_MESSAGES=ON -DJERRY_SNAPSHOT_SAVE=${ENABLE_SNAPSHOT} -DJERRY_PROFILE=${JERRY_PROFILE} ${EXTRA_JERRY_CMAKE_PARAMS} # The snapshot tool does not require the system allocator # turn it off by default. # # Additionally this is required if one compiles on a # 64bit system to a 32bit system with system allocator # enabled. This is beacuse on 64bit the system allocator # should not be used as it returns 64bit pointers which # can not be represented correctly in the JerryScript engine # currently. -DJERRY_SYSTEM_ALLOCATOR=OFF ) set(JERRY_HOST_SNAPSHOT ${CMAKE_BINARY_DIR}/${DEPS_HOST_JERRY}/bin/jerry-snapshot) add_executable(jerry-snapshot IMPORTED) add_dependencies(jerry-snapshot hostjerry) set_property(TARGET jerry-snapshot PROPERTY IMPORTED_LOCATION ${JERRY_HOST_SNAPSHOT}) # Utility method to add -D= macro(add_cmake_arg TARGET_ARG KEY) if(${KEY}) list(APPEND ${TARGET_ARG} -D${KEY}=${${KEY}}) endif() endmacro(add_cmake_arg) # Target libjerry set(JERRY_LIBS jerry-core jerry-port-default jerry-ext) set(DEPS_LIB_JERRY_ARGS) # Configure the MinSizeRel as the default build type # for target jerry in release mode. if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") set(JERRY_CMAKE_BUILD_TYPE MinSizeRel) else() set(JERRY_CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE}) endif() # use system libm on Unix like targets if("${TARGET_OS}" MATCHES "TIZENRT|NUTTX") list(APPEND JERRY_LIBS jerry-libm) list(APPEND DEPS_LIB_JERRY_ARGS -DJERRY_LIBM=ON -DEXTERNAL_CMAKE_SYSTEM_PROCESSOR=${EXTERNAL_CMAKE_SYSTEM_PROCESSOR} ) elseif("${TARGET_OS}" MATCHES "LINUX|TIZEN|DARWIN|OPENWRT") list(APPEND JERRY_LIBS m) list(APPEND DEPS_LIB_JERRY_ARGS -DJERRY_LIBM=OFF) elseif("${TARGET_OS}" MATCHES "WINDOWS") list(APPEND DEPS_LIB_JERRY_ARGS -DJERRY_LIBM=OFF) else() list(APPEND JERRY_LIBS jerry-libm) list(APPEND DEPS_LIB_JERRY_ARGS -DEXTERNAL_CMAKE_SYSTEM_PROCESSOR=${EXTERNAL_CMAKE_SYSTEM_PROCESSOR} ) endif() # Add a few cmake options based on buildtype/external cmake defines if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") list(APPEND DEPS_LIB_JERRY_ARGS -DJERRY_ERROR_MESSAGES=ON) endif() # NuttX is not using the default port implementation of JerryScript if("${TARGET_OS}" MATCHES "NUTTX|TIZENRT") list(APPEND DEPS_LIB_JERRY_ARGS -DJERRY_PORT_DEFAULT=OFF) else() list(APPEND DEPS_LIB_JERRY_ARGS -DJERRY_PORT_DEFAULT=ON) endif() add_cmake_arg(DEPS_LIB_JERRY_ARGS ENABLE_LTO) add_cmake_arg(DEPS_LIB_JERRY_ARGS JERRY_MEM_STATS) add_cmake_arg(DEPS_LIB_JERRY_ARGS JERRY_ERROR_MESSAGES) add_cmake_arg(DEPS_LIB_JERRY_ARGS JERRY_DEBUGGER) add_cmake_arg(DEPS_LIB_JERRY_ARGS JERRY_GLOBAL_HEAP_SIZE) add_cmake_arg(DEPS_LIB_JERRY_ARGS JERRY_ATTR_GLOBAL_HEAP) separate_arguments(EXTRA_JERRY_CMAKE_PARAMS) build_lib_name(JERRY_CORE_NAME jerry-core) build_lib_name(JERRY_LIBM_NAME jerry-libm) build_lib_name(JERRY_EXT_NAME jerry-ext) set(DEPS_LIB_JERRY deps/jerry) set(DEPS_LIB_JERRY_SRC ${ROOT_DIR}/${DEPS_LIB_JERRY}) ExternalProject_Add(libjerry PREFIX ${DEPS_LIB_JERRY} SOURCE_DIR ${ROOT_DIR}/deps/jerry/ BUILD_IN_SOURCE 0 BINARY_DIR ${DEPS_LIB_JERRY} INSTALL_COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_BINARY_DIR}/${DEPS_LIB_JERRY}/lib/${CONFIG_TYPE} ${CMAKE_BINARY_DIR}/lib/ CMAKE_ARGS -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE} -DCMAKE_BUILD_TYPE=${JERRY_CMAKE_BUILD_TYPE} -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS} -DENABLE_ALL_IN_ONE=ON -DJERRY_CMDLINE=OFF -DJERRY_SNAPSHOT_EXEC=${ENABLE_SNAPSHOT} -DJERRY_SNAPSHOT_SAVE=OFF -DJERRY_PROFILE=${JERRY_PROFILE} -DJERRY_LOGGING=ON -DJERRY_LINE_INFO=${JERRY_LINE_INFO} -DJERRY_VM_EXEC_STOP=ON -DJERRY_ERROR_MESSAGES=ON -DENABLE_LTO=${ENABLE_LTO} ${DEPS_LIB_JERRY_ARGS} ${EXTRA_JERRY_CMAKE_PARAMS} ) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${CMAKE_BINARY_DIR}/lib/${JERRY_CORE_NAME} ${CMAKE_BINARY_DIR}/lib/${JERRY_LIBM_NAME} ${CMAKE_BINARY_DIR}/lib/${JERRY_EXT_NAME} ) # define external jerry-core target add_library(jerry-core STATIC IMPORTED) add_dependencies(jerry-core libjerry) set_property(TARGET jerry-core PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/lib/${JERRY_CORE_NAME}) # define external jerry-libm target add_library(jerry-libm STATIC IMPORTED) add_dependencies(jerry-libm libjerry) set_property(TARGET jerry-libm PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/lib/${JERRY_LIBM_NAME}) # define external jerry-ext target add_library(jerry-ext STATIC IMPORTED) add_dependencies(jerry-ext libjerry) set_property(TARGET jerry-ext PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/lib/${JERRY_EXT_NAME}) if(NOT "${TARGET_OS}" MATCHES "NUTTX|TIZENRT") build_lib_name(JERRY_PORT_NAME jerry-port) build_lib_name(JERRY_PORT_DEFAULT_NAME jerry-port-default) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${CMAKE_BINARY_DIR}/lib/${JERRY_PORT_NAME} ) # define external jerry-port-default target add_library(jerry-port-default STATIC IMPORTED) add_dependencies(jerry-port-default libjerry) set_property(TARGET jerry-port-default PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/lib/${JERRY_PORT_DEFAULT_NAME}) set(JERRY_PORT_DIR ${DEPS_LIB_JERRY_SRC}/jerry-port/default) endif() set(JERRY_INCLUDE_DIR ${DEPS_LIB_JERRY_SRC}/jerry-core/include) set(JERRY_EXT_DIR ${DEPS_LIB_JERRY_SRC}/jerry-ext) iotjs-1.0+715/cmake/libtuv.cmake000066400000000000000000000044671371177304000164170ustar00rootroot00000000000000# 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. cmake_minimum_required(VERSION 2.8) # Configure external libtuv set(DEPS_TUV deps/libtuv) set(DEPS_TUV_SRC ${ROOT_DIR}/${DEPS_TUV}) build_lib_name(LIBTUV_NAME tuv) if("${TARGET_OS}" STREQUAL "MOCK") string(TOLOWER ${TARGET_ARCH}-linux PLATFORM_DESCRIPTOR) else() string(TOLOWER ${TARGET_ARCH}-${TARGET_OS} PLATFORM_DESCRIPTOR) endif() set(DEPS_TUV_TOOLCHAIN ${DEPS_TUV_SRC}/cmake/config/config_${PLATFORM_DESCRIPTOR}.cmake) message(STATUS "libtuv toolchain file: ${DEPS_TUV_TOOLCHAIN}") ExternalProject_Add(libtuv PREFIX ${DEPS_TUV} SOURCE_DIR ${DEPS_TUV_SRC} BUILD_IN_SOURCE 0 BINARY_DIR ${DEPS_TUV} INSTALL_COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_BINARY_DIR}/${DEPS_TUV}/lib/${CONFIG_TYPE}/ ${CMAKE_BINARY_DIR}/lib/ CMAKE_ARGS -DCMAKE_TOOLCHAIN_FILE=${DEPS_TUV_TOOLCHAIN} -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS} -DTARGET_PLATFORM=${PLATFORM_DESCRIPTOR} -DLIBTUV_CUSTOM_LIB_OUT=lib -DBUILDTESTER=NO -DBUILDAPIEMULTESTER=NO -DTARGET_SYSTEMROOT=${TARGET_SYSTEMROOT} -DTARGET_BOARD=${TARGET_BOARD} ) add_library(tuv STATIC IMPORTED) add_dependencies(tuv libtuv) set_property(TARGET tuv PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/lib/${LIBTUV_NAME}) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${CMAKE_BINARY_DIR}/lib/${LIBTUV_NAME}) set(TUV_INCLUDE_DIR ${DEPS_TUV_SRC}/include) set(TUV_LIBS tuv) if("${TARGET_OS}" STREQUAL "MOCK" OR "${TARGET_OS}" STREQUAL "LINUX") list(APPEND TUV_LIBS pthread) elseif("${TARGET_OS}" STREQUAL "WINDOWS") list(APPEND TUV_LIBS ws2_32.lib UserEnv.lib advapi32.lib iphlpapi.lib psapi.lib shell32.lib) endif() iotjs-1.0+715/cmake/mbedtls.cmake000066400000000000000000000073141371177304000165360ustar00rootroot00000000000000# 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. cmake_minimum_required(VERSION 2.8) set(MODULE_NAME "tls") if ("${TARGET_OS}" STREQUAL "TIZENRT") set(MBEDTLS_LIBS "") set(MBEDTLS_INCLUDE_DIR ${TARGET_SYSTEMROOT}/../external/include) else() set(DEPS_MBEDTLS deps/mbedtls) set(DEPS_MBEDTLS_SRC ${ROOT_DIR}/${DEPS_MBEDTLS}) set(DEPS_MBEDTLS_BUILD_DIR ${CMAKE_BINARY_DIR}/${DEPS_MBEDTLS}/library/${CONFIG_TYPE}) set(MODULE_BINARY_DIR ${DEPS_MBEDTLS_BUILD_DIR}) if("${TARGET_OS}" STREQUAL "TIZEN") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-cpp") endif() if(USING_MSVC) set(CONFIG_DELIMITER "") else() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-sign-conversion") set(CONFIG_DELIMITER "'") endif() set(MBED_CONFIG "${CONFIG_DELIMITER}${CONFIG_DELIMITER}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I${ROOT_DIR}/config/mbedtls") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMBEDTLS_CONFIG_FILE=${MBED_CONFIG}") # FIXME: # Remove this workaround when the related bug is fixed in # mbedtls. https://github.com/ARMmbed/mbedtls/issues/1550 set(CMAKE_C_FLAGS_BCK "${CMAKE_C_FLAGS}") string(REPLACE "-fsanitize=address" "" CMAKE_C_FLAGS ${CMAKE_C_FLAGS}) build_lib_name(MBED_X509_NAME mbedx509) build_lib_name(MBED_TLS_NAME mbedtls) build_lib_name(MBED_CRYPTO_NAME mbedcrypto) ExternalProject_Add(mbedtls PREFIX ${DEPS_MBEDTLS} SOURCE_DIR ${DEPS_MBEDTLS_SRC} BUILD_IN_SOURCE 0 BINARY_DIR ${DEPS_MBEDTLS} INSTALL_COMMAND COMMAND ${CMAKE_COMMAND} -E copy ${DEPS_MBEDTLS_BUILD_DIR}/${MBED_X509_NAME} ${ARCHIVE_DIR} COMMAND ${CMAKE_COMMAND} -E copy ${DEPS_MBEDTLS_BUILD_DIR}/${MBED_TLS_NAME} ${ARCHIVE_DIR} COMMAND ${CMAKE_COMMAND} -E copy ${DEPS_MBEDTLS_BUILD_DIR}/${MBED_CRYPTO_NAME} ${ARCHIVE_DIR} CMAKE_ARGS -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE} -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS} -DENABLE_PROGRAMS=OFF -DENABLE_TESTING=OFF ) # define external mbedtls target add_library(libmbedtls STATIC IMPORTED) add_dependencies(libmbedtls mbedtls) set_property(TARGET libmbedtls PROPERTY IMPORTED_LOCATION ${ARCHIVE_DIR}/${MBED_TLS_NAME}) # define external mbedx509 target add_library(libmbedx509 STATIC IMPORTED) add_dependencies(libmbedx509 mbedx509) set_property(TARGET libmbedx509 PROPERTY IMPORTED_LOCATION ${ARCHIVE_DIR}/${MBED_X509_NAME}) # define external libmbedcrypto target add_library(libmbedcrypto STATIC IMPORTED) add_dependencies(libmbedcrypto mbedcrypto) set_property(TARGET libmbedcrypto PROPERTY IMPORTED_LOCATION ${ARCHIVE_DIR}/${MBED_CRYPTO_NAME}) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${ARCHIVE_DIR}/${MBED_X509_NAME} ${ARCHIVE_DIR}/${MBED_TLS_NAME} ${ARCHIVE_DIR}/${MBED_CRYPTO_NAME} ) set(MBEDTLS_LIBS libmbedtls libmbedx509 libmbedcrypto) set(MBEDTLS_INCLUDE_DIR ${DEPS_MBEDTLS}/include) # FIXME: # Remove this workaround when the related bug is fixed in # mbedtls. https://github.com/ARMmbed/mbedtls/issues/1550 set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS_BCK}") endif() iotjs-1.0+715/config/000077500000000000000000000000001371177304000142625ustar00rootroot00000000000000iotjs-1.0+715/config/mbedtls/000077500000000000000000000000001371177304000157145ustar00rootroot00000000000000iotjs-1.0+715/config/mbedtls/config-for-iotjs.h000066400000000000000000000475251371177304000212610ustar00rootroot00000000000000/* Copyright 2018-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. */ /* * Minimal configuration for TLS 1.1 (RFC 4346) * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_CONFIG_H #define MBEDTLS_CONFIG_H /** * \name SECTION: System support * * This section sets system specific settings. * \{ */ /** * \def MBEDTLS_HAVE_ASM * * The compiler has support for asm(). * * Requires support for asm() in compiler. * * Used in: * library/timing.c * library/padlock.c * include/mbedtls/bn_mul.h * * Comment to disable the use of assembly code. */ #define MBEDTLS_HAVE_ASM /** * \def MBEDTLS_HAVE_TIME * * System has time.h and time(). * The time does not need to be correct, only time differences are used, * by contrast with MBEDTLS_HAVE_TIME_DATE * * Defining MBEDTLS_HAVE_TIME allows you to specify MBEDTLS_PLATFORM_TIME_ALT, * MBEDTLS_PLATFORM_TIME_MACRO, MBEDTLS_PLATFORM_TIME_TYPE_MACRO and * MBEDTLS_PLATFORM_STD_TIME. * * Comment if your system does not support time functions */ #define MBEDTLS_HAVE_TIME /** * \def MBEDTLS_AES_ROM_TABLES * * Store the AES tables in ROM. * * Uncomment this macro to store the AES tables in ROM. */ #define MBEDTLS_AES_ROM_TABLES /** * \def MBEDTLS_CIPHER_MODE_CBC * * Enable Cipher Block Chaining mode (CBC) for symmetric ciphers. */ #define MBEDTLS_CIPHER_MODE_CBC /** * \def MBEDTLS_REMOVE_ARC4_CIPHERSUITES * * Remove RC4 ciphersuites by default in SSL / TLS. * This flag removes the ciphersuites based on RC4 from the default list as * returned by mbedtls_ssl_list_ciphersuites(). However, it is still possible to * enable (some of) them with mbedtls_ssl_conf_ciphersuites() by including them * explicitly. * * Uncomment this macro to remove RC4 ciphersuites by default. */ #define MBEDTLS_REMOVE_ARC4_CIPHERSUITES /** * \def MBEDTLS_ECP_DP_SECP192R1_ENABLED * * MBEDTLS_ECP_XXXX_ENABLED: Enables specific curves within the Elliptic Curve * module. By default all supported curves are enabled. * * Comment macros to disable the curve and functions for it */ #define MBEDTLS_ECP_DP_SECP256R1_ENABLED #define MBEDTLS_ECP_DP_SECP384R1_ENABLED #define MBEDTLS_ECP_DP_SECP256K1_ENABLED #define MBEDTLS_ECP_DP_BP256R1_ENABLED #define MBEDTLS_ECP_DP_BP384R1_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_RSA_ENABLED * * Enable the RSA-only based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, * MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA */ #define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED * * Enable the DHE-RSA based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_DHM_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, * MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA */ #define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED * * Enable the ECDHE-RSA based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_ECDH_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, * MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA */ #define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED * * Enable the ECDHE-ECDSA based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_ECDH_C, MBEDTLS_ECDSA_C, MBEDTLS_X509_CRT_PARSE_C, * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA */ #define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED * * Enable the ECDH-ECDSA based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 */ #define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED * * Enable the ECDH-RSA based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 */ #define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED /** * \def MBEDTLS_PKCS1_V15 * * Enable support for PKCS#1 v1.5 encoding. * * Requires: MBEDTLS_RSA_C * * This enables support for PKCS#1 v1.5 operations. */ #define MBEDTLS_PKCS1_V15 /** * \def MBEDTLS_PKCS1_V21 * * Enable support for PKCS#1 v2.1 encoding. * * Requires: MBEDTLS_MD_C, MBEDTLS_RSA_C * * This enables support for RSAES-OAEP and RSASSA-PSS operations. */ #define MBEDTLS_PKCS1_V21 /** * \def MBEDTLS_SHA256_SMALLER * * Enable an implementation of SHA-256 that has lower ROM footprint but also * lower performance. * * The default implementation is meant to be a reasonnable compromise between * performance and size. This version optimizes more aggressively for size at * the expense of performance. Eg on Cortex-M4 it reduces the size of * mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about * 30%. * * Uncomment to enable the smaller implementation of SHA256. */ #define MBEDTLS_SHA256_SMALLER /** * \def MBEDTLS_SSL_PROTO_TLS1 * * Enable support for TLS 1.0. * * Requires: MBEDTLS_MD5_C * MBEDTLS_SHA1_C * * Comment this macro to disable support for TLS 1.0 */ #define MBEDTLS_SSL_PROTO_TLS1 /** * \def MBEDTLS_SSL_PROTO_TLS1_1 * * Enable support for TLS 1.1 (and DTLS 1.0 if DTLS is enabled). * * Requires: MBEDTLS_MD5_C * MBEDTLS_SHA1_C * * Comment this macro to disable support for TLS 1.1 / DTLS 1.0 */ #define MBEDTLS_SSL_PROTO_TLS1_1 /** * \def MBEDTLS_SSL_PROTO_TLS1_2 * * Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled). * * Requires: MBEDTLS_SHA1_C or MBEDTLS_SHA256_C or MBEDTLS_SHA512_C * (Depends on ciphersuites) * * Comment this macro to disable support for TLS 1.2 / DTLS 1.2 */ #define MBEDTLS_SSL_PROTO_TLS1_2 /** * \def MBEDTLS_SSL_SERVER_NAME_INDICATION * * Enable support for RFC 6066 server name indication (SNI) in SSL. * * Requires: MBEDTLS_X509_CRT_PARSE_C * * Comment this macro to disable support for server name indication in SSL */ #define MBEDTLS_SSL_SERVER_NAME_INDICATION /* \} name SECTION: mbed TLS feature support */ /** * \name SECTION: mbed TLS modules * * This section enables or disables entire modules in mbed TLS * \{ */ /** * \def MBEDTLS_AES_C * * Enable the AES block cipher. * * Module: library/aes.c * Caller: library/ssl_tls.c * library/pem.c * library/ctr_drbg.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA * * PEM_PARSE uses AES for decrypting encrypted keys. */ #define MBEDTLS_AES_C /** * \def MBEDTLS_ASN1_PARSE_C * * Enable the generic ASN1 parser. * * Module: library/asn1.c * Caller: library/x509.c * library/dhm.c * library/pkcs12.c * library/pkcs5.c * library/pkparse.c */ #define MBEDTLS_ASN1_PARSE_C /** * \def MBEDTLS_ASN1_WRITE_C * * Enable the generic ASN1 writer. * * Module: library/asn1write.c * Caller: library/ecdsa.c * library/pkwrite.c * library/x509_create.c * library/x509write_crt.c * library/mbedtls_x509write_csr.c */ #define MBEDTLS_ASN1_WRITE_C /** * \def MBEDTLS_BASE64_C * * Enable the Base64 module. * * Module: library/base64.c * Caller: library/pem.c * * This module is required for PEM support (required by X.509). */ #define MBEDTLS_BASE64_C /** * \def MBEDTLS_BIGNUM_C * * Enable the multi-precision integer library. * * Module: library/bignum.c * Caller: library/dhm.c * library/ecp.c * library/ecdsa.c * library/rsa.c * library/ssl_tls.c * * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support. */ #define MBEDTLS_BIGNUM_C /** * \def MBEDTLS_CIPHER_C * * Enable the generic cipher layer. * * Module: library/cipher.c * Caller: library/ssl_tls.c * * Uncomment to enable generic cipher wrappers. */ #define MBEDTLS_CIPHER_C /** * \def MBEDTLS_CTR_DRBG_C * * Enable the CTR_DRBG AES-256-based random generator. * * Module: library/ctr_drbg.c * Caller: * * Requires: MBEDTLS_AES_C * * This module provides the CTR_DRBG AES-256 random number generator. */ #define MBEDTLS_CTR_DRBG_C /** * \def MBEDTLS_DHM_C * * Enable the Diffie-Hellman-Merkle module. * * Module: library/dhm.c * Caller: library/ssl_cli.c * library/ssl_srv.c * * This module is used by the following key exchanges: * DHE-RSA, DHE-PSK */ #define MBEDTLS_DHM_C /** * \def MBEDTLS_ECDH_C * * Enable the elliptic curve Diffie-Hellman library. * * Module: library/ecdh.c * Caller: library/ssl_cli.c * library/ssl_srv.c * * This module is used by the following key exchanges: * ECDHE-ECDSA, ECDHE-RSA, DHE-PSK * * Requires: MBEDTLS_ECP_C */ #define MBEDTLS_ECDH_C /** * \def MBEDTLS_ECDSA_C * * Enable the elliptic curve DSA library. * * Module: library/ecdsa.c * Caller: * * This module is used by the following key exchanges: * ECDHE-ECDSA * * Requires: MBEDTLS_ECP_C, MBEDTLS_ASN1_WRITE_C, MBEDTLS_ASN1_PARSE_C */ #define MBEDTLS_ECDSA_C /** * \def MBEDTLS_ECP_C * * Enable the elliptic curve over GF(p) library. * * Module: library/ecp.c * Caller: library/ecdh.c * library/ecdsa.c * library/ecjpake.c * * Requires: MBEDTLS_BIGNUM_C and at least one MBEDTLS_ECP_DP_XXX_ENABLED */ #define MBEDTLS_ECP_C /** * \def MBEDTLS_ENTROPY_C * * Enable the platform-specific entropy code. * * Module: library/entropy.c * Caller: * * Requires: MBEDTLS_SHA512_C or MBEDTLS_SHA256_C * * This module provides a generic entropy pool */ #define MBEDTLS_ENTROPY_C /** * \def MBEDTLS_GCM_C * * Enable the Galois/Counter Mode (GCM) for AES. * * Module: library/gcm.c * * Requires: MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C * * This module enables the AES-GCM and CAMELLIA-GCM ciphersuites, if other * requisites are enabled as well. */ #define MBEDTLS_GCM_C /** * \def MBEDTLS_MD_C * * Enable the generic message digest layer. * * Module: library/mbedtls_md.c * Caller: * * Uncomment to enable generic message digest wrappers. */ #define MBEDTLS_MD_C /** * \def MBEDTLS_MD5_C * * Enable the MD5 hash algorithm. * * Module: library/mbedtls_md5.c * Caller: library/mbedtls_md.c * library/pem.c * library/ssl_tls.c * * This module is required for SSL/TLS and X.509. * PEM_PARSE uses MD5 for decrypting encrypted keys. */ #define MBEDTLS_MD5_C /** * \def MBEDTLS_OID_C * * Enable the OID database. * * Module: library/oid.c * Caller: library/asn1write.c * library/pkcs5.c * library/pkparse.c * library/pkwrite.c * library/rsa.c * library/x509.c * library/x509_create.c * library/mbedtls_x509_crl.c * library/mbedtls_x509_crt.c * library/mbedtls_x509_csr.c * library/x509write_crt.c * library/mbedtls_x509write_csr.c * * This modules translates between OIDs and internal values. */ #define MBEDTLS_OID_C /** * \def MBEDTLS_PEM_PARSE_C * * Enable PEM decoding / parsing. * * Module: library/pem.c * Caller: library/dhm.c * library/pkparse.c * library/mbedtls_x509_crl.c * library/mbedtls_x509_crt.c * library/mbedtls_x509_csr.c * * Requires: MBEDTLS_BASE64_C * * This modules adds support for decoding / parsing PEM files. */ #define MBEDTLS_PEM_PARSE_C /** * \def MBEDTLS_PK_C * * Enable the generic public (asymetric) key layer. * * Module: library/pk.c * Caller: library/ssl_tls.c * library/ssl_cli.c * library/ssl_srv.c * * Requires: MBEDTLS_RSA_C or MBEDTLS_ECP_C * * Uncomment to enable generic public key wrappers. */ #define MBEDTLS_PK_C /** * \def MBEDTLS_PK_PARSE_C * * Enable the generic public (asymetric) key parser. * * Module: library/pkparse.c * Caller: library/mbedtls_x509_crt.c * library/mbedtls_x509_csr.c * * Requires: MBEDTLS_PK_C * * Uncomment to enable generic public key parse functions. */ #define MBEDTLS_PK_PARSE_C /** * \def MBEDTLS_RSA_C * * Enable the RSA public-key cryptosystem. * * Module: library/rsa.c * Caller: library/ssl_cli.c * library/ssl_srv.c * library/ssl_tls.c * library/x509.c * * This module is used by the following key exchanges: * RSA, DHE-RSA, ECDHE-RSA, RSA-PSK * * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C */ #define MBEDTLS_RSA_C /** * \def MBEDTLS_SHA1_C * * Enable the SHA1 cryptographic hash algorithm. * * Module: library/mbedtls_sha1.c * Caller: library/mbedtls_md.c * library/ssl_cli.c * library/ssl_srv.c * library/ssl_tls.c * library/x509write_crt.c * * This module is required for SSL/TLS and SHA1-signed certificates. */ #define MBEDTLS_SHA1_C /** * \def MBEDTLS_SHA256_C * * Enable the SHA-224 and SHA-256 cryptographic hash algorithms. * * Module: library/mbedtls_sha256.c * Caller: library/entropy.c * library/mbedtls_md.c * library/ssl_cli.c * library/ssl_srv.c * library/ssl_tls.c * * This module adds support for SHA-224 and SHA-256. * This module is required for the SSL/TLS 1.2 PRF function. */ #define MBEDTLS_SHA256_C /** * \def MBEDTLS_SSL_CLI_C * * Enable the SSL/TLS client code. * * Module: library/ssl_cli.c * Caller: * * Requires: MBEDTLS_SSL_TLS_C * * This module is required for SSL/TLS client support. */ #define MBEDTLS_SSL_CLI_C /** * \def MBEDTLS_SSL_SRV_C * * Enable the SSL/TLS server code. * * Module: library/ssl_srv.c * Caller: * * Requires: MBEDTLS_SSL_TLS_C * * This module is required for SSL/TLS server support. */ #define MBEDTLS_SSL_SRV_C /** * \def MBEDTLS_SSL_TLS_C * * Enable the generic SSL/TLS code. * * Module: library/ssl_tls.c * Caller: library/ssl_cli.c * library/ssl_srv.c * * Requires: MBEDTLS_CIPHER_C, MBEDTLS_MD_C * and at least one of the MBEDTLS_SSL_PROTO_XXX defines * * This module is required for SSL/TLS. */ #define MBEDTLS_SSL_TLS_C /** * \def MBEDTLS_X509_USE_C * * Enable X.509 core for using certificates. * * Module: library/x509.c * Caller: library/mbedtls_x509_crl.c * library/mbedtls_x509_crt.c * library/mbedtls_x509_csr.c * * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, * MBEDTLS_PK_PARSE_C * * This module is required for the X.509 parsing modules. */ #define MBEDTLS_X509_USE_C /** * \def MBEDTLS_X509_CRT_PARSE_C * * Enable X.509 certificate parsing. * * Module: library/mbedtls_x509_crt.c * Caller: library/ssl_cli.c * library/ssl_srv.c * library/ssl_tls.c * * Requires: MBEDTLS_X509_USE_C * * This module is required for X.509 certificate parsing. */ #define MBEDTLS_X509_CRT_PARSE_C /* \} name SECTION: mbed TLS modules */ #endif /* MBEDTLS_CONFIG_H */ iotjs-1.0+715/config/nuttx/000077500000000000000000000000001371177304000154445ustar00rootroot00000000000000iotjs-1.0+715/config/nuttx/stm32f4dis/000077500000000000000000000000001371177304000173465ustar00rootroot00000000000000iotjs-1.0+715/config/nuttx/stm32f4dis/app/000077500000000000000000000000001371177304000201265ustar00rootroot00000000000000iotjs-1.0+715/config/nuttx/stm32f4dis/app/Kconfig000066400000000000000000000005541371177304000214350ustar00rootroot00000000000000# # For a description of the syntax of this configuration file, # see the file kconfig-language.txt in the NuttX tools repository. # config IOTJS bool "IoT.js" default n ---help--- Enable IoT.js platform if IOTJS config IOTJS_PRIORITY int "IoT.js task priority" default 100 config IOTJS_STACKSIZE int "IoT.js stack size" default 16384 endif iotjs-1.0+715/config/nuttx/stm32f4dis/app/Make.defs000066400000000000000000000013251371177304000216470ustar00rootroot00000000000000# Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors # Copyright 2016 University of Szeged # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ifeq ($(CONFIG_IOTJS),y) CONFIGURED_APPS += system/iotjs endif iotjs-1.0+715/config/nuttx/stm32f4dis/app/Makefile000066400000000000000000000121761371177304000215750ustar00rootroot00000000000000# 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) 2009, 2011-2013 Gregory Nutt. All rights reserved. # Author: Gregory Nutt # # 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. # ############################################################################ # TODO, this makefile should run make under the app dirs, instead of # sourcing the Make.defs! -include $(TOPDIR)/.config -include $(TOPDIR)/Make.defs include $(APPDIR)/Make.defs IOTJS_ABSOLUTE_ROOT_DIR := $(shell cd $(TOPDIR) && cd $(IOTJS_ROOT_DIR) && pwd) CONFIG_IOTJS_PRIORITY ?= SCHED_PRIORITY_DEFAULT CONFIG_IOTJS_STACKSIZE ?= 16384 # NSH sysinfo command 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 = setjmp.S CSRCS = jerry_port.c MAINSRC = iotjs_main.c LIBS = libhttpparser.a libiotjs.a libjerry-core.a libtuv.a libjerry-libm.a libjerry-ext.a 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 = $(APPDIR)\libapps$(LIBEXT) else ifeq ($(WINTOOL),y) BIN = $(APPDIR)\\libapps$(LIBEXT) else BIN = $(APPDIR)/libapps$(LIBEXT) endif endif ifeq ($(WINTOOL),y) INSTALL_DIR = "${shell cygpath -w $(BIN_DIR)}" else INSTALL_DIR = $(BIN_DIR) endif CONFIG_XYZ_PROGNAME ?= iotjs$(EXEEXT) PROGNAME = $(CONFIG_XYZ_PROGNAME) ROOTDEPPATH = --dep-path . # Common build VPATH = all: .built .PHONY: context depend clean distclean $(AOBJS): %$(OBJEXT): %.S $(call ASSEMBLE, $<, $@) $(COBJS): %$(OBJEXT): %.c $(call COMPILE, $<, $@) copylibs : cp $(IOTJS_ABSOLUTE_ROOT_DIR)/build/arm-nuttx/$(BUILD_TYPE)/lib/lib*.a . $(LIBS) : copylibs $(firstword $(AR)) x $@ .built: $(LIBS) $(OBJS) $(eval OBJS += $(shell find . -name "*.obj")) $(call ARCHIVE, $(BIN), $(OBJS)) $(Q) touch .built ifeq ($(CONFIG_BUILD_KERNEL),y) $(BIN_DIR)$(DELIM)$(PROGNAME): $(OBJS) $(MAINOBJ) @echo "LD: $(PROGNAME)" $(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 # Register application ifeq ($(CONFIG_NSH_BUILTIN_APPS),y) $(BUILTIN_REGISTRY)$(DELIM)iotjs.bdat: $(DEPCONFIG) Makefile $(call REGISTER,"iotjs",$(PRIORITY),$(STACKSIZE),iotjs_main) context: $(BUILTIN_REGISTRY)$(DELIM)iotjs.bdat else context: endif # Create dependencies .depend: Makefile $(SRCS) $(Q) $(MKDEP) $(ROOTDEPPATH) "$(CC)" -- $(CFLAGS) -- $(SRCS) >Make.dep $(Q) touch $@ depend: .depend clean: $(eval OBJS += $(shell find . -name "*.obj")) $(call DELFILE, $(OBJS)) $(call DELFILE, .built) $(call CLEAN) distclean: clean $(call DELFILE, Make.dep) $(call DELFILE, .depend) -include Make.dep .PHONY: preconfig preconfig: iotjs-1.0+715/config/nuttx/stm32f4dis/app/iotjs_main.c000066400000000000000000000061121371177304000224260ustar00rootroot00000000000000/* 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 * * 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 #include #include #include "setjmp.h" /**************************************************************************** * Public Functions ****************************************************************************/ extern int iotjs_entry(int argc, char *argv[]); extern int tuv_cleanup(void); #ifdef CONFIG_BUILD_KERNEL extern int main(int argc, FAR char *argv[]) #else extern int iotjs_main(int argc, char *argv[]) #endif { int ret = 0; ret = iotjs_entry(argc, argv); tuv_cleanup(); return ret; } iotjs-1.0+715/config/nuttx/stm32f4dis/app/jerry_port.c000066400000000000000000000104341371177304000224730ustar00rootroot00000000000000/* 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 #include #include #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 local time zone adjustment, in milliseconds, * for the given timestamp. */ double jerry_port_get_local_time_zone_adjustment(double unix_ms, bool is_utc) { (void)unix_ms; (void)is_utc; return 0.0; } /* jerry_port_get_local_time_zone_adjustment */ /** * Dummy function to get the current time. * * @return 0 */ double jerry_port_get_current_time(void) { return 0; } /* jerry_port_get_current_time */ /** * Provide the implementation of 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 */ /** * Normalize a file path * * @return length of the path written to the output buffer */ size_t jerry_port_normalize_path( const char *in_path_p, /**< input file path */ char *out_buf_p, /**< output buffer */ size_t out_buf_size, /**< size of output buffer */ char *base_file_p) /**< base file path */ { (void)base_file_p; size_t len = strlen(in_path_p); if (len + 1 > out_buf_size) { return 0; } /* Return the original string. */ strcpy(out_buf_p, in_path_p); return len; } /* jerry_port_normalize_path */ /** * Get the module object of a native module. * * @return undefined */ jerry_value_t jerry_port_get_native_module( jerry_value_t name) /**< module specifier */ { (void)name; return jerry_create_undefined(); } /* jerry_port_get_native_module */ /** * Determines the size of the given file. * @return size of the file */ static size_t jerry_port_get_file_size(FILE *file_p) /**< opened file */ { fseek(file_p, 0, SEEK_END); long size = ftell(file_p); fseek(file_p, 0, SEEK_SET); return (size_t)size; } /* jerry_port_get_file_size */ /** * Opens file with the given path and reads its source. * @return the source of the file */ uint8_t *jerry_port_read_source(const char *file_name_p, /**< file name */ size_t *out_size_p) /**< [out] read bytes */ { FILE *file_p = fopen(file_name_p, "rb"); if (file_p == NULL) { jerry_port_log(JERRY_LOG_LEVEL_ERROR, "Error: failed to open file: %s\n", file_name_p); return NULL; } size_t file_size = jerry_port_get_file_size(file_p); uint8_t *buffer_p = (uint8_t *)malloc(file_size); if (buffer_p == NULL) { fclose(file_p); jerry_port_log(JERRY_LOG_LEVEL_ERROR, "Error: failed to allocate memory for module"); return NULL; } size_t bytes_read = fread(buffer_p, 1u, file_size, file_p); if (!bytes_read) { fclose(file_p); free(buffer_p); jerry_port_log(JERRY_LOG_LEVEL_ERROR, "Error: failed to read file: %s\n", file_name_p); return NULL; } fclose(file_p); *out_size_p = bytes_read; return buffer_p; } /* jerry_port_read_source */ /** * Release the previously opened file's content. */ void jerry_port_release_source(uint8_t *buffer_p) /**< buffer to free */ { free(buffer_p); } /* jerry_port_release_source */ iotjs-1.0+715/config/nuttx/stm32f4dis/app/setjmp.S000066400000000000000000000040161371177304000215550ustar00rootroot00000000000000/* 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. */ /* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ .syntax unified .macro func _name .global \_name .type \_name, %function \_name: .endm .macro endfunc _name .size \_name, .-\_name .endm /** * setjmp (jmp_buf env) * * See also: * longjmp * * @return 0 - if returns from direct call, * nonzero - if returns after longjmp. */ func setjmp stmia r0!, {r4 - r11, lr} str sp, [r0], #4 vstm r0, {s16 - s31} mov r0, #0 bx lr endfunc setjmp /** * longjmp (jmp_buf env, int val) * * Note: * if val is not 0, then it would be returned from setjmp, * otherwise - 0 would be returned. * * See also: * setjmp */ func longjmp ldmia r0!, {r4 - r11, lr} ldr sp, [r0] add r0, r0, #4 vldm r0, {s16 - s31} mov r0, r1 cmp r0, #0 bne 1f mov r0, #1 1: bx lr endfunc longjmp iotjs-1.0+715/config/nuttx/stm32f4dis/app/setjmp.h000066400000000000000000000026471371177304000216120ustar00rootroot00000000000000/* 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. */ /* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SETJMP_H #define SETJMP_H #include typedef uint64_t jmp_buf[14]; int setjmp(jmp_buf env); void longjmp(jmp_buf env, int val); #endif /* !SETJMP_H */ iotjs-1.0+715/config/nuttx/stm32f4dis/config.alloptions000066400000000000000000001217501371177304000227270ustar00rootroot00000000000000# # Automatically generated file; DO NOT EDIT. # Nuttx/ 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 # # Build Configuration # CONFIG_APPS_DIR="../apps" CONFIG_BUILD_FLAT=y # CONFIG_BUILD_2PASS is not set # # Binary Output Formats # # CONFIG_RRLOAD_BINARY is not set CONFIG_INTELHEX_BINARY=y # CONFIG_MOTOROLA_SREC is not set CONFIG_RAW_BINARY=y # CONFIG_UBOOT_UIMAGE 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 # CONFIG_ARCH_DEBUG_H is not set # # Debug Options # CONFIG_DEBUG_ALERT=y # CONFIG_DEBUG_FEATURES is not set CONFIG_ARCH_HAVE_STACKCHECK=y # CONFIG_STACK_COLORATION is not set CONFIG_ARCH_HAVE_HEAPCHECK=y # CONFIG_HEAP_COLORATION is not set # CONFIG_DEBUG_SYMBOLS is not set CONFIG_ARCH_HAVE_CUSTOMOPT=y # CONFIG_DEBUG_NOOPT is not set # CONFIG_DEBUG_CUSTOMOPT is not set CONFIG_DEBUG_FULLOPT=y # # System Type # CONFIG_ARCH_ARM=y # CONFIG_ARCH_AVR is not set # CONFIG_ARCH_HC is not set # CONFIG_ARCH_MIPS is not set # CONFIG_ARCH_MISOC is not set # CONFIG_ARCH_RENESAS is not set # CONFIG_ARCH_RISCV is not set # CONFIG_ARCH_SIM is not set # CONFIG_ARCH_X86 is not set # CONFIG_ARCH_XTENSA is not set # CONFIG_ARCH_Z16 is not set # CONFIG_ARCH_Z80 is not set CONFIG_ARCH="arm" # # ARM Options # # CONFIG_ARCH_CHIP_A1X is not set # CONFIG_ARCH_CHIP_C5471 is not set # CONFIG_ARCH_CHIP_DM320 is not set # CONFIG_ARCH_CHIP_EFM32 is not set # CONFIG_ARCH_CHIP_IMX1 is not set # CONFIG_ARCH_CHIP_IMX6 is not set # CONFIG_ARCH_CHIP_KINETIS is not set # CONFIG_ARCH_CHIP_KL is not set # CONFIG_ARCH_CHIP_LM is not set # CONFIG_ARCH_CHIP_TIVA is not set # CONFIG_ARCH_CHIP_LPC11XX is not set # CONFIG_ARCH_CHIP_LPC17XX is not set # CONFIG_ARCH_CHIP_LPC214X is not set # CONFIG_ARCH_CHIP_LPC2378 is not set # CONFIG_ARCH_CHIP_LPC31XX is not set # CONFIG_ARCH_CHIP_LPC43XX is not set # CONFIG_ARCH_CHIP_NUC1XX is not set # CONFIG_ARCH_CHIP_SAMA5 is not set # CONFIG_ARCH_CHIP_SAMD is not set # CONFIG_ARCH_CHIP_SAML is not set # CONFIG_ARCH_CHIP_SAM34 is not set # CONFIG_ARCH_CHIP_SAMV7 is not set CONFIG_ARCH_CHIP_STM32=y # CONFIG_ARCH_CHIP_STM32F7 is not set # CONFIG_ARCH_CHIP_STM32L4 is not set # CONFIG_ARCH_CHIP_STR71X is not set # CONFIG_ARCH_CHIP_TMS570 is not set # CONFIG_ARCH_CHIP_MOXART is not set # CONFIG_ARCH_ARM7TDMI is not set # CONFIG_ARCH_ARM926EJS is not set # CONFIG_ARCH_ARM920T is not set # CONFIG_ARCH_CORTEXM0 is not set # CONFIG_ARCH_CORTEXM3 is not set CONFIG_ARCH_CORTEXM4=y # CONFIG_ARCH_CORTEXM7 is not set # CONFIG_ARCH_CORTEXA5 is not set # CONFIG_ARCH_CORTEXA8 is not set # CONFIG_ARCH_CORTEXA9 is not set # CONFIG_ARCH_CORTEXR4 is not set # CONFIG_ARCH_CORTEXR4F is not set # CONFIG_ARCH_CORTEXR5 is not set # CONFIG_ARCH_CORTEX5F is not set # CONFIG_ARCH_CORTEXR7 is not set # CONFIG_ARCH_CORTEXR7F is not set CONFIG_ARCH_FAMILY="armv7-m" CONFIG_ARCH_CHIP="stm32" # CONFIG_ARM_TOOLCHAIN_IAR is not set CONFIG_ARM_TOOLCHAIN_GNU=y # CONFIG_ARMV7M_USEBASEPRI is not set CONFIG_ARCH_HAVE_CMNVECTOR=y # CONFIG_ARMV7M_CMNVECTOR is not set # CONFIG_ARMV7M_LAZYFPU is not set CONFIG_ARCH_HAVE_FPU=y # CONFIG_ARCH_HAVE_DPFPU is not set CONFIG_ARCH_FPU=y # CONFIG_ARCH_HAVE_TRUSTZONE is not set CONFIG_ARM_HAVE_MPU_UNIFIED=y # CONFIG_ARM_MPU is not set # # ARMV7M Configuration Options # # CONFIG_ARMV7M_HAVE_ICACHE is not set # CONFIG_ARMV7M_HAVE_DCACHE is not set # CONFIG_ARMV7M_HAVE_ITCM is not set # CONFIG_ARMV7M_HAVE_DTCM is not set # CONFIG_ARMV7M_TOOLCHAIN_IARL is not set # CONFIG_ARMV7M_TOOLCHAIN_BUILDROOT is not set # CONFIG_ARMV7M_TOOLCHAIN_CODEREDL is not set # CONFIG_ARMV7M_TOOLCHAIN_CODESOURCERYL is not set CONFIG_ARMV7M_TOOLCHAIN_GNU_EABIL=y CONFIG_ARMV7M_HAVE_STACKCHECK=y # CONFIG_ARMV7M_STACKCHECK is not set # CONFIG_ARMV7M_ITMSYSLOG is not set # CONFIG_SERIAL_TERMIOS is not set # CONFIG_SDIO_DMA is not set # CONFIG_SDIO_WIDTH_D1_ONLY is not set # # STM32 Configuration Options # # CONFIG_ARCH_CHIP_STM32L151C6 is not set # CONFIG_ARCH_CHIP_STM32L151C8 is not set # CONFIG_ARCH_CHIP_STM32L151CB is not set # CONFIG_ARCH_CHIP_STM32L151R6 is not set # CONFIG_ARCH_CHIP_STM32L151R8 is not set # CONFIG_ARCH_CHIP_STM32L151RB is not set # CONFIG_ARCH_CHIP_STM32L151V6 is not set # CONFIG_ARCH_CHIP_STM32L151V8 is not set # CONFIG_ARCH_CHIP_STM32L151VB is not set # CONFIG_ARCH_CHIP_STM32L152C6 is not set # CONFIG_ARCH_CHIP_STM32L152C8 is not set # CONFIG_ARCH_CHIP_STM32L152CB is not set # CONFIG_ARCH_CHIP_STM32L152R6 is not set # CONFIG_ARCH_CHIP_STM32L152R8 is not set # CONFIG_ARCH_CHIP_STM32L152RB is not set # CONFIG_ARCH_CHIP_STM32L152V6 is not set # CONFIG_ARCH_CHIP_STM32L152V8 is not set # CONFIG_ARCH_CHIP_STM32L152VB is not set # CONFIG_ARCH_CHIP_STM32L162ZD is not set # CONFIG_ARCH_CHIP_STM32L162VE is not set # CONFIG_ARCH_CHIP_STM32F100C8 is not set # CONFIG_ARCH_CHIP_STM32F100CB is not set # CONFIG_ARCH_CHIP_STM32F100R8 is not set # CONFIG_ARCH_CHIP_STM32F100RB is not set # CONFIG_ARCH_CHIP_STM32F100RC is not set # CONFIG_ARCH_CHIP_STM32F100RD is not set # CONFIG_ARCH_CHIP_STM32F100RE is not set # CONFIG_ARCH_CHIP_STM32F100V8 is not set # CONFIG_ARCH_CHIP_STM32F100VB is not set # CONFIG_ARCH_CHIP_STM32F100VC is not set # CONFIG_ARCH_CHIP_STM32F100VD is not set # CONFIG_ARCH_CHIP_STM32F100VE is not set # CONFIG_ARCH_CHIP_STM32F102CB is not set # CONFIG_ARCH_CHIP_STM32F103T8 is not set # CONFIG_ARCH_CHIP_STM32F103TB is not set # CONFIG_ARCH_CHIP_STM32F103C4 is not set # CONFIG_ARCH_CHIP_STM32F103C8 is not set # CONFIG_ARCH_CHIP_STM32F103CB is not set # CONFIG_ARCH_CHIP_STM32F103R8 is not set # CONFIG_ARCH_CHIP_STM32F103RB is not set # CONFIG_ARCH_CHIP_STM32F103RC is not set # CONFIG_ARCH_CHIP_STM32F103RD is not set # CONFIG_ARCH_CHIP_STM32F103RE is not set # CONFIG_ARCH_CHIP_STM32F103RG is not set # CONFIG_ARCH_CHIP_STM32F103V8 is not set # CONFIG_ARCH_CHIP_STM32F103VB is not set # CONFIG_ARCH_CHIP_STM32F103VC is not set # CONFIG_ARCH_CHIP_STM32F103VE is not set # CONFIG_ARCH_CHIP_STM32F103ZE is not set # CONFIG_ARCH_CHIP_STM32F105VB is not set # CONFIG_ARCH_CHIP_STM32F105RB is not set # CONFIG_ARCH_CHIP_STM32F107VC is not set # CONFIG_ARCH_CHIP_STM32F205RG is not set # CONFIG_ARCH_CHIP_STM32F207IG is not set # CONFIG_ARCH_CHIP_STM32F207ZE is not set # CONFIG_ARCH_CHIP_STM32F302K6 is not set # CONFIG_ARCH_CHIP_STM32F302K8 is not set # CONFIG_ARCH_CHIP_STM32F302CB is not set # CONFIG_ARCH_CHIP_STM32F302CC is not set # CONFIG_ARCH_CHIP_STM32F302RB is not set # CONFIG_ARCH_CHIP_STM32F302RC is not set # CONFIG_ARCH_CHIP_STM32F302VB is not set # CONFIG_ARCH_CHIP_STM32F302VC is not set # CONFIG_ARCH_CHIP_STM32F303K6 is not set # CONFIG_ARCH_CHIP_STM32F303K8 is not set # CONFIG_ARCH_CHIP_STM32F303C6 is not set # CONFIG_ARCH_CHIP_STM32F303C8 is not set # CONFIG_ARCH_CHIP_STM32F303CB is not set # CONFIG_ARCH_CHIP_STM32F303CC is not set # CONFIG_ARCH_CHIP_STM32F303RB is not set # CONFIG_ARCH_CHIP_STM32F303RC is not set # CONFIG_ARCH_CHIP_STM32F303RD is not set # CONFIG_ARCH_CHIP_STM32F303RE is not set # CONFIG_ARCH_CHIP_STM32F303VB is not set # CONFIG_ARCH_CHIP_STM32F303VC is not set # CONFIG_ARCH_CHIP_STM32F372C8 is not set # CONFIG_ARCH_CHIP_STM32F372R8 is not set # CONFIG_ARCH_CHIP_STM32F372V8 is not set # CONFIG_ARCH_CHIP_STM32F372CB is not set # CONFIG_ARCH_CHIP_STM32F372RB is not set # CONFIG_ARCH_CHIP_STM32F372VB is not set # CONFIG_ARCH_CHIP_STM32F372CC is not set # CONFIG_ARCH_CHIP_STM32F372RC is not set # CONFIG_ARCH_CHIP_STM32F372VC is not set # CONFIG_ARCH_CHIP_STM32F373C8 is not set # CONFIG_ARCH_CHIP_STM32F373R8 is not set # CONFIG_ARCH_CHIP_STM32F373V8 is not set # CONFIG_ARCH_CHIP_STM32F373CB is not set # CONFIG_ARCH_CHIP_STM32F373RB is not set # CONFIG_ARCH_CHIP_STM32F373VB is not set # CONFIG_ARCH_CHIP_STM32F373CC is not set # CONFIG_ARCH_CHIP_STM32F373RC is not set # CONFIG_ARCH_CHIP_STM32F373VC is not set # CONFIG_ARCH_CHIP_STM32F401RE is not set # CONFIG_ARCH_CHIP_STM32F411RE is not set # CONFIG_ARCH_CHIP_STM32F411VE is not set # CONFIG_ARCH_CHIP_STM32F405RG is not set # CONFIG_ARCH_CHIP_STM32F405VG is not set # CONFIG_ARCH_CHIP_STM32F405ZG is not set # CONFIG_ARCH_CHIP_STM32F407VE is not set CONFIG_ARCH_CHIP_STM32F407VG=y # CONFIG_ARCH_CHIP_STM32F407ZE is not set # CONFIG_ARCH_CHIP_STM32F407ZG is not set # CONFIG_ARCH_CHIP_STM32F407IE is not set # CONFIG_ARCH_CHIP_STM32F407IG is not set # CONFIG_ARCH_CHIP_STM32F427V is not set # CONFIG_ARCH_CHIP_STM32F427Z is not set # CONFIG_ARCH_CHIP_STM32F427I is not set # CONFIG_ARCH_CHIP_STM32F429V is not set # CONFIG_ARCH_CHIP_STM32F429Z is not set # CONFIG_ARCH_CHIP_STM32F429I is not set # CONFIG_ARCH_CHIP_STM32F429B is not set # CONFIG_ARCH_CHIP_STM32F429N is not set # CONFIG_ARCH_CHIP_STM32F446M is not set # CONFIG_ARCH_CHIP_STM32F446R is not set # CONFIG_ARCH_CHIP_STM32F446V is not set # CONFIG_ARCH_CHIP_STM32F446Z is not set # CONFIG_ARCH_CHIP_STM32F469A is not set # CONFIG_ARCH_CHIP_STM32F469I is not set # CONFIG_ARCH_CHIP_STM32F469B is not set # CONFIG_ARCH_CHIP_STM32F469N is not set CONFIG_STM32_FLASH_CONFIG_DEFAULT=y # CONFIG_STM32_FLASH_CONFIG_4 is not set # CONFIG_STM32_FLASH_CONFIG_6 is not set # CONFIG_STM32_FLASH_CONFIG_8 is not set # CONFIG_STM32_FLASH_CONFIG_B is not set # CONFIG_STM32_FLASH_CONFIG_C is not set # CONFIG_STM32_FLASH_CONFIG_D is not set # CONFIG_STM32_FLASH_CONFIG_E is not set # CONFIG_STM32_FLASH_CONFIG_F is not set # CONFIG_STM32_FLASH_CONFIG_G is not set # CONFIG_STM32_FLASH_CONFIG_I is not set # CONFIG_STM32_STM32L15XX is not set # CONFIG_STM32_ENERGYLITE is not set # CONFIG_STM32_STM32F10XX is not set # CONFIG_STM32_VALUELINE is not set # CONFIG_STM32_CONNECTIVITYLINE is not set # CONFIG_STM32_PERFORMANCELINE is not set # CONFIG_STM32_USBACCESSLINE is not set # CONFIG_STM32_HIGHDENSITY is not set # CONFIG_STM32_MEDIUMDENSITY is not set # CONFIG_STM32_LOWDENSITY is not set # CONFIG_STM32_STM32F20XX is not set # CONFIG_STM32_STM32F205 is not set # CONFIG_STM32_STM32F207 is not set # CONFIG_STM32_STM32F30XX is not set # CONFIG_STM32_STM32F302 is not set # CONFIG_STM32_STM32F303 is not set # CONFIG_STM32_STM32F37XX is not set CONFIG_STM32_STM32F40XX=y # CONFIG_STM32_STM32F401 is not set # CONFIG_STM32_STM32F411 is not set # CONFIG_STM32_STM32F405 is not set CONFIG_STM32_STM32F407=y # CONFIG_STM32_STM32F427 is not set # CONFIG_STM32_STM32F429 is not set # CONFIG_STM32_STM32F446 is not set # CONFIG_STM32_STM32F469 is not set # CONFIG_STM32_DFU is not set # # STM32 Peripheral Support # CONFIG_STM32_HAVE_CCM=y # CONFIG_STM32_HAVE_USBDEV is not set CONFIG_STM32_HAVE_OTGFS=y CONFIG_STM32_HAVE_FSMC=y # CONFIG_STM32_HAVE_LTDC is not set CONFIG_STM32_HAVE_USART3=y CONFIG_STM32_HAVE_UART4=y CONFIG_STM32_HAVE_UART5=y CONFIG_STM32_HAVE_USART6=y # CONFIG_STM32_HAVE_UART7 is not set # CONFIG_STM32_HAVE_UART8 is not set CONFIG_STM32_HAVE_TIM1=y CONFIG_STM32_HAVE_TIM2=y CONFIG_STM32_HAVE_TIM3=y CONFIG_STM32_HAVE_TIM4=y CONFIG_STM32_HAVE_TIM5=y CONFIG_STM32_HAVE_TIM6=y CONFIG_STM32_HAVE_TIM7=y CONFIG_STM32_HAVE_TIM8=y CONFIG_STM32_HAVE_TIM9=y CONFIG_STM32_HAVE_TIM10=y CONFIG_STM32_HAVE_TIM11=y CONFIG_STM32_HAVE_TIM12=y CONFIG_STM32_HAVE_TIM13=y CONFIG_STM32_HAVE_TIM14=y # CONFIG_STM32_HAVE_TIM15 is not set # CONFIG_STM32_HAVE_TIM16 is not set # CONFIG_STM32_HAVE_TIM17 is not set CONFIG_STM32_HAVE_ADC2=y CONFIG_STM32_HAVE_ADC3=y # CONFIG_STM32_HAVE_ADC4 is not set # CONFIG_STM32_HAVE_ADC1_DMA is not set # CONFIG_STM32_HAVE_ADC2_DMA is not set # CONFIG_STM32_HAVE_ADC3_DMA is not set # CONFIG_STM32_HAVE_ADC4_DMA is not set # CONFIG_STM32_HAVE_SDADC1 is not set # CONFIG_STM32_HAVE_SDADC2 is not set # CONFIG_STM32_HAVE_SDADC3 is not set # CONFIG_STM32_HAVE_SDADC1_DMA is not set # CONFIG_STM32_HAVE_SDADC2_DMA is not set # CONFIG_STM32_HAVE_SDADC3_DMA is not set CONFIG_STM32_HAVE_CAN1=y CONFIG_STM32_HAVE_CAN2=y CONFIG_STM32_HAVE_DAC1=y CONFIG_STM32_HAVE_DAC2=y CONFIG_STM32_HAVE_RNG=y CONFIG_STM32_HAVE_ETHMAC=y CONFIG_STM32_HAVE_I2C2=y CONFIG_STM32_HAVE_I2C3=y CONFIG_STM32_HAVE_SPI2=y CONFIG_STM32_HAVE_SPI3=y # CONFIG_STM32_HAVE_SPI4 is not set # CONFIG_STM32_HAVE_SPI5 is not set # CONFIG_STM32_HAVE_SPI6 is not set # CONFIG_STM32_HAVE_SAIPLL is not set # CONFIG_STM32_HAVE_I2SPLL is not set CONFIG_STM32_ADC1=y # CONFIG_STM32_ADC2 is not set # CONFIG_STM32_ADC3 is not set # CONFIG_STM32_BKPSRAM is not set # CONFIG_STM32_CAN1 is not set # CONFIG_STM32_CAN2 is not set # CONFIG_STM32_CCMDATARAM is not set # CONFIG_STM32_CRC is not set # CONFIG_STM32_CRYP is not set # CONFIG_STM32_DMA1 is not set # CONFIG_STM32_DMA2 is not set # CONFIG_STM32_DAC1 is not set # CONFIG_STM32_DAC2 is not set # CONFIG_STM32_DCMI is not set CONFIG_STM32_ETHMAC=y # CONFIG_STM32_FSMC is not set # CONFIG_STM32_HASH is not set CONFIG_STM32_I2C1=y # CONFIG_STM32_I2C2 is not set # CONFIG_STM32_I2C3 is not set CONFIG_STM32_OTGFS=y # CONFIG_STM32_OTGHS is not set CONFIG_STM32_PWR=y # CONFIG_STM32_RNG is not set CONFIG_STM32_SDIO=y CONFIG_STM32_SPI1=y # CONFIG_STM32_SPI2 is not set # CONFIG_STM32_SPI3 is not set CONFIG_STM32_SYSCFG=y CONFIG_STM32_TIM1=y # CONFIG_STM32_TIM2 is not set CONFIG_STM32_TIM3=y # CONFIG_STM32_TIM4 is not set # CONFIG_STM32_TIM5 is not set # CONFIG_STM32_TIM6 is not set # CONFIG_STM32_TIM7 is not set # CONFIG_STM32_TIM8 is not set # CONFIG_STM32_TIM9 is not set # CONFIG_STM32_TIM10 is not set # CONFIG_STM32_TIM11 is not set # CONFIG_STM32_TIM12 is not set # CONFIG_STM32_TIM13 is not set # CONFIG_STM32_TIM14 is not set # CONFIG_STM32_USART1 is not set # CONFIG_STM32_USART2 is not set # CONFIG_STM32_USART3 is not set # CONFIG_STM32_UART4 is not set # CONFIG_STM32_UART5 is not set CONFIG_STM32_USART6=y # CONFIG_STM32_IWDG is not set # CONFIG_STM32_WWDG is not set CONFIG_STM32_ADC=y CONFIG_STM32_SPI=y CONFIG_STM32_I2C=y # CONFIG_STM32_NOEXT_VECTORS is not set # # Alternate Pin Mapping # # CONFIG_STM32_FLASH_PREFETCH is not set # CONFIG_STM32_JTAG_DISABLE is not set # CONFIG_STM32_JTAG_FULL_ENABLE is not set # CONFIG_STM32_JTAG_NOJNTRST_ENABLE is not set CONFIG_STM32_JTAG_SW_ENABLE=y # CONFIG_STM32_DISABLE_IDLE_SLEEP_DURING_DEBUG is not set # CONFIG_STM32_FORCEPOWER is not set # CONFIG_ARCH_BOARD_STM32_CUSTOM_CLOCKCONFIG is not set # CONFIG_STM32_CCMEXCLUDE is not set # # Timer Configuration # # CONFIG_STM32_ONESHOT is not set # CONFIG_STM32_FREERUN is not set CONFIG_STM32_TIM1_PWM=y CONFIG_STM32_TIM1_MODE=0 CONFIG_STM32_TIM1_CHANNEL=1 CONFIG_STM32_TIM1_CHMODE=0 # CONFIG_STM32_TIM3_PWM is not set # CONFIG_STM32_PWM_MULTICHAN is not set # CONFIG_STM32_TIM1_ADC is not set CONFIG_STM32_TIM3_ADC=y CONFIG_STM32_TIM3_ADC1=y CONFIG_HAVE_ADC1_TIMER=y CONFIG_STM32_ADC1_SAMPLE_FREQUENCY=100 CONFIG_STM32_ADC1_TIMTRIG=0 # CONFIG_STM32_TIM1_CAP is not set # CONFIG_STM32_TIM2_CAP is not set # CONFIG_STM32_TIM3_CAP is not set # CONFIG_STM32_TIM4_CAP is not set # CONFIG_STM32_TIM5_CAP is not set # CONFIG_STM32_TIM8_CAP is not set # CONFIG_STM32_TIM9_CAP is not set # CONFIG_STM32_TIM10_CAP is not set # CONFIG_STM32_TIM11_CAP is not set # CONFIG_STM32_TIM12_CAP is not set # CONFIG_STM32_TIM13_CAP is not set # CONFIG_STM32_TIM14_CAP is not set # # ADC Configuration # CONFIG_STM32_USART=y CONFIG_STM32_SERIALDRIVER=y # # U[S]ART Configuration # # # U[S]ART Device Configuration # # CONFIG_STM32_USART2_SERIALDRIVER is not set # CONFIG_STM32_USART2_1WIREDRIVER is not set CONFIG_STM32_USART6_SERIALDRIVER=y # CONFIG_STM32_USART6_1WIREDRIVER is not set # CONFIG_USART6_RS485 is not set # # Serial Driver Configuration # # CONFIG_SERIAL_DISABLE_REORDERING is not set # CONFIG_STM32_FLOWCONTROL_BROKEN is not set # CONFIG_STM32_USART_BREAKS is not set # CONFIG_STM32_USART_SINGLEWIRE is not set # # SPI Configuration # # CONFIG_STM32_SPI_INTERRUPTS is not set # CONFIG_STM32_SPI_DMA is not set # # I2C Configuration # # CONFIG_STM32_I2C_ALT is not set # CONFIG_STM32_I2C_DYNTIMEO is not set CONFIG_STM32_I2CTIMEOSEC=0 CONFIG_STM32_I2CTIMEOMS=500 CONFIG_STM32_I2CTIMEOTICKS=500 # CONFIG_STM32_I2C_DUTY16_9 is not set # # SDIO Configuration # CONFIG_SDIO_DMAPRIO=0x00010000 # CONFIG_STM32_HAVE_RTC_COUNTER is not set # CONFIG_STM32_HAVE_RTC_SUBSECONDS is not set # # Ethernet MAC configuration # CONFIG_STM32_PHYADDR=0 # CONFIG_STM32_PHYINIT is not set # CONFIG_STM32_MII is not set CONFIG_STM32_AUTONEG=y CONFIG_STM32_PHYSR=31 CONFIG_STM32_PHYSR_ALTCONFIG=y CONFIG_STM32_PHYSR_ALTMODE=0x001c CONFIG_STM32_PHYSR_10HD=0x0004 CONFIG_STM32_PHYSR_100HD=0x0008 CONFIG_STM32_PHYSR_10FD=0x0014 CONFIG_STM32_PHYSR_100FD=0x0018 # CONFIG_STM32_ETH_PTP is not set CONFIG_STM32_RMII=y # CONFIG_STM32_RMII_MCO1 is not set # CONFIG_STM32_RMII_MCO2 is not set CONFIG_STM32_RMII_EXTCLK=y CONFIG_STM32_ETHMAC_HPWORK=y # # USB FS Host Configuration # # # USB HS Host Configuration # # # USB Host Debug Configuration # # # USB Device Configuration # # # Architecture Options # # CONFIG_ARCH_NOINTC is not set # CONFIG_ARCH_VECNOTIRQ is not set # CONFIG_ARCH_DMA is not set CONFIG_ARCH_HAVE_IRQPRIO=y # 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_MULTICPU 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 is not set # CONFIG_ARCH_IRQPRIO is not set CONFIG_ARCH_STACKDUMP=y # CONFIG_ENDIAN_BIG is not set # CONFIG_ARCH_IDLE_CUSTOM is not set # CONFIG_ARCH_HAVE_RAMFUNCS is not set CONFIG_ARCH_HAVE_RAMVECTORS=y # CONFIG_ARCH_RAMVECTORS is not set # # Board Settings # CONFIG_BOARD_LOOPSPERMSEC=16717 # CONFIG_ARCH_CALIBRATION is not set # # Interrupt options # CONFIG_ARCH_HAVE_INTERRUPTSTACK=y CONFIG_ARCH_INTERRUPTSTACK=0 CONFIG_ARCH_HAVE_HIPRI_INTERRUPT=y # CONFIG_ARCH_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=0x20000000 CONFIG_RAM_SIZE=114688 # CONFIG_ARCH_HAVE_SDRAM is not set # # Board Selection # CONFIG_ARCH_BOARD_STM32F4_DISCOVERY=y # CONFIG_ARCH_BOARD_MIKROE_STM32F4 is not set # CONFIG_ARCH_BOARD_CUSTOM is not set CONFIG_ARCH_BOARD="stm32f4discovery" # # Common Board Options # CONFIG_ARCH_HAVE_LEDS=y CONFIG_ARCH_LEDS=y CONFIG_ARCH_HAVE_BUTTONS=y CONFIG_ARCH_BUTTONS=y CONFIG_ARCH_HAVE_IRQBUTTONS=y # CONFIG_ARCH_IRQBUTTONS is not set # # Board-Specific Options # CONFIG_STM32F4DISBB=y # CONFIG_BOARD_CRASHDUMP is not set CONFIG_LIB_BOARDCTL=y # CONFIG_BOARDCTL_RESET is not set # CONFIG_BOARDCTL_UNIQUEID is not set CONFIG_BOARDCTL_USBDEVCTRL=y # CONFIG_BOARDCTL_TSCTEST is not set # CONFIG_BOARDCTL_GRAPHICS is not set # CONFIG_BOARDCTL_IOCTL is not set # # 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=10000 # CONFIG_SYSTEM_TIME64 is not set CONFIG_CLOCK_MONOTONIC=y CONFIG_ARCH_HAVE_TIMEKEEPING=y # CONFIG_JULIAN_TIME is not set CONFIG_START_YEAR=2013 CONFIG_START_MONTH=1 CONFIG_START_DAY=27 CONFIG_MAX_WDOGPARMS=2 CONFIG_PREALLOC_WDOGS=8 CONFIG_WDOG_INTRESERVE=1 CONFIG_PREALLOC_TIMERS=4 # # Tasks and Scheduling # # CONFIG_SPINLOCK is not set # CONFIG_INIT_NONE is not set CONFIG_INIT_ENTRYPOINT=y # CONFIG_INIT_FILEPATH is not set CONFIG_USER_ENTRYPOINT="nsh_main" CONFIG_RR_INTERVAL=200 # CONFIG_SCHED_SPORADIC is not set CONFIG_TASK_NAME_SIZE=31 CONFIG_MAX_TASKS=16 # CONFIG_SCHED_HAVE_PARENT is not set CONFIG_SCHED_WAITPID=y # # Pthread Options # CONFIG_MUTEX_TYPES=y 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 # # Files and I/O # CONFIG_DEV_CONSOLE=y # CONFIG_FDCLONE_DISABLE is not set # CONFIG_FDCLONE_STDIO is not set CONFIG_SDCLONE_DISABLE=y CONFIG_NFILE_DESCRIPTORS=8 CONFIG_NFILE_STREAMS=8 CONFIG_NAME_MAX=32 # CONFIG_PRIORITY_INHERITANCE is not set # # RTOS hooks # # CONFIG_BOARD_INITIALIZE is not set # CONFIG_SCHED_STARTHOOK is not set # CONFIG_SCHED_ATEXIT is not set # CONFIG_SCHED_ONEXIT is not set # CONFIG_SIG_EVTHREAD is not set # # Signal Numbers # CONFIG_SIG_SIGUSR1=1 CONFIG_SIG_SIGUSR2=2 CONFIG_SIG_SIGALARM=3 CONFIG_SIG_SIGCONDTIMEDOUT=16 CONFIG_SIG_SIGWORK=17 # # POSIX Message Queue Options # CONFIG_PREALLOC_MQ_MSGS=4 CONFIG_MQ_MAXMSGSIZE=32 # CONFIG_MODULE is not set # # Work queue support # CONFIG_SCHED_WORKQUEUE=y CONFIG_SCHED_HPWORK=y CONFIG_SCHED_HPWORKPRIORITY=224 CONFIG_SCHED_HPWORKPERIOD=50000 CONFIG_SCHED_HPWORKSTACKSIZE=2048 # CONFIG_SCHED_LPWORK is not set # # Stack and heap information # CONFIG_IDLETHREAD_STACKSIZE=2048 CONFIG_USERMAIN_STACKSIZE=2048 CONFIG_PTHREAD_STACK_MIN=256 CONFIG_PTHREAD_STACK_DEFAULT=2048 # CONFIG_LIB_SYSCALL is not set # # Device Drivers # # CONFIG_DISABLE_POLL is not set CONFIG_DEV_NULL=y # CONFIG_DEV_ZERO is not set # CONFIG_DEV_URANDOM is not set # CONFIG_DEV_LOOP is not set # # Buffering # # CONFIG_DRVR_WRITEBUFFER is not set # CONFIG_DRVR_READAHEAD is not set # CONFIG_RAMDISK is not set # CONFIG_CAN is not set CONFIG_ARCH_HAVE_PWM_PULSECOUNT=y # CONFIG_ARCH_HAVE_PWM_MULTICHAN is not set CONFIG_PWM=y # CONFIG_PWM_PULSECOUNT is not set CONFIG_ARCH_HAVE_I2CRESET=y CONFIG_I2C=y # CONFIG_I2C_SLAVE is not set # CONFIG_I2C_POLLED is not set # CONFIG_I2C_RESET is not set # CONFIG_I2C_TRACE is not set # CONFIG_I2C_DRIVER is not set CONFIG_SPI=y # CONFIG_ARCH_HAVE_SPI_CRCGENERATION is not set # CONFIG_ARCH_HAVE_SPI_CS_CONTROL is not set CONFIG_ARCH_HAVE_SPI_BITORDER=y # CONFIG_SPI_SLAVE is not set CONFIG_SPI_EXCHANGE=y # CONFIG_SPI_CMDDATA is not set # CONFIG_SPI_CALLBACK is not set # CONFIG_SPI_HWFEATURES is not set # CONFIG_SPI_BITORDER is not set # CONFIG_SPI_CS_DELAY_CONTROL is not set # CONFIG_SPI_DRIVER is not set # CONFIG_SPI_BITBANG is not set # CONFIG_I2S is not set # # Timer Driver Support # # CONFIG_TIMER is not set # CONFIG_ONESHOT is not set # CONFIG_RTC is not set # CONFIG_WATCHDOG is not set # CONFIG_TIMERS_CS2100CP is not set CONFIG_ANALOG=y CONFIG_ADC=y CONFIG_ADC_FIFOSIZE=8 # CONFIG_ADC_NO_STARTUP_CONV is not set # CONFIG_ADC_ADS1242 is not set # CONFIG_ADC_ADS125X is not set # CONFIG_ADC_PGA11X is not set # CONFIG_DAC is not set # CONFIG_AUDIO_DEVICES is not set # CONFIG_VIDEO_DEVICES is not set # CONFIG_BCH is not set # CONFIG_INPUT is not set # # IO Expander/GPIO Support # # CONFIG_IOEXPANDER is not set # CONFIG_DEV_GPIO is not set # # LCD Driver Support # # CONFIG_LCD is not set # CONFIG_SLCD is not set # # LED Support # # CONFIG_USERLED is not set # CONFIG_RGBLED is not set # CONFIG_PCA9635PW is not set # CONFIG_NCP5623C is not set CONFIG_MMCSD=y CONFIG_MMCSD_NSLOTS=1 # CONFIG_MMCSD_READONLY is not set # CONFIG_MMCSD_MULTIBLOCK_DISABLE is not set CONFIG_MMCSD_MMCSUPPORT=y CONFIG_MMCSD_HAVECARDDETECT=y CONFIG_MMCSD_SPI=y CONFIG_MMCSD_SPICLOCK=20000000 CONFIG_MMCSD_SPIMODE=0 CONFIG_ARCH_HAVE_SDIO=y CONFIG_ARCH_HAVE_SDIOWAIT_WRCOMPLETE=y CONFIG_MMCSD_SDIO=y CONFIG_SDIO_PREFLIGHT=y # CONFIG_SDIO_MUXBUS is not set # CONFIG_MMCSD_SDIOWAIT_WRCOMPLETE is not set # CONFIG_SDIO_BLOCKSETUP is not set # CONFIG_MODEM is not set # CONFIG_MTD is not set # CONFIG_EEPROM is not set CONFIG_NETDEVICES=y # # General Ethernet MAC Driver Options # CONFIG_NETDEV_LOOPBACK=y CONFIG_LOOPBACK_HPWORK=y # CONFIG_NETDEV_TELNET is not set CONFIG_NETDEV_MULTINIC=y CONFIG_ARCH_HAVE_NETDEV_STATISTICS=y CONFIG_NETDEV_LATEINIT=y # # External Ethernet MAC Device Support # # CONFIG_NET_DM90x0 is not set # CONFIG_ENC28J60 is not set # CONFIG_ENCX24J600 is not set # CONFIG_NET_SLIP is not set # CONFIG_NET_FTMAC100 is not set # # External Ethernet PHY Device Support # # CONFIG_ARCH_PHY_INTERRUPT is not set # CONFIG_ETH0_PHY_NONE is not set # CONFIG_ETH0_PHY_AM79C874 is not set # CONFIG_ETH0_PHY_KS8721 is not set # CONFIG_ETH0_PHY_KSZ8041 is not set # CONFIG_ETH0_PHY_KSZ8051 is not set # CONFIG_ETH0_PHY_KSZ8061 is not set # CONFIG_ETH0_PHY_KSZ8081 is not set # CONFIG_ETH0_PHY_KSZ90x1 is not set # CONFIG_ETH0_PHY_DP83848C is not set CONFIG_ETH0_PHY_LAN8720=y # CONFIG_ETH0_PHY_LAN8740 is not set # CONFIG_ETH0_PHY_LAN8740A is not set # CONFIG_ETH0_PHY_LAN8742A is not set # CONFIG_ETH0_PHY_DM9161 is not set CONFIG_ETH1_PHY_NONE=y # CONFIG_ETH1_PHY_AM79C874 is not set # CONFIG_ETH1_PHY_KS8721 is not set # CONFIG_ETH1_PHY_KSZ8041 is not set # CONFIG_ETH1_PHY_KSZ8051 is not set # CONFIG_ETH1_PHY_KSZ8081 is not set # CONFIG_ETH1_PHY_KSZ90x1 is not set # CONFIG_ETH1_PHY_DP83848C is not set # CONFIG_ETH1_PHY_LAN8720 is not set # CONFIG_ETH1_PHY_DM9161 is not set CONFIG_PIPES=y CONFIG_DEV_PIPE_MAXSIZE=1024 CONFIG_DEV_PIPE_SIZE=1024 CONFIG_DEV_FIFO_SIZE=1024 # CONFIG_PM is not set # CONFIG_POWER is not set # CONFIG_SENSORS is not set CONFIG_SERIAL=y # CONFIG_DEV_LOWCONSOLE is not set CONFIG_SERIAL_REMOVABLE=y # CONFIG_SERIAL_CONSOLE is not set # CONFIG_16550_UART is not set # CONFIG_UART_SERIALDRIVER is not set # CONFIG_UART0_SERIALDRIVER is not set # CONFIG_UART1_SERIALDRIVER is not set # CONFIG_UART2_SERIALDRIVER is not set # CONFIG_UART3_SERIALDRIVER is not set # CONFIG_UART4_SERIALDRIVER is not set # CONFIG_UART5_SERIALDRIVER is not set # CONFIG_UART6_SERIALDRIVER is not set # CONFIG_UART7_SERIALDRIVER is not set # CONFIG_UART8_SERIALDRIVER is not set # CONFIG_SCI0_SERIALDRIVER is not set # CONFIG_SCI1_SERIALDRIVER is not set # CONFIG_USART0_SERIALDRIVER is not set # CONFIG_USART1_SERIALDRIVER is not set # CONFIG_USART2_SERIALDRIVER is not set # CONFIG_USART3_SERIALDRIVER is not set # CONFIG_USART4_SERIALDRIVER is not set # CONFIG_USART5_SERIALDRIVER is not set CONFIG_USART6_SERIALDRIVER=y # CONFIG_USART7_SERIALDRIVER is not set # CONFIG_USART8_SERIALDRIVER is not set # CONFIG_OTHER_UART_SERIALDRIVER is not set 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_DMA is not set CONFIG_ARCH_HAVE_SERIAL_TERMIOS=y # CONFIG_USART2_SERIAL_CONSOLE is not set # CONFIG_USART6_SERIAL_CONSOLE is not set # CONFIG_OTHER_SERIAL_CONSOLE is not set CONFIG_NO_SERIAL_CONSOLE=y # # USART6 Configuration # CONFIG_USART6_RXBUFSIZE=256 CONFIG_USART6_TXBUFSIZE=256 CONFIG_USART6_BAUD=115200 CONFIG_USART6_BITS=8 CONFIG_USART6_PARITY=0 CONFIG_USART6_2STOP=0 # CONFIG_USART6_IFLOWCONTROL is not set # CONFIG_USART6_OFLOWCONTROL is not set # CONFIG_USART6_DMA is not set # CONFIG_PSEUDOTERM is not set CONFIG_USBDEV=y # # USB Device Controller Driver Options # # CONFIG_USBDEV_ISOCHRONOUS is not set # CONFIG_USBDEV_DUALSPEED is not set CONFIG_USBDEV_SELFPOWERED=y # CONFIG_USBDEV_BUSPOWERED is not set CONFIG_USBDEV_MAXPOWER=100 # CONFIG_USBDEV_DMA is not set # CONFIG_ARCH_USBDEV_STALLQUEUE is not set # CONFIG_USBDEV_TRACE is not set # # USB Device Class Driver Options # # CONFIG_USBDEV_COMPOSITE is not set # CONFIG_PL2303 is not set CONFIG_CDCACM=y CONFIG_CDCACM_CONSOLE=y CONFIG_CDCACM_EP0MAXPACKET=64 CONFIG_CDCACM_EPINTIN=1 CONFIG_CDCACM_EPINTIN_FSSIZE=64 CONFIG_CDCACM_EPINTIN_HSSIZE=64 CONFIG_CDCACM_EPBULKOUT=3 CONFIG_CDCACM_EPBULKOUT_FSSIZE=64 CONFIG_CDCACM_EPBULKOUT_HSSIZE=512 CONFIG_CDCACM_EPBULKIN=2 CONFIG_CDCACM_EPBULKIN_FSSIZE=64 CONFIG_CDCACM_EPBULKIN_HSSIZE=512 CONFIG_CDCACM_NRDREQS=4 CONFIG_CDCACM_NWRREQS=4 CONFIG_CDCACM_BULKIN_REQLEN=96 CONFIG_CDCACM_RXBUFSIZE=256 CONFIG_CDCACM_TXBUFSIZE=256 CONFIG_CDCACM_VENDORID=0x0525 CONFIG_CDCACM_PRODUCTID=0xa4a7 CONFIG_CDCACM_VENDORSTR="NuttX" CONFIG_CDCACM_PRODUCTSTR="CDC/ACM Serial" # CONFIG_USBMSC is not set # CONFIG_USBHOST is not set # CONFIG_HAVE_USBTRACE is not set # CONFIG_DRIVERS_WIRELESS is not set # CONFIG_DRIVERS_CONTACTLESS is not set # # System Logging # # CONFIG_ARCH_SYSLOG is not set # CONFIG_RAMLOG is not set # CONFIG_SYSLOG_INTBUFFER is not set # CONFIG_SYSLOG_TIMESTAMP is not set # CONFIG_SYSLOG_SERIAL_CONSOLE is not set CONFIG_SYSLOG_CHAR=y # CONFIG_SYSLOG_CONSOLE is not set # CONFIG_SYSLOG_NONE is not set # CONFIG_SYSLOG_FILE is not set # CONFIG_CONSOLE_SYSLOG is not set CONFIG_SYSLOG_CHAR_CRLF=y CONFIG_SYSLOG_DEVPATH="/dev/ttyS0" # CONFIG_SYSLOG_CHARDEV is not set # # Networking Support # CONFIG_ARCH_HAVE_NET=y CONFIG_ARCH_HAVE_PHY=y CONFIG_NET=y # CONFIG_NET_PROMISCUOUS is not set # # Driver buffer configuration # CONFIG_NET_ETH_MTU=590 CONFIG_NET_ETH_TCP_RECVWNDO=536 CONFIG_NET_GUARDSIZE=2 # # Data link support # CONFIG_NET_MULTILINK=y CONFIG_NET_ETHERNET=y CONFIG_NET_LOOPBACK=y # CONFIG_NET_TUN is not set # # Network Device Operations # # CONFIG_NETDEV_PHY_IOCTL is not set # # Internet Protocol Selection # CONFIG_NET_IPv4=y # CONFIG_NET_IPv6 is not set # # Socket Support # CONFIG_NSOCKET_DESCRIPTORS=8 CONFIG_NET_NACTIVESOCKETS=16 CONFIG_NET_SOCKOPTS=y # CONFIG_NET_SOLINGER is not set # # Raw Socket Support # # CONFIG_NET_PKT is not set # # Unix Domain Socket Support # CONFIG_NET_LOCAL=y CONFIG_NET_LOCAL_STREAM=y CONFIG_NET_LOCAL_DGRAM=y # # TCP/IP Networking # CONFIG_NET_TCP=y # CONFIG_NET_TCPURGDATA is not set CONFIG_NET_TCP_CONNS=8 CONFIG_NET_MAX_LISTENPORTS=20 CONFIG_NET_TCP_READAHEAD=y CONFIG_NET_TCP_WRITE_BUFFERS=y CONFIG_NET_TCP_NWRBCHAINS=8 CONFIG_NET_TCP_RECVDELAY=0 CONFIG_NET_TCPBACKLOG=y # CONFIG_NET_SENDFILE is not set # # UDP Networking # CONFIG_NET_UDP=y # CONFIG_NET_UDP_CHECKSUMS is not set CONFIG_NET_UDP_CONNS=8 # CONFIG_NET_BROADCAST is not set # CONFIG_NET_RXAVAIL is not set CONFIG_NET_UDP_READAHEAD=y # # ICMP Networking Support # # CONFIG_NET_ICMP is not set # # IGMPv2 Client Support # # CONFIG_NET_IGMP is not set # # ARP Configuration # CONFIG_NET_ARP=y CONFIG_NET_ARPTAB_SIZE=16 CONFIG_NET_ARP_MAXAGE=120 # CONFIG_NET_ARP_IPIN is not set CONFIG_NET_ARP_SEND=y CONFIG_ARP_SEND_MAXTRIES=5 CONFIG_ARP_SEND_DELAYMSEC=20 # # Network I/O Buffer Support # CONFIG_NET_IOB=y CONFIG_IOB_NBUFFERS=36 CONFIG_IOB_BUFSIZE=196 CONFIG_IOB_NCHAINS=8 CONFIG_IOB_THROTTLE=8 # CONFIG_NET_ARCH_INCR32 is not set # CONFIG_NET_ARCH_CHKSUM is not set # CONFIG_NET_STATISTICS is not set # # Routing Table Configuration # # CONFIG_NET_ROUTE is not set CONFIG_NET_HOSTNAME="" # # Crypto API # # CONFIG_CRYPTO 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_NAMED_SEMAPHORES is not set CONFIG_FS_MQUEUE_MPATH="/var/mqueue" # CONFIG_FS_RAMMAP is not set CONFIG_FS_FAT=y CONFIG_FAT_LCNAMES=y CONFIG_FAT_LFN=y CONFIG_FAT_MAXFNAME=32 # CONFIG_FS_FATTIME is not set # CONFIG_FAT_FORCE_INDIRECT is not set # CONFIG_FAT_DMAMEMORY is not set # CONFIG_FAT_DIRECT_RETRY is not set # CONFIG_NFS is not set # CONFIG_FS_NXFFS is not set CONFIG_FS_ROMFS=y # CONFIG_FS_TMPFS is not set # CONFIG_FS_SMARTFS is not set # CONFIG_FS_BINFS is not set CONFIG_FS_PROCFS=y # CONFIG_FS_PROCFS_REGISTER is not set # # Exclude individual procfs entries # # CONFIG_FS_PROCFS_EXCLUDE_PROCESS is not set # CONFIG_FS_PROCFS_EXCLUDE_UPTIME is not set # CONFIG_FS_PROCFS_EXCLUDE_MOUNTS is not set # CONFIG_FS_PROCFS_EXCLUDE_NET is not set # CONFIG_FS_UNIONFS is not set # # Graphics Support # # CONFIG_NX is not set # # Memory Management # # CONFIG_MM_SMALL is not set CONFIG_MM_REGIONS=2 # CONFIG_ARCH_HAVE_HEAP2 is not set # CONFIG_GRAN is not set # # Audio Support # # CONFIG_AUDIO is not set # # Wireless Support # # # Binary Loader # # CONFIG_BINFMT_DISABLE is not set # CONFIG_BINFMT_EXEPATH is not set # CONFIG_NXFLAT is not set # CONFIG_ELF is not set CONFIG_BUILTIN=y # CONFIG_PIC is not set # CONFIG_SYMTAB_ORDEREDBYNAME 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 is not set CONFIG_LIBC_LONG_LONG=y # CONFIG_LIBC_IOCTL_VARIADIC is not set # CONFIG_LIBC_WCHAR is not set # CONFIG_LIBC_LOCALE is not set 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_LIBC_EXECFUNCS is not set CONFIG_POSIX_SPAWN_PROXY_STACKSIZE=1024 CONFIG_TASK_SPAWN_DEFAULT_STACKSIZE=2048 # CONFIG_LIBC_STRERROR 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 is not set CONFIG_ARCH_HAVE_TLS=y # CONFIG_TLS is not set # CONFIG_LIBC_IPv6_ADDRCONV is not set CONFIG_LIBC_NETDB=y # CONFIG_NETDB_HOSTFILE is not set # CONFIG_NETDB_DNSCLIENT is not set # # Non-standard Library Support # # CONFIG_LIB_CRC64_FAST is not set # CONFIG_LIB_KBDCODEC is not set # CONFIG_LIB_SLCDCODEC is not set # CONFIG_LIB_HEX2BIN is not set # # Basic CXX Support # # CONFIG_C99_BOOL8 is not set CONFIG_HAVE_CXX=y CONFIG_HAVE_CXXINITIALIZE=y # CONFIG_CXX_NEWLONG is not set # # uClibc++ Standard C++ Library # # CONFIG_UCLIBCXX is not set # # Application Configuration # # # NxWidgets/NxWM # # # Built-In Applications # CONFIG_BUILTIN_PROXY_STACKSIZE=1024 # # CAN Utilities # # # Examples # # CONFIG_EXAMPLES_ADC is not set # CONFIG_EXAMPLES_BRIDGE is not set # CONFIG_EXAMPLES_BUTTONS is not set # CONFIG_EXAMPLES_CCTYPE is not set # CONFIG_EXAMPLES_CHAT is not set # CONFIG_EXAMPLES_CONFIGDATA is not set # CONFIG_EXAMPLES_CPUHOG is not set # CONFIG_EXAMPLES_CXXTEST is not set # CONFIG_EXAMPLES_DHCPD is not set # CONFIG_EXAMPLES_DISCOVER is not set # CONFIG_EXAMPLES_ELF is not set # CONFIG_EXAMPLES_FSTEST is not set # CONFIG_EXAMPLES_FTPC is not set # CONFIG_EXAMPLES_FTPD is not set # CONFIG_EXAMPLES_HELLO is not set # CONFIG_EXAMPLES_HELLOXX is not set # CONFIG_EXAMPLES_HIDKBD is not set # CONFIG_EXAMPLES_IGMP is not set # CONFIG_EXAMPLES_JSON is not set # CONFIG_EXAMPLES_KEYPADTEST is not set # CONFIG_EXAMPLES_MEDIA is not set # CONFIG_EXAMPLES_MM is not set # CONFIG_EXAMPLES_MODBUS is not set # CONFIG_EXAMPLES_MOUNT is not set # CONFIG_EXAMPLES_NETLOOP is not set # CONFIG_EXAMPLES_NETTEST is not set # CONFIG_EXAMPLES_NRF24L01TERM is not set CONFIG_EXAMPLES_NSH=y CONFIG_EXAMPLES_NSH_CXXINITIALIZE=y # CONFIG_EXAMPLES_NULL is not set # CONFIG_EXAMPLES_NX is not set # CONFIG_EXAMPLES_NXFFS is not set # CONFIG_EXAMPLES_NXHELLO is not set # CONFIG_EXAMPLES_NXIMAGE is not set # CONFIG_EXAMPLES_NXLINES is not set # CONFIG_EXAMPLES_NXTERM is not set # CONFIG_EXAMPLES_NXTEXT is not set # CONFIG_EXAMPLES_OSTEST is not set # CONFIG_EXAMPLES_PCA9635 is not set # CONFIG_EXAMPLES_PIPE is not set # CONFIG_EXAMPLES_POSIXSPAWN is not set # CONFIG_EXAMPLES_PPPD is not set # CONFIG_EXAMPLES_PWM is not set # CONFIG_EXAMPLES_RFID_READUID is not set # CONFIG_EXAMPLES_RGBLED is not set # CONFIG_EXAMPLES_SENDMAIL is not set # CONFIG_EXAMPLES_SERIALBLASTER is not set # CONFIG_EXAMPLES_SERIALRX is not set # CONFIG_EXAMPLES_SERLOOP is not set # CONFIG_EXAMPLES_SLCD is not set # CONFIG_EXAMPLES_SMART is not set # CONFIG_EXAMPLES_SMART_TEST is not set # CONFIG_EXAMPLES_SMP is not set # CONFIG_EXAMPLES_TCPECHO is not set # CONFIG_EXAMPLES_TELNETD is not set # CONFIG_EXAMPLES_TIFF is not set # CONFIG_EXAMPLES_TOUCHSCREEN is not set # CONFIG_EXAMPLES_UDGRAM is not set # CONFIG_EXAMPLES_UDP is not set # CONFIG_EXAMPLES_UDPBLASTER is not set # CONFIG_EXAMPLES_USBSERIAL is not set # CONFIG_EXAMPLES_USBTERM is not set # CONFIG_EXAMPLES_USTREAM is not set # CONFIG_EXAMPLES_WATCHDOG is not set # CONFIG_EXAMPLES_WEBSERVER is not set # CONFIG_EXAMPLES_XMLRPC is not set # # File System Utilities # # CONFIG_FSUTILS_INIFILE is not set # CONFIG_FSUTILS_PASSWD is not set # # GPS Utilities # # CONFIG_GPSUTILS_MINMEA_LIB is not set # # Graphics Support # # CONFIG_TIFF is not set # CONFIG_GRAPHICS_TRAVELER is not set # # Interpreters # # CONFIG_INTERPRETERS_BAS is not set # CONFIG_INTERPRETERS_FICL is not set # CONFIG_INTERPRETERS_MICROPYTHON is not set # CONFIG_INTERPRETERS_MINIBASIC is not set # CONFIG_INTERPRETERS_PCODE is not set # # FreeModBus # # CONFIG_MODBUS is not set # # Network Utilities # # CONFIG_NETUTILS_CHAT is not set # CONFIG_NETUTILS_CODECS is not set # CONFIG_NETUTILS_DHCPD is not set # CONFIG_NETUTILS_DISCOVER is not set # CONFIG_NETUTILS_ESP8266 is not set # CONFIG_NETUTILS_FTPC is not set # CONFIG_NETUTILS_FTPD is not set # CONFIG_NETUTILS_JSON is not set CONFIG_NETUTILS_NETLIB=y # CONFIG_NETUTILS_NTPCLIENT is not set # CONFIG_NETUTILS_PPPD 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_XMLRPC is not set # # NSH Library # CONFIG_NSH_LIBRARY=y # CONFIG_NSH_MOTD is not set # # Command Line Configuration # CONFIG_NSH_READLINE=y # CONFIG_NSH_CLE is not set CONFIG_NSH_LINELEN=128 # CONFIG_NSH_DISABLE_SEMICOLON is not set CONFIG_NSH_CMDPARMS=y CONFIG_NSH_MAXARGUMENTS=6 CONFIG_NSH_ARGCAT=y CONFIG_NSH_NESTDEPTH=3 # CONFIG_NSH_DISABLEBG is not set CONFIG_NSH_BUILTIN_APPS=y # # Disable Individual commands # # CONFIG_NSH_DISABLE_ADDROUTE is not set # CONFIG_NSH_DISABLE_ARP is not set # CONFIG_NSH_DISABLE_BASENAME is not set # CONFIG_NSH_DISABLE_CAT is not set # CONFIG_NSH_DISABLE_CD is not set # CONFIG_NSH_DISABLE_CP is not set # CONFIG_NSH_DISABLE_CMP is not set CONFIG_NSH_DISABLE_DATE=y # CONFIG_NSH_DISABLE_DD is not set # CONFIG_NSH_DISABLE_DF is not set # CONFIG_NSH_DISABLE_DELROUTE is not set # CONFIG_NSH_DISABLE_DIRNAME is not set # CONFIG_NSH_DISABLE_ECHO is not set # CONFIG_NSH_DISABLE_EXEC is not set # CONFIG_NSH_DISABLE_EXIT is not set # CONFIG_NSH_DISABLE_FREE is not set # CONFIG_NSH_DISABLE_GET is not set # CONFIG_NSH_DISABLE_HELP is not set # CONFIG_NSH_DISABLE_HEXDUMP is not set # CONFIG_NSH_DISABLE_IFCONFIG is not set # CONFIG_NSH_DISABLE_IFUPDOWN is not set # CONFIG_NSH_DISABLE_KILL is not set # CONFIG_NSH_DISABLE_LOSETUP is not set CONFIG_NSH_DISABLE_LOSMART=y # CONFIG_NSH_DISABLE_LS is not set # CONFIG_NSH_DISABLE_MB is not set # CONFIG_NSH_DISABLE_MKDIR is not set # CONFIG_NSH_DISABLE_MKFATFS is not set # CONFIG_NSH_DISABLE_MKFIFO is not set # CONFIG_NSH_DISABLE_MKRD is not set # CONFIG_NSH_DISABLE_MH is not set # CONFIG_NSH_DISABLE_MOUNT is not set # CONFIG_NSH_DISABLE_MV is not set # CONFIG_NSH_DISABLE_MW is not set CONFIG_NSH_DISABLE_PRINTF=y # CONFIG_NSH_DISABLE_PS is not set # CONFIG_NSH_DISABLE_PUT is not set # CONFIG_NSH_DISABLE_PWD is not set # CONFIG_NSH_DISABLE_RM is not set # CONFIG_NSH_DISABLE_RMDIR is not set # CONFIG_NSH_DISABLE_SET is not set # CONFIG_NSH_DISABLE_SH is not set # CONFIG_NSH_DISABLE_SLEEP is not set # CONFIG_NSH_DISABLE_TIME is not set # CONFIG_NSH_DISABLE_TEST is not set # CONFIG_NSH_DISABLE_UMOUNT is not set # CONFIG_NSH_DISABLE_UNAME is not set # CONFIG_NSH_DISABLE_UNSET is not set # CONFIG_NSH_DISABLE_USLEEP is not set # CONFIG_NSH_DISABLE_WGET is not set # CONFIG_NSH_DISABLE_XD is not set CONFIG_NSH_MMCSDMINOR=0 CONFIG_NSH_MMCSDSLOTNO=0 CONFIG_NSH_MMCSDSPIPORTNO=0 # # Configure Command Options # CONFIG_NSH_CMDOPT_DF_H=y # CONFIG_NSH_CMDOPT_DD_STATS is not set CONFIG_NSH_CODECS_BUFSIZE=128 CONFIG_NSH_CMDOPT_HEXDUMP=y CONFIG_NSH_PROC_MOUNTPOINT="/proc" CONFIG_NSH_FILEIOSIZE=512 # # Scripting Support # # CONFIG_NSH_DISABLESCRIPT is not set # CONFIG_NSH_DISABLE_ITEF is not set # CONFIG_NSH_DISABLE_LOOPS is not set CONFIG_NSH_ROMFSETC=y # CONFIG_NSH_ROMFSRC is not set CONFIG_NSH_ROMFSMOUNTPT="/test" CONFIG_NSH_INITSCRIPT="init.d/rcS" CONFIG_NSH_ROMFSDEVNO=0 CONFIG_NSH_ROMFSSECTSIZE=64 CONFIG_NSH_DEFAULTROMFS=y # CONFIG_NSH_ARCHROMFS is not set # CONFIG_NSH_CUSTOMROMFS is not set CONFIG_NSH_FATDEVNO=1 CONFIG_NSH_FATSECTSIZE=512 CONFIG_NSH_FATNSECTORS=1024 CONFIG_NSH_FATMOUNTPT="/tmp" # # Console Configuration # CONFIG_NSH_CONSOLE=y # CONFIG_NSH_USBCONSOLE is not set # CONFIG_NSH_ALTCONDEV is not set CONFIG_NSH_ARCHINIT=y # # Networking Configuration # CONFIG_NSH_NETINIT=y # CONFIG_NSH_NETINIT_THREAD is not set # # IP Address Configuration # # # IPv4 Addresses # CONFIG_NSH_IPADDR=0x0a000002 CONFIG_NSH_DRIPADDR=0x0a000001 CONFIG_NSH_NETMASK=0xffffff00 # CONFIG_NSH_NOMAC is not set CONFIG_NSH_MAX_ROUNDTRIP=20 # CONFIG_NSH_LOGIN is not set # CONFIG_NSH_CONSOLE_LOGIN is not set # # Platform-specific Support # # CONFIG_PLATFORM_CONFIGDATA is not set # # System Libraries and NSH Add-Ons # # CONFIG_SYSTEM_CDCACM is not set # CONFIG_SYSTEM_CLE is not set # CONFIG_SYSTEM_CUTERM is not set # CONFIG_SYSTEM_FREE is not set # CONFIG_SYSTEM_HEX2BIN is not set # CONFIG_SYSTEM_HEXED is not set # CONFIG_SYSTEM_I2CTOOL is not set # CONFIG_SYSTEM_INSTALL is not set CONFIG_IOTJS=y CONFIG_IOTJS_PRIORITY=100 CONFIG_IOTJS_STACKSIZE=16384 # CONFIG_SYSTEM_NETDB is not set # CONFIG_SYSTEM_RAMTEST is not set CONFIG_READLINE_HAVE_EXTMATCH=y CONFIG_SYSTEM_READLINE=y CONFIG_READLINE_ECHO=y CONFIG_READLINE_TABCOMPLETION=y CONFIG_READLINE_MAX_BUILTINS=64 CONFIG_READLINE_MAX_EXTCMDS=64 CONFIG_READLINE_CMD_HISTORY=y CONFIG_READLINE_CMD_HISTORY_LINELEN=80 CONFIG_READLINE_CMD_HISTORY_LEN=16 # CONFIG_SYSTEM_SUDOKU is not set # CONFIG_SYSTEM_SYSTEM is not set # CONFIG_SYSTEM_TEE is not set # CONFIG_SYSTEM_UBLOXMODEM is not set # CONFIG_SYSTEM_VI is not set # CONFIG_SYSTEM_ZMODEM is not set iotjs-1.0+715/config/nuttx/stm32f4dis/config.default000066400000000000000000001123461371177304000221700ustar00rootroot00000000000000# # Automatically generated file; DO NOT EDIT. # Nuttx/ 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 # # Build Configuration # CONFIG_APPS_DIR="../apps" CONFIG_BUILD_FLAT=y # CONFIG_BUILD_2PASS is not set # # Binary Output Formats # # CONFIG_RRLOAD_BINARY is not set CONFIG_INTELHEX_BINARY=y # CONFIG_MOTOROLA_SREC is not set CONFIG_RAW_BINARY=y # CONFIG_UBOOT_UIMAGE 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 # CONFIG_ARCH_DEBUG_H is not set # # Debug Options # CONFIG_DEBUG_ALERT=y # CONFIG_DEBUG_FEATURES is not set CONFIG_ARCH_HAVE_STACKCHECK=y # CONFIG_STACK_COLORATION is not set CONFIG_ARCH_HAVE_HEAPCHECK=y # CONFIG_HEAP_COLORATION is not set # CONFIG_DEBUG_SYMBOLS is not set CONFIG_ARCH_HAVE_CUSTOMOPT=y # CONFIG_DEBUG_NOOPT is not set # CONFIG_DEBUG_CUSTOMOPT is not set CONFIG_DEBUG_FULLOPT=y # # System Type # CONFIG_ARCH_ARM=y # CONFIG_ARCH_AVR is not set # CONFIG_ARCH_HC is not set # CONFIG_ARCH_MIPS is not set # CONFIG_ARCH_RGMP is not set # CONFIG_ARCH_RENESAS is not set # CONFIG_ARCH_SIM is not set # CONFIG_ARCH_X86 is not set # CONFIG_ARCH_Z16 is not set # CONFIG_ARCH_Z80 is not set CONFIG_ARCH="arm" # # ARM Options # # CONFIG_ARCH_CHIP_A1X is not set # CONFIG_ARCH_CHIP_C5471 is not set # CONFIG_ARCH_CHIP_CALYPSO is not set # CONFIG_ARCH_CHIP_DM320 is not set # CONFIG_ARCH_CHIP_EFM32 is not set # CONFIG_ARCH_CHIP_IMX1 is not set # CONFIG_ARCH_CHIP_IMX6 is not set # CONFIG_ARCH_CHIP_KINETIS is not set # CONFIG_ARCH_CHIP_KL is not set # CONFIG_ARCH_CHIP_LM is not set # CONFIG_ARCH_CHIP_TIVA is not set # CONFIG_ARCH_CHIP_LPC11XX is not set # CONFIG_ARCH_CHIP_LPC17XX is not set # CONFIG_ARCH_CHIP_LPC214X is not set # CONFIG_ARCH_CHIP_LPC2378 is not set # CONFIG_ARCH_CHIP_LPC31XX is not set # CONFIG_ARCH_CHIP_LPC43XX is not set # CONFIG_ARCH_CHIP_NUC1XX is not set # CONFIG_ARCH_CHIP_SAMA5 is not set # CONFIG_ARCH_CHIP_SAMD is not set # CONFIG_ARCH_CHIP_SAML is not set # CONFIG_ARCH_CHIP_SAM34 is not set # CONFIG_ARCH_CHIP_SAMV7 is not set CONFIG_ARCH_CHIP_STM32=y # CONFIG_ARCH_CHIP_STM32F7 is not set # CONFIG_ARCH_CHIP_STM32L4 is not set # CONFIG_ARCH_CHIP_STR71X is not set # CONFIG_ARCH_CHIP_TMS570 is not set # CONFIG_ARCH_CHIP_MOXART is not set # CONFIG_ARCH_ARM7TDMI is not set # CONFIG_ARCH_ARM926EJS is not set # CONFIG_ARCH_ARM920T is not set # CONFIG_ARCH_CORTEXM0 is not set # CONFIG_ARCH_CORTEXM3 is not set CONFIG_ARCH_CORTEXM4=y # CONFIG_ARCH_CORTEXM7 is not set # CONFIG_ARCH_CORTEXA5 is not set # CONFIG_ARCH_CORTEXA8 is not set # CONFIG_ARCH_CORTEXA9 is not set # CONFIG_ARCH_CORTEXR4 is not set # CONFIG_ARCH_CORTEXR4F is not set # CONFIG_ARCH_CORTEXR5 is not set # CONFIG_ARCH_CORTEX5F is not set # CONFIG_ARCH_CORTEXR7 is not set # CONFIG_ARCH_CORTEXR7F is not set CONFIG_ARCH_FAMILY="armv7-m" CONFIG_ARCH_CHIP="stm32" # CONFIG_ARM_TOOLCHAIN_IAR is not set CONFIG_ARM_TOOLCHAIN_GNU=y # CONFIG_ARMV7M_USEBASEPRI is not set CONFIG_ARCH_HAVE_CMNVECTOR=y # CONFIG_ARMV7M_CMNVECTOR is not set # CONFIG_ARMV7M_LAZYFPU is not set CONFIG_ARCH_HAVE_FPU=y # CONFIG_ARCH_HAVE_DPFPU is not set CONFIG_ARCH_FPU=y # CONFIG_ARCH_HAVE_TRUSTZONE is not set CONFIG_ARM_HAVE_MPU_UNIFIED=y # CONFIG_ARM_MPU is not set # # ARMV7M Configuration Options # # CONFIG_ARMV7M_HAVE_ICACHE is not set # CONFIG_ARMV7M_HAVE_DCACHE is not set # CONFIG_ARMV7M_HAVE_ITCM is not set # CONFIG_ARMV7M_HAVE_DTCM is not set # CONFIG_ARMV7M_TOOLCHAIN_IARL is not set # CONFIG_ARMV7M_TOOLCHAIN_BUILDROOT is not set # CONFIG_ARMV7M_TOOLCHAIN_CODEREDL is not set # CONFIG_ARMV7M_TOOLCHAIN_CODESOURCERYL is not set CONFIG_ARMV7M_TOOLCHAIN_GNU_EABIL=y CONFIG_ARMV7M_HAVE_STACKCHECK=y # CONFIG_ARMV7M_STACKCHECK is not set # CONFIG_ARMV7M_ITMSYSLOG is not set # CONFIG_SERIAL_TERMIOS is not set # CONFIG_SDIO_DMA is not set # CONFIG_SDIO_WIDTH_D1_ONLY is not set # # STM32 Configuration Options # # CONFIG_ARCH_CHIP_STM32L151C6 is not set # CONFIG_ARCH_CHIP_STM32L151C8 is not set # CONFIG_ARCH_CHIP_STM32L151CB is not set # CONFIG_ARCH_CHIP_STM32L151R6 is not set # CONFIG_ARCH_CHIP_STM32L151R8 is not set # CONFIG_ARCH_CHIP_STM32L151RB is not set # CONFIG_ARCH_CHIP_STM32L151V6 is not set # CONFIG_ARCH_CHIP_STM32L151V8 is not set # CONFIG_ARCH_CHIP_STM32L151VB is not set # CONFIG_ARCH_CHIP_STM32L152C6 is not set # CONFIG_ARCH_CHIP_STM32L152C8 is not set # CONFIG_ARCH_CHIP_STM32L152CB is not set # CONFIG_ARCH_CHIP_STM32L152R6 is not set # CONFIG_ARCH_CHIP_STM32L152R8 is not set # CONFIG_ARCH_CHIP_STM32L152RB is not set # CONFIG_ARCH_CHIP_STM32L152V6 is not set # CONFIG_ARCH_CHIP_STM32L152V8 is not set # CONFIG_ARCH_CHIP_STM32L152VB is not set # CONFIG_ARCH_CHIP_STM32L162ZD is not set # CONFIG_ARCH_CHIP_STM32L162VE is not set # CONFIG_ARCH_CHIP_STM32F100C8 is not set # CONFIG_ARCH_CHIP_STM32F100CB is not set # CONFIG_ARCH_CHIP_STM32F100R8 is not set # CONFIG_ARCH_CHIP_STM32F100RB is not set # CONFIG_ARCH_CHIP_STM32F100RC is not set # CONFIG_ARCH_CHIP_STM32F100RD is not set # CONFIG_ARCH_CHIP_STM32F100RE is not set # CONFIG_ARCH_CHIP_STM32F100V8 is not set # CONFIG_ARCH_CHIP_STM32F100VB is not set # CONFIG_ARCH_CHIP_STM32F100VC is not set # CONFIG_ARCH_CHIP_STM32F100VD is not set # CONFIG_ARCH_CHIP_STM32F100VE is not set # CONFIG_ARCH_CHIP_STM32F102CB is not set # CONFIG_ARCH_CHIP_STM32F103T8 is not set # CONFIG_ARCH_CHIP_STM32F103TB is not set # CONFIG_ARCH_CHIP_STM32F103C4 is not set # CONFIG_ARCH_CHIP_STM32F103C8 is not set # CONFIG_ARCH_CHIP_STM32F103CB is not set # CONFIG_ARCH_CHIP_STM32F103R8 is not set # CONFIG_ARCH_CHIP_STM32F103RB is not set # CONFIG_ARCH_CHIP_STM32F103RC is not set # CONFIG_ARCH_CHIP_STM32F103RD is not set # CONFIG_ARCH_CHIP_STM32F103RE is not set # CONFIG_ARCH_CHIP_STM32F103RG is not set # CONFIG_ARCH_CHIP_STM32F103V8 is not set # CONFIG_ARCH_CHIP_STM32F103VB is not set # CONFIG_ARCH_CHIP_STM32F103VC is not set # CONFIG_ARCH_CHIP_STM32F103VE is not set # CONFIG_ARCH_CHIP_STM32F103ZE is not set # CONFIG_ARCH_CHIP_STM32F105VB is not set # CONFIG_ARCH_CHIP_STM32F105RB is not set # CONFIG_ARCH_CHIP_STM32F107VC is not set # CONFIG_ARCH_CHIP_STM32F205RG is not set # CONFIG_ARCH_CHIP_STM32F207IG is not set # CONFIG_ARCH_CHIP_STM32F207ZE is not set # CONFIG_ARCH_CHIP_STM32F302K6 is not set # CONFIG_ARCH_CHIP_STM32F302K8 is not set # CONFIG_ARCH_CHIP_STM32F302CB is not set # CONFIG_ARCH_CHIP_STM32F302CC is not set # CONFIG_ARCH_CHIP_STM32F302RB is not set # CONFIG_ARCH_CHIP_STM32F302RC is not set # CONFIG_ARCH_CHIP_STM32F302VB is not set # CONFIG_ARCH_CHIP_STM32F302VC is not set # CONFIG_ARCH_CHIP_STM32F303K6 is not set # CONFIG_ARCH_CHIP_STM32F303K8 is not set # CONFIG_ARCH_CHIP_STM32F303C6 is not set # CONFIG_ARCH_CHIP_STM32F303C8 is not set # CONFIG_ARCH_CHIP_STM32F303CB is not set # CONFIG_ARCH_CHIP_STM32F303CC is not set # CONFIG_ARCH_CHIP_STM32F303RB is not set # CONFIG_ARCH_CHIP_STM32F303RC is not set # CONFIG_ARCH_CHIP_STM32F303RD is not set # CONFIG_ARCH_CHIP_STM32F303RE is not set # CONFIG_ARCH_CHIP_STM32F303VB is not set # CONFIG_ARCH_CHIP_STM32F303VC is not set # CONFIG_ARCH_CHIP_STM32F372C8 is not set # CONFIG_ARCH_CHIP_STM32F372R8 is not set # CONFIG_ARCH_CHIP_STM32F372V8 is not set # CONFIG_ARCH_CHIP_STM32F372CB is not set # CONFIG_ARCH_CHIP_STM32F372RB is not set # CONFIG_ARCH_CHIP_STM32F372VB is not set # CONFIG_ARCH_CHIP_STM32F372CC is not set # CONFIG_ARCH_CHIP_STM32F372RC is not set # CONFIG_ARCH_CHIP_STM32F372VC is not set # CONFIG_ARCH_CHIP_STM32F373C8 is not set # CONFIG_ARCH_CHIP_STM32F373R8 is not set # CONFIG_ARCH_CHIP_STM32F373V8 is not set # CONFIG_ARCH_CHIP_STM32F373CB is not set # CONFIG_ARCH_CHIP_STM32F373RB is not set # CONFIG_ARCH_CHIP_STM32F373VB is not set # CONFIG_ARCH_CHIP_STM32F373CC is not set # CONFIG_ARCH_CHIP_STM32F373RC is not set # CONFIG_ARCH_CHIP_STM32F373VC is not set # CONFIG_ARCH_CHIP_STM32F401RE is not set # CONFIG_ARCH_CHIP_STM32F411RE is not set # CONFIG_ARCH_CHIP_STM32F411VE is not set # CONFIG_ARCH_CHIP_STM32F405RG is not set # CONFIG_ARCH_CHIP_STM32F405VG is not set # CONFIG_ARCH_CHIP_STM32F405ZG is not set # CONFIG_ARCH_CHIP_STM32F407VE is not set CONFIG_ARCH_CHIP_STM32F407VG=y # CONFIG_ARCH_CHIP_STM32F407ZE is not set # CONFIG_ARCH_CHIP_STM32F407ZG is not set # CONFIG_ARCH_CHIP_STM32F407IE is not set # CONFIG_ARCH_CHIP_STM32F407IG is not set # CONFIG_ARCH_CHIP_STM32F427V is not set # CONFIG_ARCH_CHIP_STM32F427Z is not set # CONFIG_ARCH_CHIP_STM32F427I is not set # CONFIG_ARCH_CHIP_STM32F429V is not set # CONFIG_ARCH_CHIP_STM32F429Z is not set # CONFIG_ARCH_CHIP_STM32F429I is not set # CONFIG_ARCH_CHIP_STM32F429B is not set # CONFIG_ARCH_CHIP_STM32F429N is not set # CONFIG_ARCH_CHIP_STM32F446M is not set # CONFIG_ARCH_CHIP_STM32F446R is not set # CONFIG_ARCH_CHIP_STM32F446V is not set # CONFIG_ARCH_CHIP_STM32F446Z is not set # CONFIG_ARCH_CHIP_STM32F469A is not set # CONFIG_ARCH_CHIP_STM32F469I is not set # CONFIG_ARCH_CHIP_STM32F469B is not set # CONFIG_ARCH_CHIP_STM32F469N is not set CONFIG_STM32_FLASH_CONFIG_DEFAULT=y # CONFIG_STM32_FLASH_CONFIG_4 is not set # CONFIG_STM32_FLASH_CONFIG_6 is not set # CONFIG_STM32_FLASH_CONFIG_8 is not set # CONFIG_STM32_FLASH_CONFIG_B is not set # CONFIG_STM32_FLASH_CONFIG_C is not set # CONFIG_STM32_FLASH_CONFIG_D is not set # CONFIG_STM32_FLASH_CONFIG_E is not set # CONFIG_STM32_FLASH_CONFIG_F is not set # CONFIG_STM32_FLASH_CONFIG_G is not set # CONFIG_STM32_FLASH_CONFIG_I is not set # CONFIG_STM32_STM32L15XX is not set # CONFIG_STM32_ENERGYLITE is not set # CONFIG_STM32_STM32F10XX is not set # CONFIG_STM32_VALUELINE is not set # CONFIG_STM32_CONNECTIVITYLINE is not set # CONFIG_STM32_PERFORMANCELINE is not set # CONFIG_STM32_USBACCESSLINE is not set # CONFIG_STM32_HIGHDENSITY is not set # CONFIG_STM32_MEDIUMDENSITY is not set # CONFIG_STM32_LOWDENSITY is not set # CONFIG_STM32_STM32F20XX is not set # CONFIG_STM32_STM32F205 is not set # CONFIG_STM32_STM32F207 is not set # CONFIG_STM32_STM32F30XX is not set # CONFIG_STM32_STM32F302 is not set # CONFIG_STM32_STM32F303 is not set # CONFIG_STM32_STM32F37XX is not set CONFIG_STM32_STM32F40XX=y # CONFIG_STM32_STM32F401 is not set # CONFIG_STM32_STM32F411 is not set # CONFIG_STM32_STM32F405 is not set CONFIG_STM32_STM32F407=y # CONFIG_STM32_STM32F427 is not set # CONFIG_STM32_STM32F429 is not set # CONFIG_STM32_STM32F446 is not set # CONFIG_STM32_STM32F469 is not set # CONFIG_STM32_DFU is not set # # STM32 Peripheral Support # CONFIG_STM32_HAVE_CCM=y # CONFIG_STM32_HAVE_USBDEV is not set CONFIG_STM32_HAVE_OTGFS=y CONFIG_STM32_HAVE_FSMC=y # CONFIG_STM32_HAVE_LTDC is not set CONFIG_STM32_HAVE_USART3=y CONFIG_STM32_HAVE_UART4=y CONFIG_STM32_HAVE_UART5=y CONFIG_STM32_HAVE_USART6=y # CONFIG_STM32_HAVE_UART7 is not set # CONFIG_STM32_HAVE_UART8 is not set CONFIG_STM32_HAVE_TIM1=y CONFIG_STM32_HAVE_TIM2=y CONFIG_STM32_HAVE_TIM3=y CONFIG_STM32_HAVE_TIM4=y CONFIG_STM32_HAVE_TIM5=y CONFIG_STM32_HAVE_TIM6=y CONFIG_STM32_HAVE_TIM7=y CONFIG_STM32_HAVE_TIM8=y CONFIG_STM32_HAVE_TIM9=y CONFIG_STM32_HAVE_TIM10=y CONFIG_STM32_HAVE_TIM11=y CONFIG_STM32_HAVE_TIM12=y CONFIG_STM32_HAVE_TIM13=y CONFIG_STM32_HAVE_TIM14=y # CONFIG_STM32_HAVE_TIM15 is not set # CONFIG_STM32_HAVE_TIM16 is not set # CONFIG_STM32_HAVE_TIM17 is not set CONFIG_STM32_HAVE_ADC2=y CONFIG_STM32_HAVE_ADC3=y # CONFIG_STM32_HAVE_ADC4 is not set # CONFIG_STM32_HAVE_ADC1_DMA is not set # CONFIG_STM32_HAVE_ADC2_DMA is not set # CONFIG_STM32_HAVE_ADC3_DMA is not set # CONFIG_STM32_HAVE_ADC4_DMA is not set CONFIG_STM32_HAVE_CAN1=y CONFIG_STM32_HAVE_CAN2=y CONFIG_STM32_HAVE_DAC1=y CONFIG_STM32_HAVE_DAC2=y CONFIG_STM32_HAVE_RNG=y CONFIG_STM32_HAVE_ETHMAC=y CONFIG_STM32_HAVE_I2C2=y CONFIG_STM32_HAVE_I2C3=y CONFIG_STM32_HAVE_SPI2=y CONFIG_STM32_HAVE_SPI3=y # CONFIG_STM32_HAVE_SPI4 is not set # CONFIG_STM32_HAVE_SPI5 is not set # CONFIG_STM32_HAVE_SPI6 is not set # CONFIG_STM32_HAVE_SAIPLL is not set # CONFIG_STM32_HAVE_I2SPLL is not set # CONFIG_STM32_ADC1 is not set # CONFIG_STM32_ADC2 is not set # CONFIG_STM32_ADC3 is not set # CONFIG_STM32_BKPSRAM is not set # CONFIG_STM32_CAN1 is not set # CONFIG_STM32_CAN2 is not set # CONFIG_STM32_CCMDATARAM is not set # CONFIG_STM32_CRC is not set # CONFIG_STM32_CRYP is not set # CONFIG_STM32_DMA1 is not set # CONFIG_STM32_DMA2 is not set # CONFIG_STM32_DAC1 is not set # CONFIG_STM32_DAC2 is not set # CONFIG_STM32_DCMI is not set # CONFIG_STM32_ETHMAC is not set # CONFIG_STM32_FSMC is not set # CONFIG_STM32_HASH is not set # CONFIG_STM32_I2C1 is not set # CONFIG_STM32_I2C2 is not set # CONFIG_STM32_I2C3 is not set CONFIG_STM32_OTGFS=y # CONFIG_STM32_OTGHS is not set CONFIG_STM32_PWR=y # CONFIG_STM32_RNG is not set CONFIG_STM32_SDIO=y CONFIG_STM32_SPI1=y # CONFIG_STM32_SPI2 is not set # CONFIG_STM32_SPI3 is not set CONFIG_STM32_SYSCFG=y # CONFIG_STM32_TIM1 is not set # CONFIG_STM32_TIM2 is not set # CONFIG_STM32_TIM3 is not set # CONFIG_STM32_TIM4 is not set # CONFIG_STM32_TIM5 is not set # CONFIG_STM32_TIM6 is not set # CONFIG_STM32_TIM7 is not set # CONFIG_STM32_TIM8 is not set # CONFIG_STM32_TIM9 is not set # CONFIG_STM32_TIM10 is not set # CONFIG_STM32_TIM11 is not set # CONFIG_STM32_TIM12 is not set # CONFIG_STM32_TIM13 is not set # CONFIG_STM32_TIM14 is not set # CONFIG_STM32_USART1 is not set CONFIG_STM32_USART2=y # CONFIG_STM32_USART3 is not set # CONFIG_STM32_UART4 is not set # CONFIG_STM32_UART5 is not set # CONFIG_STM32_USART6 is not set # CONFIG_STM32_IWDG is not set # CONFIG_STM32_WWDG is not set CONFIG_STM32_SPI=y # CONFIG_STM32_NOEXT_VECTORS is not set # # Alternate Pin Mapping # # CONFIG_STM32_FLASH_PREFETCH is not set # CONFIG_STM32_JTAG_DISABLE is not set # CONFIG_STM32_JTAG_FULL_ENABLE is not set # CONFIG_STM32_JTAG_NOJNTRST_ENABLE is not set CONFIG_STM32_JTAG_SW_ENABLE=y # CONFIG_STM32_DISABLE_IDLE_SLEEP_DURING_DEBUG is not set # CONFIG_STM32_FORCEPOWER is not set # CONFIG_ARCH_BOARD_STM32_CUSTOM_CLOCKCONFIG is not set # CONFIG_STM32_CCMEXCLUDE is not set # # Timer Configuration # # CONFIG_STM32_ONESHOT is not set # CONFIG_STM32_FREERUN is not set # CONFIG_STM32_TIM1_CAP is not set # CONFIG_STM32_TIM2_CAP is not set # CONFIG_STM32_TIM3_CAP is not set # CONFIG_STM32_TIM4_CAP is not set # CONFIG_STM32_TIM5_CAP is not set # CONFIG_STM32_TIM8_CAP is not set # CONFIG_STM32_TIM9_CAP is not set # CONFIG_STM32_TIM10_CAP is not set # CONFIG_STM32_TIM11_CAP is not set # CONFIG_STM32_TIM12_CAP is not set # CONFIG_STM32_TIM13_CAP is not set # CONFIG_STM32_TIM14_CAP is not set CONFIG_STM32_USART=y CONFIG_STM32_SERIALDRIVER=y # # U[S]ART Configuration # # # U[S]ART Device Configuration # CONFIG_STM32_USART2_SERIALDRIVER=y # CONFIG_STM32_USART2_1WIREDRIVER is not set # CONFIG_USART2_RS485 is not set # # Serial Driver Configuration # # CONFIG_SERIAL_DISABLE_REORDERING is not set # CONFIG_STM32_FLOWCONTROL_BROKEN is not set # CONFIG_STM32_USART_BREAKS is not set # CONFIG_STM32_USART_SINGLEWIRE is not set # # SPI Configuration # # CONFIG_STM32_SPI_INTERRUPTS is not set # CONFIG_STM32_SPI_DMA is not set # # SDIO Configuration # CONFIG_SDIO_DMAPRIO=0x00010000 # CONFIG_STM32_HAVE_RTC_COUNTER is not set # CONFIG_STM32_HAVE_RTC_SUBSECONDS is not set # # USB FS Host Configuration # # # USB HS Host Configuration # # # USB Host Debug Configuration # # # USB Device Configuration # # # Architecture Options # # CONFIG_ARCH_NOINTC is not set # CONFIG_ARCH_VECNOTIRQ is not set # CONFIG_ARCH_DMA is not set CONFIG_ARCH_HAVE_IRQPRIO=y # 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_MULTICPU 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 is not set # CONFIG_ARCH_IRQPRIO is not set CONFIG_ARCH_STACKDUMP=y # CONFIG_ENDIAN_BIG is not set # CONFIG_ARCH_IDLE_CUSTOM is not set # CONFIG_ARCH_HAVE_RAMFUNCS is not set CONFIG_ARCH_HAVE_RAMVECTORS=y # CONFIG_ARCH_RAMVECTORS is not set # # Board Settings # CONFIG_BOARD_LOOPSPERMSEC=16717 # CONFIG_ARCH_CALIBRATION is not set # # Interrupt options # CONFIG_ARCH_HAVE_INTERRUPTSTACK=y CONFIG_ARCH_INTERRUPTSTACK=0 CONFIG_ARCH_HAVE_HIPRI_INTERRUPT=y # CONFIG_ARCH_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=0x20000000 CONFIG_RAM_SIZE=114688 # CONFIG_ARCH_HAVE_SDRAM is not set # # Board Selection # CONFIG_ARCH_BOARD_STM32F4_DISCOVERY=y # CONFIG_ARCH_BOARD_MIKROE_STM32F4 is not set # CONFIG_ARCH_BOARD_CUSTOM is not set CONFIG_ARCH_BOARD="stm32f4discovery" # # Common Board Options # CONFIG_ARCH_HAVE_LEDS=y CONFIG_ARCH_LEDS=y CONFIG_ARCH_HAVE_BUTTONS=y CONFIG_ARCH_BUTTONS=y CONFIG_ARCH_HAVE_IRQBUTTONS=y # CONFIG_ARCH_IRQBUTTONS is not set # # Board-Specific Options # # CONFIG_STM32F4DISBB is not set # CONFIG_BOARD_CRASHDUMP is not set CONFIG_LIB_BOARDCTL=y # CONFIG_BOARDCTL_RESET is not set # CONFIG_BOARDCTL_UNIQUEID is not set CONFIG_BOARDCTL_USBDEVCTRL=y # CONFIG_BOARDCTL_TSCTEST is not set # CONFIG_BOARDCTL_ADCTEST is not set # CONFIG_BOARDCTL_PWMTEST is not set # CONFIG_BOARDCTL_GRAPHICS is not set # CONFIG_BOARDCTL_IOCTL is not set # # 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=10000 # CONFIG_SYSTEM_TIME64 is not set CONFIG_CLOCK_MONOTONIC=y CONFIG_ARCH_HAVE_TIMEKEEPING=y # CONFIG_JULIAN_TIME is not set CONFIG_START_YEAR=2013 CONFIG_START_MONTH=1 CONFIG_START_DAY=27 CONFIG_MAX_WDOGPARMS=2 CONFIG_PREALLOC_WDOGS=8 CONFIG_WDOG_INTRESERVE=1 CONFIG_PREALLOC_TIMERS=4 # # Tasks and Scheduling # # CONFIG_INIT_NONE is not set CONFIG_INIT_ENTRYPOINT=y # CONFIG_INIT_FILEPATH is not set CONFIG_USER_ENTRYPOINT="nsh_main" CONFIG_RR_INTERVAL=200 # CONFIG_SCHED_SPORADIC is not set CONFIG_TASK_NAME_SIZE=31 CONFIG_MAX_TASKS=16 # CONFIG_SCHED_HAVE_PARENT is not set CONFIG_SCHED_WAITPID=y # # Pthread Options # CONFIG_MUTEX_TYPES=y CONFIG_NPTHREAD_KEYS=4 # # Performance Monitoring # # CONFIG_SCHED_CPULOAD is not set # CONFIG_SCHED_INSTRUMENTATION 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=y CONFIG_NFILE_DESCRIPTORS=8 CONFIG_NFILE_STREAMS=8 CONFIG_NAME_MAX=32 # CONFIG_PRIORITY_INHERITANCE is not set # # RTOS hooks # # CONFIG_BOARD_INITIALIZE is not set # CONFIG_SCHED_STARTHOOK is not set # CONFIG_SCHED_ATEXIT is not set # CONFIG_SCHED_ONEXIT is not set # CONFIG_SIG_EVTHREAD is not set # # Signal Numbers # CONFIG_SIG_SIGUSR1=1 CONFIG_SIG_SIGUSR2=2 CONFIG_SIG_SIGALARM=3 CONFIG_SIG_SIGCONDTIMEDOUT=16 CONFIG_SIG_SIGWORK=17 # # POSIX Message Queue Options # CONFIG_PREALLOC_MQ_MSGS=4 CONFIG_MQ_MAXMSGSIZE=32 # CONFIG_MODULE is not set # # Work queue support # CONFIG_SCHED_WORKQUEUE=y CONFIG_SCHED_HPWORK=y CONFIG_SCHED_HPWORKPRIORITY=224 CONFIG_SCHED_HPWORKPERIOD=50000 CONFIG_SCHED_HPWORKSTACKSIZE=2048 # CONFIG_SCHED_LPWORK is not set # # Stack and heap information # CONFIG_IDLETHREAD_STACKSIZE=2048 CONFIG_USERMAIN_STACKSIZE=2048 CONFIG_PTHREAD_STACK_MIN=256 CONFIG_PTHREAD_STACK_DEFAULT=2048 # CONFIG_LIB_SYSCALL is not set # # Device Drivers # # CONFIG_DISABLE_POLL is not set CONFIG_DEV_NULL=y # CONFIG_DEV_ZERO is not set # CONFIG_DEV_URANDOM is not set # CONFIG_DEV_LOOP is not set # # Buffering # # CONFIG_DRVR_WRITEBUFFER is not set # CONFIG_DRVR_READAHEAD is not set # CONFIG_RAMDISK 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 is not set CONFIG_ARCH_HAVE_I2CRESET=y # CONFIG_I2C is not set CONFIG_SPI=y # CONFIG_SPI_SLAVE is not set CONFIG_SPI_EXCHANGE=y # CONFIG_SPI_CMDDATA is not set # CONFIG_SPI_CALLBACK is not set # CONFIG_SPI_HWFEATURES is not set # CONFIG_ARCH_HAVE_SPI_CRCGENERATION is not set # CONFIG_ARCH_HAVE_SPI_CS_CONTROL is not set CONFIG_ARCH_HAVE_SPI_BITORDER=y # CONFIG_SPI_BITORDER is not set # CONFIG_SPI_CS_DELAY_CONTROL is not set # CONFIG_SPI_DRIVER is not set # CONFIG_SPI_BITBANG is not set # CONFIG_I2S is not set # # Timer Driver Support # # CONFIG_TIMER is not set # CONFIG_ONESHOT is not set # CONFIG_RTC is not set # CONFIG_WATCHDOG is not set # CONFIG_ANALOG is not set # CONFIG_AUDIO_DEVICES is not set # CONFIG_VIDEO_DEVICES is not set # CONFIG_BCH is not set # CONFIG_INPUT is not set # # IO Expander/GPIO Support # # CONFIG_IOEXPANDER is not set # CONFIG_DEV_GPIO is not set # # LCD Driver Support # # CONFIG_LCD is not set # CONFIG_SLCD is not set # # LED Support # # CONFIG_USERLED is not set # CONFIG_RGBLED is not set # CONFIG_PCA9635PW is not set # CONFIG_NCP5623C is not set CONFIG_MMCSD=y CONFIG_MMCSD_NSLOTS=1 # CONFIG_MMCSD_READONLY is not set # CONFIG_MMCSD_MULTIBLOCK_DISABLE is not set CONFIG_MMCSD_MMCSUPPORT=y CONFIG_MMCSD_HAVECARDDETECT=y CONFIG_MMCSD_SPI=y CONFIG_MMCSD_SPICLOCK=20000000 CONFIG_MMCSD_SPIMODE=0 CONFIG_ARCH_HAVE_SDIO=y CONFIG_ARCH_HAVE_SDIOWAIT_WRCOMPLETE=y CONFIG_MMCSD_SDIO=y CONFIG_SDIO_PREFLIGHT=y # CONFIG_SDIO_MUXBUS is not set # CONFIG_MMCSD_SDIOWAIT_WRCOMPLETE is not set # CONFIG_SDIO_BLOCKSETUP is not set # CONFIG_MODEM is not set # CONFIG_MTD is not set # CONFIG_EEPROM is not set CONFIG_NETDEVICES=y # # General Ethernet MAC Driver Options # # CONFIG_NETDEV_LOOPBACK is not set # CONFIG_NETDEV_TELNET is not set # CONFIG_NETDEV_MULTINIC is not set # CONFIG_ARCH_HAVE_NETDEV_STATISTICS is not set CONFIG_NETDEV_LATEINIT=y # # 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_FTMAC100 is not set # CONFIG_NET_VNET is not set CONFIG_PIPES=y CONFIG_DEV_PIPE_MAXSIZE=1024 CONFIG_DEV_PIPE_SIZE=1024 CONFIG_DEV_FIFO_SIZE=1024 # CONFIG_PM is not set # CONFIG_POWER is not set # CONFIG_SENSORS is not set # CONFIG_SERCOMM_CONSOLE is not set CONFIG_SERIAL=y # CONFIG_DEV_LOWCONSOLE is not set CONFIG_SERIAL_REMOVABLE=y # CONFIG_SERIAL_CONSOLE is not set # CONFIG_16550_UART is not set # CONFIG_UART_SERIALDRIVER is not set # CONFIG_UART0_SERIALDRIVER is not set # CONFIG_UART1_SERIALDRIVER is not set # CONFIG_UART2_SERIALDRIVER is not set # CONFIG_UART3_SERIALDRIVER is not set # CONFIG_UART4_SERIALDRIVER is not set # CONFIG_UART5_SERIALDRIVER is not set # CONFIG_UART6_SERIALDRIVER is not set # CONFIG_UART7_SERIALDRIVER is not set # CONFIG_UART8_SERIALDRIVER is not set # CONFIG_SCI0_SERIALDRIVER is not set # CONFIG_SCI1_SERIALDRIVER is not set # CONFIG_USART0_SERIALDRIVER is not set # CONFIG_USART1_SERIALDRIVER is not set CONFIG_USART2_SERIALDRIVER=y # CONFIG_USART3_SERIALDRIVER is not set # CONFIG_USART4_SERIALDRIVER is not set # CONFIG_USART5_SERIALDRIVER is not set # CONFIG_USART6_SERIALDRIVER is not set # CONFIG_USART7_SERIALDRIVER is not set # CONFIG_USART8_SERIALDRIVER is not set # CONFIG_OTHER_UART_SERIALDRIVER is not set 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_DMA is not set CONFIG_ARCH_HAVE_SERIAL_TERMIOS=y # CONFIG_USART2_SERIAL_CONSOLE is not set # CONFIG_OTHER_SERIAL_CONSOLE is not set CONFIG_NO_SERIAL_CONSOLE=y # # USART2 Configuration # CONFIG_USART2_RXBUFSIZE=256 CONFIG_USART2_TXBUFSIZE=256 CONFIG_USART2_BAUD=115200 CONFIG_USART2_BITS=8 CONFIG_USART2_PARITY=0 CONFIG_USART2_2STOP=0 # CONFIG_USART2_IFLOWCONTROL is not set # CONFIG_USART2_OFLOWCONTROL is not set # CONFIG_USART2_DMA is not set # CONFIG_PSEUDOTERM is not set CONFIG_USBDEV=y # # USB Device Controller Driver Options # # CONFIG_USBDEV_ISOCHRONOUS is not set # CONFIG_USBDEV_DUALSPEED is not set CONFIG_USBDEV_SELFPOWERED=y # CONFIG_USBDEV_BUSPOWERED is not set CONFIG_USBDEV_MAXPOWER=100 # CONFIG_USBDEV_DMA is not set # CONFIG_ARCH_USBDEV_STALLQUEUE is not set # CONFIG_USBDEV_TRACE is not set # # USB Device Class Driver Options # # CONFIG_USBDEV_COMPOSITE is not set # CONFIG_PL2303 is not set CONFIG_CDCACM=y CONFIG_CDCACM_CONSOLE=y CONFIG_CDCACM_EP0MAXPACKET=64 CONFIG_CDCACM_EPINTIN=1 CONFIG_CDCACM_EPINTIN_FSSIZE=64 CONFIG_CDCACM_EPINTIN_HSSIZE=64 CONFIG_CDCACM_EPBULKOUT=3 CONFIG_CDCACM_EPBULKOUT_FSSIZE=64 CONFIG_CDCACM_EPBULKOUT_HSSIZE=512 CONFIG_CDCACM_EPBULKIN=2 CONFIG_CDCACM_EPBULKIN_FSSIZE=64 CONFIG_CDCACM_EPBULKIN_HSSIZE=512 CONFIG_CDCACM_NRDREQS=4 CONFIG_CDCACM_NWRREQS=4 CONFIG_CDCACM_BULKIN_REQLEN=96 CONFIG_CDCACM_RXBUFSIZE=256 CONFIG_CDCACM_TXBUFSIZE=256 CONFIG_CDCACM_VENDORID=0x0525 CONFIG_CDCACM_PRODUCTID=0xa4a7 CONFIG_CDCACM_VENDORSTR="NuttX" CONFIG_CDCACM_PRODUCTSTR="CDC/ACM Serial" # CONFIG_USBMSC is not set # CONFIG_USBHOST is not set # CONFIG_HAVE_USBTRACE is not set # CONFIG_DRIVERS_WIRELESS is not set # CONFIG_DRIVERS_CONTACTLESS is not set # # System Logging # # CONFIG_ARCH_SYSLOG is not set # CONFIG_RAMLOG is not set # CONFIG_SYSLOG_INTBUFFER is not set # CONFIG_SYSLOG_TIMESTAMP is not set # CONFIG_SYSLOG_SERIAL_CONSOLE is not set CONFIG_SYSLOG_CHAR=y # CONFIG_SYSLOG_CONSOLE is not set # CONFIG_SYSLOG_NONE is not set # CONFIG_SYSLOG_FILE is not set # CONFIG_CONSOLE_SYSLOG is not set CONFIG_SYSLOG_CHAR_CRLF=y CONFIG_SYSLOG_DEVPATH="/dev/ttyS0" # CONFIG_SYSLOG_CHARDEV is not set # # Networking Support # CONFIG_ARCH_HAVE_NET=y # CONFIG_ARCH_HAVE_PHY is not set CONFIG_NET=y # CONFIG_NET_NOINTS is not set # CONFIG_NET_PROMISCUOUS is not set # # Driver buffer configuration # # CONFIG_NET_MULTIBUFFER is not set CONFIG_NET_ETH_MTU=590 CONFIG_NET_ETH_TCP_RECVWNDO=536 CONFIG_NET_GUARDSIZE=2 # # Data link support # # CONFIG_NET_MULTILINK is not set CONFIG_NET_ETHERNET=y # CONFIG_NET_LOOPBACK is not set # CONFIG_NET_TUN is not set # # Network Device Operations # # CONFIG_NETDEV_PHY_IOCTL is not set # # Internet Protocol Selection # CONFIG_NET_IPv4=y # CONFIG_NET_IPv6 is not set # # Socket Support # CONFIG_NSOCKET_DESCRIPTORS=8 CONFIG_NET_NACTIVESOCKETS=16 CONFIG_NET_SOCKOPTS=y # CONFIG_NET_SOLINGER is not set # # Raw Socket Support # # CONFIG_NET_PKT is not set # # Unix Domain Socket Support # CONFIG_NET_LOCAL=y CONFIG_NET_LOCAL_STREAM=y CONFIG_NET_LOCAL_DGRAM=y # # TCP/IP Networking # CONFIG_NET_TCP=y # CONFIG_NET_TCPURGDATA is not set CONFIG_NET_TCP_CONNS=8 CONFIG_NET_MAX_LISTENPORTS=20 CONFIG_NET_TCP_READAHEAD=y CONFIG_NET_TCP_WRITE_BUFFERS=y CONFIG_NET_TCP_NWRBCHAINS=8 CONFIG_NET_TCP_RECVDELAY=0 # CONFIG_NET_TCPBACKLOG is not set # CONFIG_NET_SENDFILE is not set # # UDP Networking # # CONFIG_NET_UDP is not set # # ICMP Networking Support # # CONFIG_NET_ICMP is not set # # IGMPv2 Client Support # # CONFIG_NET_IGMP is not set # # ARP Configuration # CONFIG_NET_ARP=y CONFIG_NET_ARPTAB_SIZE=16 CONFIG_NET_ARP_MAXAGE=120 # CONFIG_NET_ARP_IPIN is not set # CONFIG_NET_ARP_SEND is not set # # Network I/O Buffer Support # CONFIG_NET_IOB=y CONFIG_IOB_NBUFFERS=36 CONFIG_IOB_BUFSIZE=196 CONFIG_IOB_NCHAINS=8 CONFIG_IOB_THROTTLE=8 # CONFIG_NET_ARCH_INCR32 is not set # CONFIG_NET_ARCH_CHKSUM is not set # CONFIG_NET_STATISTICS is not set # # Routing Table Configuration # # CONFIG_NET_ROUTE is not set CONFIG_NET_HOSTNAME="" # # Crypto API # # CONFIG_CRYPTO 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_NAMED_SEMAPHORES is not set CONFIG_FS_MQUEUE_MPATH="/var/mqueue" # CONFIG_FS_RAMMAP is not set CONFIG_FS_FAT=y CONFIG_FAT_LCNAMES=y CONFIG_FAT_LFN=y CONFIG_FAT_MAXFNAME=32 # CONFIG_FS_FATTIME is not set # CONFIG_FAT_FORCE_INDIRECT is not set # CONFIG_FAT_DMAMEMORY is not set # CONFIG_FAT_DIRECT_RETRY is not set # CONFIG_FS_NXFFS is not set # CONFIG_FS_ROMFS is not set # CONFIG_FS_TMPFS is not set # CONFIG_FS_SMARTFS is not set # CONFIG_FS_BINFS is not set CONFIG_FS_PROCFS=y # CONFIG_FS_PROCFS_REGISTER is not set # # Exclude individual procfs entries # # CONFIG_FS_PROCFS_EXCLUDE_PROCESS is not set # CONFIG_FS_PROCFS_EXCLUDE_UPTIME is not set # CONFIG_FS_PROCFS_EXCLUDE_MOUNTS is not set # CONFIG_FS_PROCFS_EXCLUDE_NET is not set # CONFIG_FS_UNIONFS is not set # # Graphics Support # # CONFIG_NX is not set # # Memory Management # # CONFIG_MM_SMALL is not set CONFIG_MM_REGIONS=2 # CONFIG_ARCH_HAVE_HEAP2 is not set # CONFIG_GRAN is not set # # Audio Support # # CONFIG_AUDIO is not set # # Wireless Support # # # Binary Loader # # CONFIG_BINFMT_DISABLE is not set # CONFIG_BINFMT_EXEPATH is not set # CONFIG_NXFLAT is not set # CONFIG_ELF is not set CONFIG_BUILTIN=y # CONFIG_PIC is not set # CONFIG_SYMTAB_ORDEREDBYNAME 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 is not set CONFIG_LIBC_LONG_LONG=y # CONFIG_LIBC_IOCTL_VARIADIC is not set 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_LIBC_EXECFUNCS is not set CONFIG_POSIX_SPAWN_PROXY_STACKSIZE=1024 CONFIG_TASK_SPAWN_DEFAULT_STACKSIZE=2048 # CONFIG_LIBC_STRERROR 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 is not set CONFIG_ARCH_HAVE_TLS=y # CONFIG_TLS is not set CONFIG_LIBC_NETDB=y # CONFIG_NETDB_HOSTFILE is not set # # Non-standard Library Support # # CONFIG_LIB_CRC64_FAST is not set # CONFIG_LIB_KBDCODEC is not set # CONFIG_LIB_SLCDCODEC is not set # CONFIG_LIB_HEX2BIN is not set # # Basic CXX Support # # CONFIG_C99_BOOL8 is not set CONFIG_HAVE_CXX=y CONFIG_HAVE_CXXINITIALIZE=y # CONFIG_CXX_NEWLONG is not set # # uClibc++ Standard C++ Library # # CONFIG_UCLIBCXX is not set # # Application Configuration # # # Built-In Applications # CONFIG_BUILTIN_PROXY_STACKSIZE=1024 # # CAN Utilities # # # Examples # # CONFIG_EXAMPLES_BUTTONS is not set # CONFIG_EXAMPLES_CHAT is not set # CONFIG_EXAMPLES_CONFIGDATA is not set # CONFIG_EXAMPLES_CPUHOG is not set # CONFIG_EXAMPLES_CXXTEST is not set # CONFIG_EXAMPLES_DHCPD is not set # CONFIG_EXAMPLES_ELF is not set # CONFIG_EXAMPLES_FSTEST is not set # CONFIG_EXAMPLES_FTPC is not set # CONFIG_EXAMPLES_FTPD is not set # CONFIG_EXAMPLES_HELLO is not set # CONFIG_EXAMPLES_HELLOXX is not set # CONFIG_EXAMPLES_HIDKBD is not set # CONFIG_EXAMPLES_IGMP is not set # CONFIG_EXAMPLES_JSON is not set # CONFIG_EXAMPLES_KEYPADTEST is not set # CONFIG_EXAMPLES_MEDIA is not set # CONFIG_EXAMPLES_MM is not set # CONFIG_EXAMPLES_MODBUS is not set # CONFIG_EXAMPLES_MOUNT is not set # CONFIG_EXAMPLES_NETTEST is not set # CONFIG_EXAMPLES_NRF24L01TERM is not set CONFIG_EXAMPLES_NSH=y CONFIG_EXAMPLES_NSH_CXXINITIALIZE=y # CONFIG_EXAMPLES_NULL is not set # CONFIG_EXAMPLES_NXFFS is not set # CONFIG_EXAMPLES_NXHELLO is not set # CONFIG_EXAMPLES_NXIMAGE is not set # CONFIG_EXAMPLES_NX is not set # CONFIG_EXAMPLES_NXLINES is not set # CONFIG_EXAMPLES_NXTERM is not set # CONFIG_EXAMPLES_NXTEXT is not set # CONFIG_EXAMPLES_OSTEST is not set # CONFIG_EXAMPLES_PCA9635 is not set # CONFIG_EXAMPLES_PIPE is not set # CONFIG_EXAMPLES_POSIXSPAWN is not set # CONFIG_EXAMPLES_PPPD is not set # CONFIG_EXAMPLES_RFID_READUID is not set # CONFIG_EXAMPLES_RGBLED is not set # CONFIG_EXAMPLES_RGMP is not set # CONFIG_EXAMPLES_SENDMAIL is not set # CONFIG_EXAMPLES_SERIALBLASTER is not set # CONFIG_EXAMPLES_SERIALRX is not set # CONFIG_EXAMPLES_SERLOOP is not set # CONFIG_EXAMPLES_SLCD is not set # CONFIG_EXAMPLES_SMART is not set # CONFIG_EXAMPLES_SMART_TEST is not set # CONFIG_EXAMPLES_SMP is not set # CONFIG_EXAMPLES_TCPECHO is not set # CONFIG_EXAMPLES_TELNETD is not set # CONFIG_EXAMPLES_TIFF is not set # CONFIG_EXAMPLES_TOUCHSCREEN is not set # CONFIG_EXAMPLES_UDGRAM is not set # CONFIG_EXAMPLES_USBSERIAL is not set # CONFIG_EXAMPLES_USBTERM is not set # CONFIG_EXAMPLES_USTREAM is not set # CONFIG_EXAMPLES_WATCHDOG is not set # CONFIG_EXAMPLES_WEBSERVER is not set # CONFIG_EXAMPLES_XMLRPC is not set # # File System Utilities # # CONFIG_FSUTILS_INIFILE is not set # CONFIG_FSUTILS_PASSWD is not set # # GPS Utilities # # CONFIG_GPSUTILS_MINMEA_LIB is not set # # Graphics Support # # CONFIG_TIFF is not set # CONFIG_GRAPHICS_TRAVELER is not set # # Interpreters # # CONFIG_INTERPRETERS_BAS is not set # CONFIG_INTERPRETERS_FICL is not set # CONFIG_INTERPRETERS_MICROPYTHON is not set # CONFIG_INTERPRETERS_MINIBASIC is not set # CONFIG_INTERPRETERS_PCODE is not set # # FreeModBus # # CONFIG_MODBUS is not set # # Network Utilities # # CONFIG_NETUTILS_CHAT is not set # CONFIG_NETUTILS_CODECS is not set # CONFIG_NETUTILS_ESP8266 is not set # CONFIG_NETUTILS_FTPC is not set # CONFIG_NETUTILS_FTPD is not set # CONFIG_NETUTILS_JSON is not set CONFIG_NETUTILS_NETLIB=y # CONFIG_NETUTILS_SMTP is not set # CONFIG_NETUTILS_TELNETD is not set # CONFIG_NETUTILS_WEBCLIENT is not set # CONFIG_NETUTILS_WEBSERVER is not set # CONFIG_NETUTILS_XMLRPC is not set # # NSH Library # CONFIG_NSH_LIBRARY=y # CONFIG_NSH_MOTD is not set # # Command Line Configuration # CONFIG_NSH_READLINE=y # CONFIG_NSH_CLE is not set CONFIG_NSH_LINELEN=64 # CONFIG_NSH_DISABLE_SEMICOLON is not set CONFIG_NSH_CMDPARMS=y CONFIG_NSH_MAXARGUMENTS=6 CONFIG_NSH_ARGCAT=y CONFIG_NSH_NESTDEPTH=3 # CONFIG_NSH_DISABLEBG is not set CONFIG_NSH_BUILTIN_APPS=y # # Disable Individual commands # # CONFIG_NSH_DISABLE_ADDROUTE is not set # CONFIG_NSH_DISABLE_ARP is not set # CONFIG_NSH_DISABLE_BASENAME is not set # CONFIG_NSH_DISABLE_CAT is not set # CONFIG_NSH_DISABLE_CD is not set # CONFIG_NSH_DISABLE_CP is not set # CONFIG_NSH_DISABLE_CMP is not set CONFIG_NSH_DISABLE_DATE=y # CONFIG_NSH_DISABLE_DD is not set # CONFIG_NSH_DISABLE_DF is not set # CONFIG_NSH_DISABLE_DELROUTE is not set # CONFIG_NSH_DISABLE_DIRNAME is not set # CONFIG_NSH_DISABLE_ECHO is not set # CONFIG_NSH_DISABLE_EXEC is not set # CONFIG_NSH_DISABLE_EXIT is not set # CONFIG_NSH_DISABLE_FREE is not set # CONFIG_NSH_DISABLE_GET is not set # CONFIG_NSH_DISABLE_HELP is not set # CONFIG_NSH_DISABLE_HEXDUMP is not set # CONFIG_NSH_DISABLE_IFCONFIG is not set # CONFIG_NSH_DISABLE_IFUPDOWN is not set # CONFIG_NSH_DISABLE_KILL is not set # CONFIG_NSH_DISABLE_LOSETUP is not set CONFIG_NSH_DISABLE_LOSMART=y # CONFIG_NSH_DISABLE_LS is not set # CONFIG_NSH_DISABLE_MB is not set # CONFIG_NSH_DISABLE_MKDIR is not set # CONFIG_NSH_DISABLE_MKFATFS is not set # CONFIG_NSH_DISABLE_MKFIFO is not set # CONFIG_NSH_DISABLE_MKRD is not set # CONFIG_NSH_DISABLE_MH is not set # CONFIG_NSH_DISABLE_MOUNT is not set # CONFIG_NSH_DISABLE_MV is not set # CONFIG_NSH_DISABLE_MW is not set CONFIG_NSH_DISABLE_PRINTF=y # CONFIG_NSH_DISABLE_PS is not set # CONFIG_NSH_DISABLE_PUT is not set # CONFIG_NSH_DISABLE_PWD is not set # CONFIG_NSH_DISABLE_RM is not set # CONFIG_NSH_DISABLE_RMDIR is not set # CONFIG_NSH_DISABLE_SET is not set # CONFIG_NSH_DISABLE_SH is not set # CONFIG_NSH_DISABLE_SLEEP is not set # CONFIG_NSH_DISABLE_TIME is not set # CONFIG_NSH_DISABLE_TEST is not set # CONFIG_NSH_DISABLE_UMOUNT is not set # CONFIG_NSH_DISABLE_UNAME is not set # CONFIG_NSH_DISABLE_UNSET is not set # CONFIG_NSH_DISABLE_USLEEP is not set # CONFIG_NSH_DISABLE_WGET is not set # CONFIG_NSH_DISABLE_XD is not set CONFIG_NSH_MMCSDMINOR=0 CONFIG_NSH_MMCSDSLOTNO=0 CONFIG_NSH_MMCSDSPIPORTNO=0 # # Configure Command Options # CONFIG_NSH_CMDOPT_DF_H=y CONFIG_NSH_CODECS_BUFSIZE=128 CONFIG_NSH_CMDOPT_HEXDUMP=y CONFIG_NSH_PROC_MOUNTPOINT="/proc" CONFIG_NSH_FILEIOSIZE=512 # # Scripting Support # # CONFIG_NSH_DISABLESCRIPT is not set # CONFIG_NSH_DISABLE_ITEF is not set # CONFIG_NSH_DISABLE_LOOPS is not set # # Console Configuration # CONFIG_NSH_CONSOLE=y # CONFIG_NSH_USBCONSOLE is not set # CONFIG_NSH_ALTCONDEV is not set CONFIG_NSH_ARCHINIT=y # # Networking Configuration # CONFIG_NSH_NETINIT=y # CONFIG_NSH_NETINIT_THREAD is not set # # IP Address Configuration # # # IPv4 Addresses # CONFIG_NSH_IPADDR=0x0a000002 CONFIG_NSH_DRIPADDR=0x0a000001 CONFIG_NSH_NETMASK=0xffffff00 # CONFIG_NSH_NOMAC is not set CONFIG_NSH_MAX_ROUNDTRIP=20 # CONFIG_NSH_LOGIN is not set # CONFIG_NSH_CONSOLE_LOGIN is not set # # NxWidgets/NxWM # # # Platform-specific Support # # CONFIG_PLATFORM_CONFIGDATA is not set # # System Libraries and NSH Add-Ons # # CONFIG_SYSTEM_CDCACM is not set # CONFIG_SYSTEM_CLE is not set # CONFIG_SYSTEM_CUTERM is not set # CONFIG_SYSTEM_FREE is not set # CONFIG_SYSTEM_HEX2BIN is not set # CONFIG_SYSTEM_HEXED is not set # CONFIG_SYSTEM_INSTALL is not set CONFIG_IOTJS=y CONFIG_IOTJS_PRIORITY=100 CONFIG_IOTJS_STACKSIZE=16384 CONFIG_IOTJS_HEAPSIZE=107520 # CONFIG_SYSTEM_NETDB is not set # CONFIG_SYSTEM_RAMTEST is not set CONFIG_READLINE_HAVE_EXTMATCH=y CONFIG_SYSTEM_READLINE=y CONFIG_READLINE_ECHO=y CONFIG_READLINE_TABCOMPLETION=y CONFIG_READLINE_MAX_BUILTINS=64 CONFIG_READLINE_MAX_EXTCMDS=64 CONFIG_READLINE_CMD_HISTORY=y CONFIG_READLINE_CMD_HISTORY_LINELEN=80 CONFIG_READLINE_CMD_HISTORY_LEN=16 # CONFIG_SYSTEM_SUDOKU is not set # CONFIG_SYSTEM_SYSTEM is not set # CONFIG_SYSTEM_TEE is not set # CONFIG_SYSTEM_UBLOXMODEM is not set # CONFIG_SYSTEM_VI is not set # CONFIG_SYSTEM_ZMODEM is not set iotjs-1.0+715/config/nuttx/stm32f4dis/config.travis000066400000000000000000001150171371177304000220520ustar00rootroot00000000000000# # Automatically generated file; DO NOT EDIT. # Nuttx/ 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 # # Build Configuration # CONFIG_APPS_DIR="../apps" CONFIG_BUILD_FLAT=y # CONFIG_BUILD_2PASS is not set # # Binary Output Formats # # CONFIG_RRLOAD_BINARY is not set CONFIG_INTELHEX_BINARY=y # CONFIG_MOTOROLA_SREC is not set CONFIG_RAW_BINARY=y # CONFIG_UBOOT_UIMAGE 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 # CONFIG_ARCH_DEBUG_H is not set # # Debug Options # CONFIG_DEBUG_ALERT=y # CONFIG_DEBUG_FEATURES is not set CONFIG_ARCH_HAVE_STACKCHECK=y # CONFIG_STACK_COLORATION is not set CONFIG_ARCH_HAVE_HEAPCHECK=y # CONFIG_HEAP_COLORATION is not set # CONFIG_DEBUG_SYMBOLS is not set CONFIG_ARCH_HAVE_CUSTOMOPT=y # CONFIG_DEBUG_NOOPT is not set # CONFIG_DEBUG_CUSTOMOPT is not set CONFIG_DEBUG_FULLOPT=y # # System Type # CONFIG_ARCH_ARM=y # CONFIG_ARCH_AVR is not set # CONFIG_ARCH_HC is not set # CONFIG_ARCH_MIPS is not set # CONFIG_ARCH_MISOC is not set # CONFIG_ARCH_RENESAS is not set # CONFIG_ARCH_RISCV is not set # CONFIG_ARCH_SIM is not set # CONFIG_ARCH_X86 is not set # CONFIG_ARCH_XTENSA is not set # CONFIG_ARCH_Z16 is not set # CONFIG_ARCH_Z80 is not set CONFIG_ARCH="arm" # # ARM Options # # CONFIG_ARCH_CHIP_A1X is not set # CONFIG_ARCH_CHIP_C5471 is not set # CONFIG_ARCH_CHIP_DM320 is not set # CONFIG_ARCH_CHIP_EFM32 is not set # CONFIG_ARCH_CHIP_IMX1 is not set # CONFIG_ARCH_CHIP_IMX6 is not set # CONFIG_ARCH_CHIP_KINETIS is not set # CONFIG_ARCH_CHIP_KL is not set # CONFIG_ARCH_CHIP_LM is not set # CONFIG_ARCH_CHIP_TIVA is not set # CONFIG_ARCH_CHIP_LPC11XX is not set # CONFIG_ARCH_CHIP_LPC17XX is not set # CONFIG_ARCH_CHIP_LPC214X is not set # CONFIG_ARCH_CHIP_LPC2378 is not set # CONFIG_ARCH_CHIP_LPC31XX is not set # CONFIG_ARCH_CHIP_LPC43XX is not set # CONFIG_ARCH_CHIP_NUC1XX is not set # CONFIG_ARCH_CHIP_SAMA5 is not set # CONFIG_ARCH_CHIP_SAMD is not set # CONFIG_ARCH_CHIP_SAML is not set # CONFIG_ARCH_CHIP_SAM34 is not set # CONFIG_ARCH_CHIP_SAMV7 is not set CONFIG_ARCH_CHIP_STM32=y # CONFIG_ARCH_CHIP_STM32F7 is not set # CONFIG_ARCH_CHIP_STM32L4 is not set # CONFIG_ARCH_CHIP_STR71X is not set # CONFIG_ARCH_CHIP_TMS570 is not set # CONFIG_ARCH_CHIP_MOXART is not set # CONFIG_ARCH_ARM7TDMI is not set # CONFIG_ARCH_ARM926EJS is not set # CONFIG_ARCH_ARM920T is not set # CONFIG_ARCH_CORTEXM0 is not set # CONFIG_ARCH_CORTEXM3 is not set CONFIG_ARCH_CORTEXM4=y # CONFIG_ARCH_CORTEXM7 is not set # CONFIG_ARCH_CORTEXA5 is not set # CONFIG_ARCH_CORTEXA8 is not set # CONFIG_ARCH_CORTEXA9 is not set # CONFIG_ARCH_CORTEXR4 is not set # CONFIG_ARCH_CORTEXR4F is not set # CONFIG_ARCH_CORTEXR5 is not set # CONFIG_ARCH_CORTEX5F is not set # CONFIG_ARCH_CORTEXR7 is not set # CONFIG_ARCH_CORTEXR7F is not set CONFIG_ARCH_FAMILY="armv7-m" CONFIG_ARCH_CHIP="stm32" # CONFIG_ARM_TOOLCHAIN_IAR is not set CONFIG_ARM_TOOLCHAIN_GNU=y # CONFIG_ARMV7M_USEBASEPRI is not set CONFIG_ARCH_HAVE_CMNVECTOR=y # CONFIG_ARMV7M_CMNVECTOR is not set # CONFIG_ARMV7M_LAZYFPU is not set CONFIG_ARCH_HAVE_FPU=y # CONFIG_ARCH_HAVE_DPFPU is not set CONFIG_ARCH_FPU=y # CONFIG_ARCH_HAVE_TRUSTZONE is not set CONFIG_ARM_HAVE_MPU_UNIFIED=y # CONFIG_ARM_MPU is not set # # ARMV7M Configuration Options # # CONFIG_ARMV7M_HAVE_ICACHE is not set # CONFIG_ARMV7M_HAVE_DCACHE is not set # CONFIG_ARMV7M_HAVE_ITCM is not set # CONFIG_ARMV7M_HAVE_DTCM is not set # CONFIG_ARMV7M_TOOLCHAIN_IARL is not set # CONFIG_ARMV7M_TOOLCHAIN_BUILDROOT is not set # CONFIG_ARMV7M_TOOLCHAIN_CODEREDL is not set # CONFIG_ARMV7M_TOOLCHAIN_CODESOURCERYL is not set CONFIG_ARMV7M_TOOLCHAIN_GNU_EABIL=y CONFIG_ARMV7M_HAVE_STACKCHECK=y # CONFIG_ARMV7M_STACKCHECK is not set # CONFIG_ARMV7M_ITMSYSLOG is not set # CONFIG_SERIAL_TERMIOS is not set # CONFIG_SDIO_DMA is not set # CONFIG_SDIO_WIDTH_D1_ONLY is not set # # STM32 Configuration Options # # CONFIG_ARCH_CHIP_STM32L151C6 is not set # CONFIG_ARCH_CHIP_STM32L151C8 is not set # CONFIG_ARCH_CHIP_STM32L151CB is not set # CONFIG_ARCH_CHIP_STM32L151R6 is not set # CONFIG_ARCH_CHIP_STM32L151R8 is not set # CONFIG_ARCH_CHIP_STM32L151RB is not set # CONFIG_ARCH_CHIP_STM32L151V6 is not set # CONFIG_ARCH_CHIP_STM32L151V8 is not set # CONFIG_ARCH_CHIP_STM32L151VB is not set # CONFIG_ARCH_CHIP_STM32L152C6 is not set # CONFIG_ARCH_CHIP_STM32L152C8 is not set # CONFIG_ARCH_CHIP_STM32L152CB is not set # CONFIG_ARCH_CHIP_STM32L152R6 is not set # CONFIG_ARCH_CHIP_STM32L152R8 is not set # CONFIG_ARCH_CHIP_STM32L152RB is not set # CONFIG_ARCH_CHIP_STM32L152V6 is not set # CONFIG_ARCH_CHIP_STM32L152V8 is not set # CONFIG_ARCH_CHIP_STM32L152VB is not set # CONFIG_ARCH_CHIP_STM32L162ZD is not set # CONFIG_ARCH_CHIP_STM32L162VE is not set # CONFIG_ARCH_CHIP_STM32F100C8 is not set # CONFIG_ARCH_CHIP_STM32F100CB is not set # CONFIG_ARCH_CHIP_STM32F100R8 is not set # CONFIG_ARCH_CHIP_STM32F100RB is not set # CONFIG_ARCH_CHIP_STM32F100RC is not set # CONFIG_ARCH_CHIP_STM32F100RD is not set # CONFIG_ARCH_CHIP_STM32F100RE is not set # CONFIG_ARCH_CHIP_STM32F100V8 is not set # CONFIG_ARCH_CHIP_STM32F100VB is not set # CONFIG_ARCH_CHIP_STM32F100VC is not set # CONFIG_ARCH_CHIP_STM32F100VD is not set # CONFIG_ARCH_CHIP_STM32F100VE is not set # CONFIG_ARCH_CHIP_STM32F102CB is not set # CONFIG_ARCH_CHIP_STM32F103T8 is not set # CONFIG_ARCH_CHIP_STM32F103TB is not set # CONFIG_ARCH_CHIP_STM32F103C4 is not set # CONFIG_ARCH_CHIP_STM32F103C8 is not set # CONFIG_ARCH_CHIP_STM32F103CB is not set # CONFIG_ARCH_CHIP_STM32F103R8 is not set # CONFIG_ARCH_CHIP_STM32F103RB is not set # CONFIG_ARCH_CHIP_STM32F103RC is not set # CONFIG_ARCH_CHIP_STM32F103RD is not set # CONFIG_ARCH_CHIP_STM32F103RE is not set # CONFIG_ARCH_CHIP_STM32F103RG is not set # CONFIG_ARCH_CHIP_STM32F103V8 is not set # CONFIG_ARCH_CHIP_STM32F103VB is not set # CONFIG_ARCH_CHIP_STM32F103VC is not set # CONFIG_ARCH_CHIP_STM32F103VE is not set # CONFIG_ARCH_CHIP_STM32F103ZE is not set # CONFIG_ARCH_CHIP_STM32F105VB is not set # CONFIG_ARCH_CHIP_STM32F105RB is not set # CONFIG_ARCH_CHIP_STM32F107VC is not set # CONFIG_ARCH_CHIP_STM32F205RG is not set # CONFIG_ARCH_CHIP_STM32F207IG is not set # CONFIG_ARCH_CHIP_STM32F207ZE is not set # CONFIG_ARCH_CHIP_STM32F302K6 is not set # CONFIG_ARCH_CHIP_STM32F302K8 is not set # CONFIG_ARCH_CHIP_STM32F302CB is not set # CONFIG_ARCH_CHIP_STM32F302CC is not set # CONFIG_ARCH_CHIP_STM32F302RB is not set # CONFIG_ARCH_CHIP_STM32F302RC is not set # CONFIG_ARCH_CHIP_STM32F302VB is not set # CONFIG_ARCH_CHIP_STM32F302VC is not set # CONFIG_ARCH_CHIP_STM32F303K6 is not set # CONFIG_ARCH_CHIP_STM32F303K8 is not set # CONFIG_ARCH_CHIP_STM32F303C6 is not set # CONFIG_ARCH_CHIP_STM32F303C8 is not set # CONFIG_ARCH_CHIP_STM32F303CB is not set # CONFIG_ARCH_CHIP_STM32F303CC is not set # CONFIG_ARCH_CHIP_STM32F303RB is not set # CONFIG_ARCH_CHIP_STM32F303RC is not set # CONFIG_ARCH_CHIP_STM32F303RD is not set # CONFIG_ARCH_CHIP_STM32F303RE is not set # CONFIG_ARCH_CHIP_STM32F303VB is not set # CONFIG_ARCH_CHIP_STM32F303VC is not set # CONFIG_ARCH_CHIP_STM32F372C8 is not set # CONFIG_ARCH_CHIP_STM32F372R8 is not set # CONFIG_ARCH_CHIP_STM32F372V8 is not set # CONFIG_ARCH_CHIP_STM32F372CB is not set # CONFIG_ARCH_CHIP_STM32F372RB is not set # CONFIG_ARCH_CHIP_STM32F372VB is not set # CONFIG_ARCH_CHIP_STM32F372CC is not set # CONFIG_ARCH_CHIP_STM32F372RC is not set # CONFIG_ARCH_CHIP_STM32F372VC is not set # CONFIG_ARCH_CHIP_STM32F373C8 is not set # CONFIG_ARCH_CHIP_STM32F373R8 is not set # CONFIG_ARCH_CHIP_STM32F373V8 is not set # CONFIG_ARCH_CHIP_STM32F373CB is not set # CONFIG_ARCH_CHIP_STM32F373RB is not set # CONFIG_ARCH_CHIP_STM32F373VB is not set # CONFIG_ARCH_CHIP_STM32F373CC is not set # CONFIG_ARCH_CHIP_STM32F373RC is not set # CONFIG_ARCH_CHIP_STM32F373VC is not set # CONFIG_ARCH_CHIP_STM32F401RE is not set # CONFIG_ARCH_CHIP_STM32F411RE is not set # CONFIG_ARCH_CHIP_STM32F411VE is not set # CONFIG_ARCH_CHIP_STM32F405RG is not set # CONFIG_ARCH_CHIP_STM32F405VG is not set # CONFIG_ARCH_CHIP_STM32F405ZG is not set # CONFIG_ARCH_CHIP_STM32F407VE is not set CONFIG_ARCH_CHIP_STM32F407VG=y # CONFIG_ARCH_CHIP_STM32F407ZE is not set # CONFIG_ARCH_CHIP_STM32F407ZG is not set # CONFIG_ARCH_CHIP_STM32F407IE is not set # CONFIG_ARCH_CHIP_STM32F407IG is not set # CONFIG_ARCH_CHIP_STM32F427V is not set # CONFIG_ARCH_CHIP_STM32F427Z is not set # CONFIG_ARCH_CHIP_STM32F427I is not set # CONFIG_ARCH_CHIP_STM32F429V is not set # CONFIG_ARCH_CHIP_STM32F429Z is not set # CONFIG_ARCH_CHIP_STM32F429I is not set # CONFIG_ARCH_CHIP_STM32F429B is not set # CONFIG_ARCH_CHIP_STM32F429N is not set # CONFIG_ARCH_CHIP_STM32F446M is not set # CONFIG_ARCH_CHIP_STM32F446R is not set # CONFIG_ARCH_CHIP_STM32F446V is not set # CONFIG_ARCH_CHIP_STM32F446Z is not set # CONFIG_ARCH_CHIP_STM32F469A is not set # CONFIG_ARCH_CHIP_STM32F469I is not set # CONFIG_ARCH_CHIP_STM32F469B is not set # CONFIG_ARCH_CHIP_STM32F469N is not set CONFIG_STM32_FLASH_CONFIG_DEFAULT=y # CONFIG_STM32_FLASH_CONFIG_4 is not set # CONFIG_STM32_FLASH_CONFIG_6 is not set # CONFIG_STM32_FLASH_CONFIG_8 is not set # CONFIG_STM32_FLASH_CONFIG_B is not set # CONFIG_STM32_FLASH_CONFIG_C is not set # CONFIG_STM32_FLASH_CONFIG_D is not set # CONFIG_STM32_FLASH_CONFIG_E is not set # CONFIG_STM32_FLASH_CONFIG_F is not set # CONFIG_STM32_FLASH_CONFIG_G is not set # CONFIG_STM32_FLASH_CONFIG_I is not set # CONFIG_STM32_STM32L15XX is not set # CONFIG_STM32_ENERGYLITE is not set # CONFIG_STM32_STM32F10XX is not set # CONFIG_STM32_VALUELINE is not set # CONFIG_STM32_CONNECTIVITYLINE is not set # CONFIG_STM32_PERFORMANCELINE is not set # CONFIG_STM32_USBACCESSLINE is not set # CONFIG_STM32_HIGHDENSITY is not set # CONFIG_STM32_MEDIUMDENSITY is not set # CONFIG_STM32_LOWDENSITY is not set # CONFIG_STM32_STM32F20XX is not set # CONFIG_STM32_STM32F205 is not set # CONFIG_STM32_STM32F207 is not set # CONFIG_STM32_STM32F30XX is not set # CONFIG_STM32_STM32F302 is not set # CONFIG_STM32_STM32F303 is not set # CONFIG_STM32_STM32F37XX is not set CONFIG_STM32_STM32F40XX=y # CONFIG_STM32_STM32F401 is not set # CONFIG_STM32_STM32F411 is not set # CONFIG_STM32_STM32F405 is not set CONFIG_STM32_STM32F407=y # CONFIG_STM32_STM32F427 is not set # CONFIG_STM32_STM32F429 is not set # CONFIG_STM32_STM32F446 is not set # CONFIG_STM32_STM32F469 is not set # CONFIG_STM32_DFU is not set # # STM32 Peripheral Support # CONFIG_STM32_HAVE_CCM=y # CONFIG_STM32_HAVE_USBDEV is not set CONFIG_STM32_HAVE_OTGFS=y CONFIG_STM32_HAVE_FSMC=y # CONFIG_STM32_HAVE_LTDC is not set CONFIG_STM32_HAVE_USART3=y CONFIG_STM32_HAVE_UART4=y CONFIG_STM32_HAVE_UART5=y CONFIG_STM32_HAVE_USART6=y # CONFIG_STM32_HAVE_UART7 is not set # CONFIG_STM32_HAVE_UART8 is not set CONFIG_STM32_HAVE_TIM1=y CONFIG_STM32_HAVE_TIM2=y CONFIG_STM32_HAVE_TIM3=y CONFIG_STM32_HAVE_TIM4=y CONFIG_STM32_HAVE_TIM5=y CONFIG_STM32_HAVE_TIM6=y CONFIG_STM32_HAVE_TIM7=y CONFIG_STM32_HAVE_TIM8=y CONFIG_STM32_HAVE_TIM9=y CONFIG_STM32_HAVE_TIM10=y CONFIG_STM32_HAVE_TIM11=y CONFIG_STM32_HAVE_TIM12=y CONFIG_STM32_HAVE_TIM13=y CONFIG_STM32_HAVE_TIM14=y # CONFIG_STM32_HAVE_TIM15 is not set # CONFIG_STM32_HAVE_TIM16 is not set # CONFIG_STM32_HAVE_TIM17 is not set CONFIG_STM32_HAVE_ADC2=y CONFIG_STM32_HAVE_ADC3=y # CONFIG_STM32_HAVE_ADC4 is not set # CONFIG_STM32_HAVE_ADC1_DMA is not set # CONFIG_STM32_HAVE_ADC2_DMA is not set # CONFIG_STM32_HAVE_ADC3_DMA is not set # CONFIG_STM32_HAVE_ADC4_DMA is not set # CONFIG_STM32_HAVE_SDADC1 is not set # CONFIG_STM32_HAVE_SDADC2 is not set # CONFIG_STM32_HAVE_SDADC3 is not set # CONFIG_STM32_HAVE_SDADC1_DMA is not set # CONFIG_STM32_HAVE_SDADC2_DMA is not set # CONFIG_STM32_HAVE_SDADC3_DMA is not set CONFIG_STM32_HAVE_CAN1=y CONFIG_STM32_HAVE_CAN2=y CONFIG_STM32_HAVE_DAC1=y CONFIG_STM32_HAVE_DAC2=y CONFIG_STM32_HAVE_RNG=y CONFIG_STM32_HAVE_ETHMAC=y CONFIG_STM32_HAVE_I2C2=y CONFIG_STM32_HAVE_I2C3=y CONFIG_STM32_HAVE_SPI2=y CONFIG_STM32_HAVE_SPI3=y # CONFIG_STM32_HAVE_SPI4 is not set # CONFIG_STM32_HAVE_SPI5 is not set # CONFIG_STM32_HAVE_SPI6 is not set # CONFIG_STM32_HAVE_SAIPLL is not set # CONFIG_STM32_HAVE_I2SPLL is not set CONFIG_STM32_ADC1=y # CONFIG_STM32_ADC2 is not set # CONFIG_STM32_ADC3 is not set # CONFIG_STM32_BKPSRAM is not set # CONFIG_STM32_CAN1 is not set # CONFIG_STM32_CAN2 is not set # CONFIG_STM32_CCMDATARAM is not set # CONFIG_STM32_CRC is not set # CONFIG_STM32_CRYP is not set # CONFIG_STM32_DMA1 is not set # CONFIG_STM32_DMA2 is not set # CONFIG_STM32_DAC1 is not set # CONFIG_STM32_DAC2 is not set # CONFIG_STM32_DCMI is not set # CONFIG_STM32_ETHMAC is not set # CONFIG_STM32_FSMC is not set # CONFIG_STM32_HASH is not set CONFIG_STM32_I2C1=y # CONFIG_STM32_I2C2 is not set # CONFIG_STM32_I2C3 is not set CONFIG_STM32_OTGFS=y # CONFIG_STM32_OTGHS is not set CONFIG_STM32_PWR=y # CONFIG_STM32_RNG is not set CONFIG_STM32_SDIO=y CONFIG_STM32_SPI1=y # CONFIG_STM32_SPI2 is not set # CONFIG_STM32_SPI3 is not set CONFIG_STM32_SYSCFG=y CONFIG_STM32_TIM1=y # CONFIG_STM32_TIM2 is not set CONFIG_STM32_TIM3=y # CONFIG_STM32_TIM4 is not set # CONFIG_STM32_TIM5 is not set # CONFIG_STM32_TIM6 is not set # CONFIG_STM32_TIM7 is not set # CONFIG_STM32_TIM8 is not set # CONFIG_STM32_TIM9 is not set # CONFIG_STM32_TIM10 is not set # CONFIG_STM32_TIM11 is not set # CONFIG_STM32_TIM12 is not set # CONFIG_STM32_TIM13 is not set # CONFIG_STM32_TIM14 is not set # CONFIG_STM32_USART1 is not set CONFIG_STM32_USART2=y # CONFIG_STM32_USART3 is not set # CONFIG_STM32_UART4 is not set # CONFIG_STM32_UART5 is not set # CONFIG_STM32_USART6 is not set # CONFIG_STM32_IWDG is not set # CONFIG_STM32_WWDG is not set CONFIG_STM32_ADC=y CONFIG_STM32_SPI=y CONFIG_STM32_I2C=y # CONFIG_STM32_NOEXT_VECTORS is not set # # Alternate Pin Mapping # # CONFIG_STM32_FLASH_PREFETCH is not set # CONFIG_STM32_JTAG_DISABLE is not set # CONFIG_STM32_JTAG_FULL_ENABLE is not set # CONFIG_STM32_JTAG_NOJNTRST_ENABLE is not set CONFIG_STM32_JTAG_SW_ENABLE=y # CONFIG_STM32_DISABLE_IDLE_SLEEP_DURING_DEBUG is not set # CONFIG_STM32_FORCEPOWER is not set # CONFIG_ARCH_BOARD_STM32_CUSTOM_CLOCKCONFIG is not set # CONFIG_STM32_CCMEXCLUDE is not set # # Timer Configuration # # CONFIG_STM32_ONESHOT is not set # CONFIG_STM32_FREERUN is not set CONFIG_STM32_TIM1_PWM=y CONFIG_STM32_TIM1_MODE=0 CONFIG_STM32_TIM1_CHANNEL=1 CONFIG_STM32_TIM1_CHMODE=0 # CONFIG_STM32_TIM3_PWM is not set # CONFIG_STM32_PWM_MULTICHAN is not set # CONFIG_STM32_TIM1_ADC is not set CONFIG_STM32_TIM3_ADC=y CONFIG_STM32_TIM3_ADC1=y CONFIG_HAVE_ADC1_TIMER=y CONFIG_STM32_ADC1_SAMPLE_FREQUENCY=100 CONFIG_STM32_ADC1_TIMTRIG=0 # CONFIG_STM32_TIM1_CAP is not set # CONFIG_STM32_TIM2_CAP is not set # CONFIG_STM32_TIM3_CAP is not set # CONFIG_STM32_TIM4_CAP is not set # CONFIG_STM32_TIM5_CAP is not set # CONFIG_STM32_TIM8_CAP is not set # CONFIG_STM32_TIM9_CAP is not set # CONFIG_STM32_TIM10_CAP is not set # CONFIG_STM32_TIM11_CAP is not set # CONFIG_STM32_TIM12_CAP is not set # CONFIG_STM32_TIM13_CAP is not set # CONFIG_STM32_TIM14_CAP is not set # # ADC Configuration # CONFIG_STM32_USART=y CONFIG_STM32_SERIALDRIVER=y # # U[S]ART Configuration # # # U[S]ART Device Configuration # CONFIG_STM32_USART2_SERIALDRIVER=y # CONFIG_STM32_USART2_1WIREDRIVER is not set # CONFIG_USART2_RS485 is not set # # Serial Driver Configuration # # CONFIG_SERIAL_DISABLE_REORDERING is not set # CONFIG_STM32_FLOWCONTROL_BROKEN is not set # CONFIG_STM32_USART_BREAKS is not set # CONFIG_STM32_USART_SINGLEWIRE is not set # # SPI Configuration # # CONFIG_STM32_SPI_INTERRUPTS is not set # CONFIG_STM32_SPI_DMA is not set # # I2C Configuration # # CONFIG_STM32_I2C_ALT is not set # CONFIG_STM32_I2C_DYNTIMEO is not set CONFIG_STM32_I2CTIMEOSEC=0 CONFIG_STM32_I2CTIMEOMS=500 CONFIG_STM32_I2CTIMEOTICKS=500 # CONFIG_STM32_I2C_DUTY16_9 is not set # # SDIO Configuration # CONFIG_SDIO_DMAPRIO=0x00010000 # CONFIG_STM32_HAVE_RTC_COUNTER is not set # CONFIG_STM32_HAVE_RTC_SUBSECONDS is not set # # USB FS Host Configuration # # # USB HS Host Configuration # # # USB Host Debug Configuration # # # USB Device Configuration # # # Architecture Options # # CONFIG_ARCH_NOINTC is not set # CONFIG_ARCH_VECNOTIRQ is not set # CONFIG_ARCH_DMA is not set CONFIG_ARCH_HAVE_IRQPRIO=y # 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_MULTICPU 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 is not set # CONFIG_ARCH_IRQPRIO is not set CONFIG_ARCH_STACKDUMP=y # CONFIG_ENDIAN_BIG is not set # CONFIG_ARCH_IDLE_CUSTOM is not set # CONFIG_ARCH_HAVE_RAMFUNCS is not set CONFIG_ARCH_HAVE_RAMVECTORS=y # CONFIG_ARCH_RAMVECTORS is not set # # Board Settings # CONFIG_BOARD_LOOPSPERMSEC=16717 # CONFIG_ARCH_CALIBRATION is not set # # Interrupt options # CONFIG_ARCH_HAVE_INTERRUPTSTACK=y CONFIG_ARCH_INTERRUPTSTACK=0 CONFIG_ARCH_HAVE_HIPRI_INTERRUPT=y # CONFIG_ARCH_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=0x20000000 CONFIG_RAM_SIZE=114688 # CONFIG_ARCH_HAVE_SDRAM is not set # # Board Selection # CONFIG_ARCH_BOARD_STM32F4_DISCOVERY=y # CONFIG_ARCH_BOARD_MIKROE_STM32F4 is not set # CONFIG_ARCH_BOARD_CUSTOM is not set CONFIG_ARCH_BOARD="stm32f4discovery" # # Common Board Options # CONFIG_ARCH_HAVE_LEDS=y CONFIG_ARCH_LEDS=y CONFIG_ARCH_HAVE_BUTTONS=y CONFIG_ARCH_BUTTONS=y CONFIG_ARCH_HAVE_IRQBUTTONS=y # CONFIG_ARCH_IRQBUTTONS is not set # # Board-Specific Options # # CONFIG_STM32F4DISBB is not set # CONFIG_BOARD_CRASHDUMP is not set CONFIG_LIB_BOARDCTL=y # CONFIG_BOARDCTL_RESET is not set # CONFIG_BOARDCTL_UNIQUEID is not set CONFIG_BOARDCTL_USBDEVCTRL=y # CONFIG_BOARDCTL_TSCTEST is not set # CONFIG_BOARDCTL_GRAPHICS is not set # CONFIG_BOARDCTL_IOCTL is not set # # 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=10000 # CONFIG_SYSTEM_TIME64 is not set CONFIG_CLOCK_MONOTONIC=y CONFIG_ARCH_HAVE_TIMEKEEPING=y # CONFIG_JULIAN_TIME is not set CONFIG_START_YEAR=2013 CONFIG_START_MONTH=1 CONFIG_START_DAY=27 CONFIG_MAX_WDOGPARMS=2 CONFIG_PREALLOC_WDOGS=8 CONFIG_WDOG_INTRESERVE=1 CONFIG_PREALLOC_TIMERS=4 # # Tasks and Scheduling # # CONFIG_SPINLOCK is not set # CONFIG_INIT_NONE is not set CONFIG_INIT_ENTRYPOINT=y # CONFIG_INIT_FILEPATH is not set CONFIG_USER_ENTRYPOINT="nsh_main" CONFIG_RR_INTERVAL=200 # CONFIG_SCHED_SPORADIC is not set CONFIG_TASK_NAME_SIZE=31 CONFIG_MAX_TASKS=16 # CONFIG_SCHED_HAVE_PARENT is not set CONFIG_SCHED_WAITPID=y # # Pthread Options # CONFIG_MUTEX_TYPES=y 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 # # Files and I/O # CONFIG_DEV_CONSOLE=y # CONFIG_FDCLONE_DISABLE is not set # CONFIG_FDCLONE_STDIO is not set CONFIG_SDCLONE_DISABLE=y CONFIG_NFILE_DESCRIPTORS=8 CONFIG_NFILE_STREAMS=8 CONFIG_NAME_MAX=32 # CONFIG_PRIORITY_INHERITANCE is not set # # RTOS hooks # # CONFIG_BOARD_INITIALIZE is not set # CONFIG_SCHED_STARTHOOK is not set # CONFIG_SCHED_ATEXIT is not set # CONFIG_SCHED_ONEXIT is not set # CONFIG_SIG_EVTHREAD is not set # # Signal Numbers # CONFIG_SIG_SIGUSR1=1 CONFIG_SIG_SIGUSR2=2 CONFIG_SIG_SIGALARM=3 CONFIG_SIG_SIGCONDTIMEDOUT=16 CONFIG_SIG_SIGWORK=17 # # POSIX Message Queue Options # CONFIG_PREALLOC_MQ_MSGS=4 CONFIG_MQ_MAXMSGSIZE=32 # CONFIG_MODULE is not set # # Work queue support # CONFIG_SCHED_WORKQUEUE=y CONFIG_SCHED_HPWORK=y CONFIG_SCHED_HPWORKPRIORITY=224 CONFIG_SCHED_HPWORKPERIOD=50000 CONFIG_SCHED_HPWORKSTACKSIZE=2048 # CONFIG_SCHED_LPWORK is not set # # Stack and heap information # CONFIG_IDLETHREAD_STACKSIZE=2048 CONFIG_USERMAIN_STACKSIZE=2048 CONFIG_PTHREAD_STACK_MIN=256 CONFIG_PTHREAD_STACK_DEFAULT=2048 # CONFIG_LIB_SYSCALL is not set # # Device Drivers # # CONFIG_DISABLE_POLL is not set CONFIG_DEV_NULL=y # CONFIG_DEV_ZERO is not set # CONFIG_DEV_URANDOM is not set # CONFIG_DEV_LOOP is not set # # Buffering # # CONFIG_DRVR_WRITEBUFFER is not set # CONFIG_DRVR_READAHEAD is not set # CONFIG_RAMDISK is not set # CONFIG_CAN is not set CONFIG_ARCH_HAVE_PWM_PULSECOUNT=y # CONFIG_ARCH_HAVE_PWM_MULTICHAN is not set CONFIG_PWM=y # CONFIG_PWM_PULSECOUNT is not set CONFIG_ARCH_HAVE_I2CRESET=y CONFIG_I2C=y # CONFIG_I2C_SLAVE is not set # CONFIG_I2C_POLLED is not set # CONFIG_I2C_RESET is not set # CONFIG_I2C_TRACE is not set # CONFIG_I2C_DRIVER is not set CONFIG_SPI=y # CONFIG_ARCH_HAVE_SPI_CRCGENERATION is not set # CONFIG_ARCH_HAVE_SPI_CS_CONTROL is not set CONFIG_ARCH_HAVE_SPI_BITORDER=y # CONFIG_SPI_SLAVE is not set CONFIG_SPI_EXCHANGE=y # CONFIG_SPI_CMDDATA is not set # CONFIG_SPI_CALLBACK is not set # CONFIG_SPI_HWFEATURES is not set # CONFIG_SPI_BITORDER is not set # CONFIG_SPI_CS_DELAY_CONTROL is not set # CONFIG_SPI_DRIVER is not set # CONFIG_SPI_BITBANG is not set # CONFIG_I2S is not set # # Timer Driver Support # # CONFIG_TIMER is not set # CONFIG_ONESHOT is not set # CONFIG_RTC is not set # CONFIG_WATCHDOG is not set # CONFIG_TIMERS_CS2100CP is not set CONFIG_ANALOG=y CONFIG_ADC=y CONFIG_ADC_FIFOSIZE=8 # CONFIG_ADC_NO_STARTUP_CONV is not set # CONFIG_ADC_ADS1242 is not set # CONFIG_ADC_ADS125X is not set # CONFIG_ADC_PGA11X is not set # CONFIG_DAC is not set # CONFIG_AUDIO_DEVICES is not set # CONFIG_VIDEO_DEVICES is not set # CONFIG_BCH is not set # CONFIG_INPUT is not set # # IO Expander/GPIO Support # # CONFIG_IOEXPANDER is not set # CONFIG_DEV_GPIO is not set # # LCD Driver Support # # CONFIG_LCD is not set # CONFIG_SLCD is not set # # LED Support # # CONFIG_USERLED is not set # CONFIG_RGBLED is not set # CONFIG_PCA9635PW is not set # CONFIG_NCP5623C is not set CONFIG_MMCSD=y CONFIG_MMCSD_NSLOTS=1 # CONFIG_MMCSD_READONLY is not set # CONFIG_MMCSD_MULTIBLOCK_DISABLE is not set CONFIG_MMCSD_MMCSUPPORT=y CONFIG_MMCSD_HAVECARDDETECT=y CONFIG_MMCSD_SPI=y CONFIG_MMCSD_SPICLOCK=20000000 CONFIG_MMCSD_SPIMODE=0 CONFIG_ARCH_HAVE_SDIO=y CONFIG_ARCH_HAVE_SDIOWAIT_WRCOMPLETE=y CONFIG_MMCSD_SDIO=y CONFIG_SDIO_PREFLIGHT=y # CONFIG_SDIO_MUXBUS is not set # CONFIG_MMCSD_SDIOWAIT_WRCOMPLETE is not set # CONFIG_SDIO_BLOCKSETUP is not set # CONFIG_MODEM is not set # CONFIG_MTD is not set # CONFIG_EEPROM is not set CONFIG_NETDEVICES=y # # General Ethernet MAC Driver Options # # CONFIG_NETDEV_LOOPBACK is not set # CONFIG_NETDEV_TELNET is not set # CONFIG_NETDEV_MULTINIC is not set # CONFIG_ARCH_HAVE_NETDEV_STATISTICS is not set CONFIG_NETDEV_LATEINIT=y # # External Ethernet MAC Device Support # # CONFIG_NET_DM90x0 is not set # CONFIG_ENC28J60 is not set # CONFIG_ENCX24J600 is not set # CONFIG_NET_SLIP is not set # CONFIG_NET_FTMAC100 is not set CONFIG_PIPES=y CONFIG_DEV_PIPE_MAXSIZE=1024 CONFIG_DEV_PIPE_SIZE=1024 CONFIG_DEV_FIFO_SIZE=1024 # CONFIG_PM is not set # CONFIG_POWER is not set # CONFIG_SENSORS is not set CONFIG_SERIAL=y # CONFIG_DEV_LOWCONSOLE is not set CONFIG_SERIAL_REMOVABLE=y # CONFIG_SERIAL_CONSOLE is not set # CONFIG_16550_UART is not set # CONFIG_UART_SERIALDRIVER is not set # CONFIG_UART0_SERIALDRIVER is not set # CONFIG_UART1_SERIALDRIVER is not set # CONFIG_UART2_SERIALDRIVER is not set # CONFIG_UART3_SERIALDRIVER is not set # CONFIG_UART4_SERIALDRIVER is not set # CONFIG_UART5_SERIALDRIVER is not set # CONFIG_UART6_SERIALDRIVER is not set # CONFIG_UART7_SERIALDRIVER is not set # CONFIG_UART8_SERIALDRIVER is not set # CONFIG_SCI0_SERIALDRIVER is not set # CONFIG_SCI1_SERIALDRIVER is not set # CONFIG_USART0_SERIALDRIVER is not set # CONFIG_USART1_SERIALDRIVER is not set CONFIG_USART2_SERIALDRIVER=y # CONFIG_USART3_SERIALDRIVER is not set # CONFIG_USART4_SERIALDRIVER is not set # CONFIG_USART5_SERIALDRIVER is not set # CONFIG_USART6_SERIALDRIVER is not set # CONFIG_USART7_SERIALDRIVER is not set # CONFIG_USART8_SERIALDRIVER is not set # CONFIG_OTHER_UART_SERIALDRIVER is not set 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_DMA is not set CONFIG_ARCH_HAVE_SERIAL_TERMIOS=y # CONFIG_USART2_SERIAL_CONSOLE is not set # CONFIG_OTHER_SERIAL_CONSOLE is not set CONFIG_NO_SERIAL_CONSOLE=y # # USART2 Configuration # CONFIG_USART2_RXBUFSIZE=256 CONFIG_USART2_TXBUFSIZE=256 CONFIG_USART2_BAUD=115200 CONFIG_USART2_BITS=8 CONFIG_USART2_PARITY=0 CONFIG_USART2_2STOP=0 # CONFIG_USART2_IFLOWCONTROL is not set # CONFIG_USART2_OFLOWCONTROL is not set # CONFIG_USART2_DMA is not set # CONFIG_PSEUDOTERM is not set CONFIG_USBDEV=y # # USB Device Controller Driver Options # # CONFIG_USBDEV_ISOCHRONOUS is not set # CONFIG_USBDEV_DUALSPEED is not set CONFIG_USBDEV_SELFPOWERED=y # CONFIG_USBDEV_BUSPOWERED is not set CONFIG_USBDEV_MAXPOWER=100 # CONFIG_USBDEV_DMA is not set # CONFIG_ARCH_USBDEV_STALLQUEUE is not set # CONFIG_USBDEV_TRACE is not set # # USB Device Class Driver Options # # CONFIG_USBDEV_COMPOSITE is not set # CONFIG_PL2303 is not set CONFIG_CDCACM=y CONFIG_CDCACM_CONSOLE=y CONFIG_CDCACM_EP0MAXPACKET=64 CONFIG_CDCACM_EPINTIN=1 CONFIG_CDCACM_EPINTIN_FSSIZE=64 CONFIG_CDCACM_EPINTIN_HSSIZE=64 CONFIG_CDCACM_EPBULKOUT=3 CONFIG_CDCACM_EPBULKOUT_FSSIZE=64 CONFIG_CDCACM_EPBULKOUT_HSSIZE=512 CONFIG_CDCACM_EPBULKIN=2 CONFIG_CDCACM_EPBULKIN_FSSIZE=64 CONFIG_CDCACM_EPBULKIN_HSSIZE=512 CONFIG_CDCACM_NRDREQS=4 CONFIG_CDCACM_NWRREQS=4 CONFIG_CDCACM_BULKIN_REQLEN=96 CONFIG_CDCACM_RXBUFSIZE=256 CONFIG_CDCACM_TXBUFSIZE=256 CONFIG_CDCACM_VENDORID=0x0525 CONFIG_CDCACM_PRODUCTID=0xa4a7 CONFIG_CDCACM_VENDORSTR="NuttX" CONFIG_CDCACM_PRODUCTSTR="CDC/ACM Serial" # CONFIG_USBMSC is not set # CONFIG_USBHOST is not set # CONFIG_HAVE_USBTRACE is not set # CONFIG_DRIVERS_WIRELESS is not set # CONFIG_DRIVERS_CONTACTLESS is not set # # System Logging # # CONFIG_ARCH_SYSLOG is not set # CONFIG_RAMLOG is not set # CONFIG_SYSLOG_INTBUFFER is not set # CONFIG_SYSLOG_TIMESTAMP is not set # CONFIG_SYSLOG_SERIAL_CONSOLE is not set CONFIG_SYSLOG_CHAR=y # CONFIG_SYSLOG_CONSOLE is not set # CONFIG_SYSLOG_NONE is not set # CONFIG_SYSLOG_FILE is not set # CONFIG_CONSOLE_SYSLOG is not set CONFIG_SYSLOG_CHAR_CRLF=y CONFIG_SYSLOG_DEVPATH="/dev/ttyS0" # CONFIG_SYSLOG_CHARDEV is not set # # Networking Support # CONFIG_ARCH_HAVE_NET=y # CONFIG_ARCH_HAVE_PHY is not set CONFIG_NET=y # CONFIG_NET_PROMISCUOUS is not set # # Driver buffer configuration # CONFIG_NET_ETH_MTU=590 CONFIG_NET_ETH_TCP_RECVWNDO=536 CONFIG_NET_GUARDSIZE=2 # # Data link support # # CONFIG_NET_MULTILINK is not set CONFIG_NET_ETHERNET=y # CONFIG_NET_LOOPBACK is not set # CONFIG_NET_TUN is not set # # Network Device Operations # # CONFIG_NETDEV_PHY_IOCTL is not set # # Internet Protocol Selection # CONFIG_NET_IPv4=y # CONFIG_NET_IPv6 is not set # # Socket Support # CONFIG_NSOCKET_DESCRIPTORS=8 CONFIG_NET_NACTIVESOCKETS=16 CONFIG_NET_SOCKOPTS=y # CONFIG_NET_SOLINGER is not set # # Raw Socket Support # # CONFIG_NET_PKT is not set # # Unix Domain Socket Support # CONFIG_NET_LOCAL=y CONFIG_NET_LOCAL_STREAM=y CONFIG_NET_LOCAL_DGRAM=y # # TCP/IP Networking # CONFIG_NET_TCP=y # CONFIG_NET_TCPURGDATA is not set CONFIG_NET_TCP_CONNS=8 CONFIG_NET_MAX_LISTENPORTS=20 CONFIG_NET_TCP_READAHEAD=y CONFIG_NET_TCP_WRITE_BUFFERS=y CONFIG_NET_TCP_NWRBCHAINS=8 CONFIG_NET_TCP_RECVDELAY=0 # CONFIG_NET_TCPBACKLOG is not set # CONFIG_NET_SENDFILE is not set # # UDP Networking # # CONFIG_NET_UDP is not set # # ICMP Networking Support # # CONFIG_NET_ICMP is not set # # IGMPv2 Client Support # # CONFIG_NET_IGMP is not set # # ARP Configuration # CONFIG_NET_ARP=y CONFIG_NET_ARPTAB_SIZE=16 CONFIG_NET_ARP_MAXAGE=120 # CONFIG_NET_ARP_IPIN is not set # CONFIG_NET_ARP_SEND is not set # # Network I/O Buffer Support # CONFIG_NET_IOB=y CONFIG_IOB_NBUFFERS=36 CONFIG_IOB_BUFSIZE=196 CONFIG_IOB_NCHAINS=8 CONFIG_IOB_THROTTLE=8 # CONFIG_NET_ARCH_INCR32 is not set # CONFIG_NET_ARCH_CHKSUM is not set # CONFIG_NET_STATISTICS is not set # # Routing Table Configuration # # CONFIG_NET_ROUTE is not set CONFIG_NET_HOSTNAME="" # # Crypto API # # CONFIG_CRYPTO 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_NAMED_SEMAPHORES is not set CONFIG_FS_MQUEUE_MPATH="/var/mqueue" # CONFIG_FS_RAMMAP is not set CONFIG_FS_FAT=y CONFIG_FAT_LCNAMES=y CONFIG_FAT_LFN=y CONFIG_FAT_MAXFNAME=32 # CONFIG_FS_FATTIME is not set # CONFIG_FAT_FORCE_INDIRECT is not set # CONFIG_FAT_DMAMEMORY is not set # CONFIG_FAT_DIRECT_RETRY is not set # CONFIG_FS_NXFFS is not set # CONFIG_FS_ROMFS is not set # CONFIG_FS_TMPFS is not set # CONFIG_FS_SMARTFS is not set # CONFIG_FS_BINFS is not set CONFIG_FS_PROCFS=y # CONFIG_FS_PROCFS_REGISTER is not set # # Exclude individual procfs entries # # CONFIG_FS_PROCFS_EXCLUDE_PROCESS is not set # CONFIG_FS_PROCFS_EXCLUDE_UPTIME is not set # CONFIG_FS_PROCFS_EXCLUDE_MOUNTS is not set # CONFIG_FS_PROCFS_EXCLUDE_NET is not set # CONFIG_FS_UNIONFS is not set # # Graphics Support # # CONFIG_NX is not set # # Memory Management # # CONFIG_MM_SMALL is not set CONFIG_MM_REGIONS=2 # CONFIG_ARCH_HAVE_HEAP2 is not set # CONFIG_GRAN is not set # # Audio Support # # CONFIG_AUDIO is not set # # Wireless Support # # # Binary Loader # # CONFIG_BINFMT_DISABLE is not set # CONFIG_BINFMT_EXEPATH is not set # CONFIG_NXFLAT is not set # CONFIG_ELF is not set CONFIG_BUILTIN=y # CONFIG_PIC is not set # CONFIG_SYMTAB_ORDEREDBYNAME 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 is not set CONFIG_LIBC_LONG_LONG=y # CONFIG_LIBC_IOCTL_VARIADIC is not set # CONFIG_LIBC_WCHAR is not set # CONFIG_LIBC_LOCALE is not set 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_LIBC_EXECFUNCS is not set CONFIG_POSIX_SPAWN_PROXY_STACKSIZE=1024 CONFIG_TASK_SPAWN_DEFAULT_STACKSIZE=2048 # CONFIG_LIBC_STRERROR 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 is not set CONFIG_ARCH_HAVE_TLS=y # CONFIG_TLS is not set # CONFIG_LIBC_IPv6_ADDRCONV is not set CONFIG_LIBC_NETDB=y # CONFIG_NETDB_HOSTFILE is not set # # Non-standard Library Support # # CONFIG_LIB_CRC64_FAST is not set # CONFIG_LIB_KBDCODEC is not set # CONFIG_LIB_SLCDCODEC is not set # CONFIG_LIB_HEX2BIN is not set # # Basic CXX Support # # CONFIG_C99_BOOL8 is not set CONFIG_HAVE_CXX=y CONFIG_HAVE_CXXINITIALIZE=y # CONFIG_CXX_NEWLONG is not set # # uClibc++ Standard C++ Library # # CONFIG_UCLIBCXX is not set # # Application Configuration # # # NxWidgets/NxWM # # # Built-In Applications # CONFIG_BUILTIN_PROXY_STACKSIZE=1024 # # CAN Utilities # # # Examples # # CONFIG_EXAMPLES_ADC is not set # CONFIG_EXAMPLES_BUTTONS is not set # CONFIG_EXAMPLES_CCTYPE is not set # CONFIG_EXAMPLES_CHAT is not set # CONFIG_EXAMPLES_CONFIGDATA is not set # CONFIG_EXAMPLES_CPUHOG is not set # CONFIG_EXAMPLES_CXXTEST is not set # CONFIG_EXAMPLES_DHCPD is not set # CONFIG_EXAMPLES_ELF is not set # CONFIG_EXAMPLES_FSTEST is not set # CONFIG_EXAMPLES_FTPC is not set # CONFIG_EXAMPLES_FTPD is not set # CONFIG_EXAMPLES_HELLO is not set # CONFIG_EXAMPLES_HELLOXX is not set # CONFIG_EXAMPLES_HIDKBD is not set # CONFIG_EXAMPLES_IGMP is not set # CONFIG_EXAMPLES_JSON is not set # CONFIG_EXAMPLES_KEYPADTEST is not set # CONFIG_EXAMPLES_MEDIA is not set # CONFIG_EXAMPLES_MM is not set # CONFIG_EXAMPLES_MODBUS is not set # CONFIG_EXAMPLES_MOUNT is not set # CONFIG_EXAMPLES_NETTEST is not set # CONFIG_EXAMPLES_NRF24L01TERM is not set CONFIG_EXAMPLES_NSH=y CONFIG_EXAMPLES_NSH_CXXINITIALIZE=y # CONFIG_EXAMPLES_NULL is not set # CONFIG_EXAMPLES_NX is not set # CONFIG_EXAMPLES_NXFFS is not set # CONFIG_EXAMPLES_NXHELLO is not set # CONFIG_EXAMPLES_NXIMAGE is not set # CONFIG_EXAMPLES_NXLINES is not set # CONFIG_EXAMPLES_NXTERM is not set # CONFIG_EXAMPLES_NXTEXT is not set # CONFIG_EXAMPLES_OSTEST is not set # CONFIG_EXAMPLES_PCA9635 is not set # CONFIG_EXAMPLES_PIPE is not set # CONFIG_EXAMPLES_POSIXSPAWN is not set # CONFIG_EXAMPLES_PPPD is not set # CONFIG_EXAMPLES_PWM is not set # CONFIG_EXAMPLES_RFID_READUID is not set # CONFIG_EXAMPLES_RGBLED is not set # CONFIG_EXAMPLES_SENDMAIL is not set # CONFIG_EXAMPLES_SERIALBLASTER is not set # CONFIG_EXAMPLES_SERIALRX is not set # CONFIG_EXAMPLES_SERLOOP is not set # CONFIG_EXAMPLES_SLCD is not set # CONFIG_EXAMPLES_SMART is not set # CONFIG_EXAMPLES_SMART_TEST is not set # CONFIG_EXAMPLES_SMP is not set # CONFIG_EXAMPLES_TCPECHO is not set # CONFIG_EXAMPLES_TELNETD is not set # CONFIG_EXAMPLES_TIFF is not set # CONFIG_EXAMPLES_TOUCHSCREEN is not set # CONFIG_EXAMPLES_UDGRAM is not set # CONFIG_EXAMPLES_USBSERIAL is not set # CONFIG_EXAMPLES_USBTERM is not set # CONFIG_EXAMPLES_USTREAM is not set # CONFIG_EXAMPLES_WATCHDOG is not set # CONFIG_EXAMPLES_WEBSERVER is not set # CONFIG_EXAMPLES_XMLRPC is not set # # File System Utilities # # CONFIG_FSUTILS_INIFILE is not set # CONFIG_FSUTILS_PASSWD is not set # # GPS Utilities # # CONFIG_GPSUTILS_MINMEA_LIB is not set # # Graphics Support # # CONFIG_TIFF is not set # CONFIG_GRAPHICS_TRAVELER is not set # # Interpreters # # CONFIG_INTERPRETERS_BAS is not set # CONFIG_INTERPRETERS_FICL is not set # CONFIG_INTERPRETERS_MICROPYTHON is not set # CONFIG_INTERPRETERS_MINIBASIC is not set # CONFIG_INTERPRETERS_PCODE is not set # # FreeModBus # # CONFIG_MODBUS is not set # # Network Utilities # # CONFIG_NETUTILS_CHAT is not set # CONFIG_NETUTILS_CODECS is not set # CONFIG_NETUTILS_ESP8266 is not set # CONFIG_NETUTILS_FTPC is not set # CONFIG_NETUTILS_FTPD is not set # CONFIG_NETUTILS_JSON is not set CONFIG_NETUTILS_NETLIB=y # CONFIG_NETUTILS_SMTP is not set # CONFIG_NETUTILS_TELNETD is not set # CONFIG_NETUTILS_WEBCLIENT is not set # CONFIG_NETUTILS_WEBSERVER is not set # CONFIG_NETUTILS_XMLRPC is not set # # NSH Library # CONFIG_NSH_LIBRARY=y # CONFIG_NSH_MOTD is not set # # Command Line Configuration # CONFIG_NSH_READLINE=y # CONFIG_NSH_CLE is not set CONFIG_NSH_LINELEN=64 # CONFIG_NSH_DISABLE_SEMICOLON is not set CONFIG_NSH_CMDPARMS=y CONFIG_NSH_MAXARGUMENTS=6 CONFIG_NSH_ARGCAT=y CONFIG_NSH_NESTDEPTH=3 # CONFIG_NSH_DISABLEBG is not set CONFIG_NSH_BUILTIN_APPS=y # # Disable Individual commands # # CONFIG_NSH_DISABLE_ADDROUTE is not set # CONFIG_NSH_DISABLE_ARP is not set # CONFIG_NSH_DISABLE_BASENAME is not set # CONFIG_NSH_DISABLE_CAT is not set # CONFIG_NSH_DISABLE_CD is not set # CONFIG_NSH_DISABLE_CP is not set # CONFIG_NSH_DISABLE_CMP is not set CONFIG_NSH_DISABLE_DATE=y # CONFIG_NSH_DISABLE_DD is not set # CONFIG_NSH_DISABLE_DF is not set # CONFIG_NSH_DISABLE_DELROUTE is not set # CONFIG_NSH_DISABLE_DIRNAME is not set # CONFIG_NSH_DISABLE_ECHO is not set # CONFIG_NSH_DISABLE_EXEC is not set # CONFIG_NSH_DISABLE_EXIT is not set # CONFIG_NSH_DISABLE_FREE is not set # CONFIG_NSH_DISABLE_GET is not set # CONFIG_NSH_DISABLE_HELP is not set # CONFIG_NSH_DISABLE_HEXDUMP is not set # CONFIG_NSH_DISABLE_IFCONFIG is not set # CONFIG_NSH_DISABLE_IFUPDOWN is not set # CONFIG_NSH_DISABLE_KILL is not set # CONFIG_NSH_DISABLE_LOSETUP is not set CONFIG_NSH_DISABLE_LOSMART=y # CONFIG_NSH_DISABLE_LS is not set # CONFIG_NSH_DISABLE_MB is not set # CONFIG_NSH_DISABLE_MKDIR is not set # CONFIG_NSH_DISABLE_MKFATFS is not set # CONFIG_NSH_DISABLE_MKFIFO is not set # CONFIG_NSH_DISABLE_MKRD is not set # CONFIG_NSH_DISABLE_MH is not set # CONFIG_NSH_DISABLE_MOUNT is not set # CONFIG_NSH_DISABLE_MV is not set # CONFIG_NSH_DISABLE_MW is not set CONFIG_NSH_DISABLE_PRINTF=y # CONFIG_NSH_DISABLE_PS is not set # CONFIG_NSH_DISABLE_PUT is not set # CONFIG_NSH_DISABLE_PWD is not set # CONFIG_NSH_DISABLE_RM is not set # CONFIG_NSH_DISABLE_RMDIR is not set # CONFIG_NSH_DISABLE_SET is not set # CONFIG_NSH_DISABLE_SH is not set # CONFIG_NSH_DISABLE_SLEEP is not set # CONFIG_NSH_DISABLE_TIME is not set # CONFIG_NSH_DISABLE_TEST is not set # CONFIG_NSH_DISABLE_UMOUNT is not set # CONFIG_NSH_DISABLE_UNAME is not set # CONFIG_NSH_DISABLE_UNSET is not set # CONFIG_NSH_DISABLE_USLEEP is not set # CONFIG_NSH_DISABLE_WGET is not set # CONFIG_NSH_DISABLE_XD is not set CONFIG_NSH_MMCSDMINOR=0 CONFIG_NSH_MMCSDSLOTNO=0 CONFIG_NSH_MMCSDSPIPORTNO=0 # # Configure Command Options # CONFIG_NSH_CMDOPT_DF_H=y # CONFIG_NSH_CMDOPT_DD_STATS is not set CONFIG_NSH_CODECS_BUFSIZE=128 CONFIG_NSH_CMDOPT_HEXDUMP=y CONFIG_NSH_PROC_MOUNTPOINT="/proc" CONFIG_NSH_FILEIOSIZE=512 # # Scripting Support # # CONFIG_NSH_DISABLESCRIPT is not set # CONFIG_NSH_DISABLE_ITEF is not set # CONFIG_NSH_DISABLE_LOOPS is not set # # Console Configuration # CONFIG_NSH_CONSOLE=y # CONFIG_NSH_USBCONSOLE is not set # CONFIG_NSH_ALTCONDEV is not set CONFIG_NSH_ARCHINIT=y # # Networking Configuration # CONFIG_NSH_NETINIT=y # CONFIG_NSH_NETINIT_THREAD is not set # # IP Address Configuration # # # IPv4 Addresses # CONFIG_NSH_IPADDR=0x0a000002 CONFIG_NSH_DRIPADDR=0x0a000001 CONFIG_NSH_NETMASK=0xffffff00 # CONFIG_NSH_NOMAC is not set CONFIG_NSH_MAX_ROUNDTRIP=20 # CONFIG_NSH_LOGIN is not set # CONFIG_NSH_CONSOLE_LOGIN is not set # # Platform-specific Support # # CONFIG_PLATFORM_CONFIGDATA is not set # # System Libraries and NSH Add-Ons # # CONFIG_SYSTEM_CDCACM is not set # CONFIG_SYSTEM_CLE is not set # CONFIG_SYSTEM_CUTERM is not set # CONFIG_SYSTEM_FREE is not set # CONFIG_SYSTEM_HEX2BIN is not set # CONFIG_SYSTEM_HEXED is not set # CONFIG_SYSTEM_I2CTOOL is not set # CONFIG_SYSTEM_INSTALL is not set CONFIG_IOTJS=y CONFIG_IOTJS_PRIORITY=100 CONFIG_IOTJS_STACKSIZE=16384 # CONFIG_SYSTEM_NETDB is not set # CONFIG_SYSTEM_RAMTEST is not set CONFIG_READLINE_HAVE_EXTMATCH=y CONFIG_SYSTEM_READLINE=y CONFIG_READLINE_ECHO=y CONFIG_READLINE_TABCOMPLETION=y CONFIG_READLINE_MAX_BUILTINS=64 CONFIG_READLINE_MAX_EXTCMDS=64 CONFIG_READLINE_CMD_HISTORY=y CONFIG_READLINE_CMD_HISTORY_LINELEN=80 CONFIG_READLINE_CMD_HISTORY_LEN=16 # CONFIG_SYSTEM_SUDOKU is not set # CONFIG_SYSTEM_SYSTEM is not set # CONFIG_SYSTEM_TEE is not set # CONFIG_SYSTEM_UBLOXMODEM is not set # CONFIG_SYSTEM_VI is not set # CONFIG_SYSTEM_ZMODEM is not set iotjs-1.0+715/config/nuttx/stm32f4dis/patch000066400000000000000000000013211371177304000203650ustar00rootroot00000000000000--- a/configs/stm32f4discovery/include/board.h +++ b/configs/stm32f4discovery/include/board.h @@ -253,6 +253,13 @@ # define GPIO_CAN2_TX GPIO_CAN2_TX_1 #endif # Patch code to enable UART1: # It maps pin PB6 and pin PB7 to USART1_TX and USART2_RX respectively. # + +#define GPIO_USART1_RX GPIO_USART1_RX_2 +#define GPIO_USART1_TX GPIO_USART1_TX_2 + # Patch code to enable UART4: # It maps pin PA0 and pin PA1 to UART4_TX and UART4_RX respectively. # Because it makes conflict with pins of USART2, # you have to disable USART2 to use this port. # +#define GPIO_UART4_RX GPIO_UART4_RX_1 +#define GPIO_UART4_TX GPIO_UART4_TX_1 + /* UART2: * * The STM32F4 Discovery has no on-board serial devices, but the console is iotjs-1.0+715/config/nuttx/stm32f7nucleo/000077500000000000000000000000001371177304000200575ustar00rootroot00000000000000iotjs-1.0+715/config/nuttx/stm32f7nucleo/config.default000066400000000000000000000044741371177304000227030ustar00rootroot00000000000000# # This file is autogenerated: PLEASE DO NOT EDIT IT. # # You can use "make menuconfig" to make any modifications to the installed .config file. # You can then do "make savedefconfig" to generate a new defconfig file that includes your # modifications. # CONFIG_ARCH="arm" CONFIG_ARCH_BOARD="nucleo-144" CONFIG_ARCH_BOARD_NUCLEO_144=y CONFIG_ARCH_BUTTONS=y CONFIG_ARCH_CHIP_STM32F767ZI=y CONFIG_ARCH_CHIP_STM32F7=y CONFIG_ARCH_STACKDUMP=y CONFIG_ARMV7M_DCACHE=y CONFIG_ARMV7M_DCACHE_WRITETHROUGH=y CONFIG_ARMV7M_DTCM=y CONFIG_ARMV7M_ICACHE=y CONFIG_BOARD_LOOPSPERMSEC=43103 CONFIG_BUILTIN=y CONFIG_DEBUG_SYMBOLS=y CONFIG_ETH0_PHY_LAN8742A=y CONFIG_FS_PROCFS=y CONFIG_FS_PROCFS_REGISTER=y CONFIG_FS_TMPFS=y CONFIG_HAVE_CXX=y CONFIG_HAVE_CXXINITIALIZE=y CONFIG_IOTJS=y CONFIG_LIB_HOSTNAME="stntest" CONFIG_MAX_TASKS=16 CONFIG_MAX_WDOGPARMS=2 CONFIG_MM_REGIONS=3 CONFIG_NET=y CONFIG_NETDB_DNSCLIENT=y CONFIG_NETUTILS_DISCOVER=y CONFIG_NETUTILS_WEBCLIENT=y CONFIG_NET_ARP_IPIN=y CONFIG_NET_ARP_SEND=y CONFIG_NET_BROADCAST=y CONFIG_NET_ETH_PKTSIZE=1500 CONFIG_NET_ICMP=y CONFIG_NET_ICMP_SOCKET=y CONFIG_NET_IGMP=y CONFIG_NET_LOCAL=y CONFIG_NET_LOOPBACK=y CONFIG_NET_ROUTE=y CONFIG_NET_SOLINGER=y CONFIG_NET_STATISTICS=y CONFIG_NET_TCP=y CONFIG_NET_TCPBACKLOG=y CONFIG_NET_UDP=y CONFIG_NET_UDP_CHECKSUMS=y CONFIG_NFILE_DESCRIPTORS=8 CONFIG_NFILE_STREAMS=8 CONFIG_NSH_BUILTIN_APPS=y CONFIG_NSH_FILEIOSIZE=512 CONFIG_NSH_LINELEN=64 CONFIG_NSH_READLINE=y CONFIG_NUCLEO_CONSOLE_VIRTUAL=y CONFIG_PREALLOC_MQ_MSGS=4 CONFIG_PREALLOC_TIMERS=4 CONFIG_PREALLOC_WDOGS=4 CONFIG_PTHREAD_MUTEX_TYPES=y CONFIG_RAM_SIZE=245760 CONFIG_RAM_START=0x20010000 CONFIG_RAW_BINARY=y CONFIG_RR_INTERVAL=100 CONFIG_SCHED_HPWORK=y CONFIG_SCHED_LPWORK=y CONFIG_SCHED_LPWORKPRIORITY=176 CONFIG_SCHED_WAITPID=y CONFIG_SDCLONE_DISABLE=y CONFIG_SPI=y CONFIG_STACK_COLORATION=y CONFIG_START_DAY=30 CONFIG_START_MONTH=11 CONFIG_START_YEAR=2015 CONFIG_STM32F7_ETHMAC=y CONFIG_STM32F7_PHYADDR=0 CONFIG_STM32F7_PHYSR=31 CONFIG_STM32F7_PHYSR_100FD=0x0018 CONFIG_STM32F7_PHYSR_100HD=0x0008 CONFIG_STM32F7_PHYSR_10FD=0x0014 CONFIG_STM32F7_PHYSR_10HD=0x0004 CONFIG_STM32F7_PHYSR_ALTCONFIG=y CONFIG_STM32F7_PHYSR_ALTMODE=0x001c CONFIG_SYSTEM_DHCPC_RENEW=y CONFIG_SYSTEM_NSH=y CONFIG_SYSTEM_PING=y CONFIG_TASK_NAME_SIZE=0 CONFIG_USART3_SERIAL_CONSOLE=y CONFIG_USER_ENTRYPOINT="nsh_main" CONFIG_WDOG_INTRESERVE=0 iotjs-1.0+715/config/nuttx/stm32f7nucleo/nuttx.profile000066400000000000000000000002261371177304000226230ustar00rootroot00000000000000ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_IOTJS_CORE_MODULES ENABLE_MODULE_ADC ENABLE_MODULE_GPIO ENABLE_MODULE_PWM ENABLE_MODULE_STM32F7NUCLEO iotjs-1.0+715/config/tizen/000077500000000000000000000000001371177304000154135ustar00rootroot00000000000000iotjs-1.0+715/config/tizen/.gbs.conf000066400000000000000000000001701371177304000171110ustar00rootroot00000000000000[general] upstream_branch = ${upstreamversion} upstream_tag = ${upstreamversion} packaging_dir = config/tizen/packaging iotjs-1.0+715/config/tizen/filter.txt000066400000000000000000000000171371177304000174370ustar00rootroot00000000000000P /.git - .git iotjs-1.0+715/config/tizen/gbsbuild.sh000077500000000000000000000047511371177304000175540ustar00rootroot00000000000000#!/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. function print_usage { echo "USAGE: $0 [--debug|--clean]" echo "" echo "Optional arguments:" echo "--debug: Build IoT.js in debug mode. The default is release mode." echo "--clean: Make a clean gbs build by deleting the old build root." echo "" } buildtype="release" unset cleanbuild while [ -n "$1" ]; do case $1 in --debug ) buildtype="debug" ;; --clean ) cleanbuild=true ;; * ) print_usage exit 1; ;; esac shift done echo "******************************************************************" echo "* Tizen GBS build *" echo "* ~/.gbs.conf sample is at 'config/tizen/sample.gbs.conf'. *" echo "******************************************************************" echo "" echo "This working folder will be copied to ../iotjs_tizen_gbs" cd .. 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 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(3) Calling core gbs build command" gbsconf="config/tizen/sample.gbs.conf" gbscommand="gbs -c $gbsconf build -A armv7l --include-all" gbscommand+=" ${cleanbuild:+--clean} --define='build_mode $buildtype'" gbscommand+=" --define='external_build_options $IOTJS_BUILD_OPTION'" ret=0 echo $gbscommand if eval $gbscommand then echo "========================================================" echo "1. GBS Build is successful." echo "2. You can find rpm packages in below folder" echo " ~/GBS-ROOT/local/repos/tizen50m2/armv7l/RPMS" else echo "GBS Build failed!" ret=1 fi cd .. rm -rf iotjs_tizen_gbs cd iotjs exit $ret iotjs-1.0+715/config/tizen/iotjs_tizen.patch000066400000000000000000000137731371177304000210100ustar00rootroot00000000000000diff --git a/.gbs.conf b/.gbs.conf new file mode 100644 index 0000000..27429e2 --- /dev/null +++ b/.gbs.conf @@ -0,0 +1,4 @@ +[general] +upstream_branch = ${upstreamversion} +upstream_tag = ${upstreamversion} +packaging_dir = config/tizen/packaging diff --git a/LICENSE.BSD-3-Clause b/LICENSE.BSD-3-Clause new file mode 100644 index 0000000..d8fdf69 --- /dev/null +++ b/LICENSE.BSD-3-Clause @@ -0,0 +1,30 @@ +/* Copyright (c) 2013, Sony Mobile Communications AB + * Copyright (c) 2012, Google Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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. +*/ diff --git a/LICENSE.BSD-4-Clause b/LICENSE.BSD-4-Clause new file mode 100644 index 0000000..c48e617 --- /dev/null +++ b/LICENSE.BSD-4-Clause @@ -0,0 +1,28 @@ +Copyright (c) 1995, 1999 + Berkeley Software Design, Inc. All rights reserved. + +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. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by Berkeley Software Design, Inc. +4. Neither the name of the University 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 AUTHORS ``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 AUTHORS 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. diff --git a/LICENSE.MIT b/LICENSE.MIT new file mode 100644 index 0000000..bf37ab9 --- /dev/null +++ b/LICENSE.MIT @@ -0,0 +1,23 @@ +The MIT License (MIT) +Copyright (c) 2016 JerryScript Community +Copyright (c) 2015 +Copyright (c) 2015 Stefan Bellus +Copyright (c) 2005-2014 RoadNarrows LLC. + +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. diff --git a/config/mbedtls/config-for-iotjs.h b/config/mbedtls/config-for-iotjs.h index 6581586..745ebbf 100644 --- a/config/mbedtls/config-for-iotjs.h +++ b/config/mbedtls/config-for-iotjs.h @@ -57,7 +57,9 @@ * * Comment to disable the use of assembly code. */ +#ifndef TIZEN_ASAN_BUILD #define MBEDTLS_HAVE_ASM +#endif /** * \def MBEDTLS_HAVE_TIME diff --git a/config/tizen/packaging/iotjs.spec b/config/tizen/packaging/iotjs.spec index 5be21f0..d111e71 100644 --- a/config/tizen/packaging/iotjs.spec +++ b/config/tizen/packaging/iotjs.spec @@ -3,7 +3,7 @@ Version: 1.0.0 Release: 0 Summary: Platform for Internet of Things with JavaScript Group: Network & Connectivity -License: Apache-2.0 +License: Apache-2.0 and BSD-1.0 and BSD-3-Clause and MIT URL: https://www.iotjs.net/ Source: %{name}-%{version}.tar.gz Source1: %{name}.pc.in iotjs-1.0+715/config/tizen/packaging/000077500000000000000000000000001371177304000173375ustar00rootroot00000000000000iotjs-1.0+715/config/tizen/packaging/iotjs.manifest000066400000000000000000000001371371177304000222200ustar00rootroot00000000000000 iotjs-1.0+715/config/tizen/packaging/iotjs.pc.in000066400000000000000000000004471371177304000214250ustar00rootroot00000000000000prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: iotjs Description: Platform for Internet of Things with JavaScript Version: 1.0.0 Libs: -L${libdir} -liotjs -lcapi-system-peripheral-io -lpthread -lcurl -ldlog -lappcore-agent Cflags: -I${includedir}/iotjs iotjs-1.0+715/config/tizen/packaging/iotjs.spec000066400000000000000000000066611371177304000213540ustar00rootroot00000000000000Name: 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 ExclusiveArch: %arm %ix86 x86_64 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(capi-system-peripheral-io) BuildRequires: pkgconfig(dlog) BuildRequires: pkgconfig(glib-2.0) BuildRequires: pkgconfig(capi-appfw-app-control) BuildRequires: pkgconfig(bundle) #BuildRequires: pkgconfig(st_things_sdkapi) Requires(postun): /sbin/ldconfig Requires(post): /sbin/ldconfig %description Platform for Internet of Things with JavaScript # Initialize the variables %{!?build_mode: %define build_mode release} %{!?external_build_options: %define external_build_options %{nil}} %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 V=1 VERBOSE=1 ./tools/build.py \ --clean \ --buildtype=%{build_mode} \ --profile=test/profiles/tizen.profile \ --jerry-profile $PWD/test/profiles/tizen-jerry.profile \ --js-backtrace ON \ --target-arch=noarch \ --target-os=tizen \ %ifarch %{arm} --target-board=rpi3 \ %endif --external-lib=capi-system-peripheral-io \ --external-lib=capi-appfw-app-common \ --external-lib=dlog \ --external-lib=bundle \ --external-lib=capi-appfw-app-control \ --external-lib=appcore-agent \ --external-lib=pthread \ --external-lib=glib-2.0 \ --external-include-dir=/usr/include/dlog/ \ --external-include-dir=/usr/include/appcore-agent/ \ --external-include-dir=/usr/include/appfw/ \ --compile-flag="%(pkg-config --cflags glib-2.0)" \ --compile-flag=-D__TIZEN__ \ --compile-flag=-DENABLE_DEBUG_LOG \ --create-shared-lib \ --no-init-submodule \ --no-parallel-build \ %{?asan:--compile-flag=-DTIZEN_ASAN_BUILD} \ %{external_build_options} # --external-lib=sdkapi \ %install mkdir -p %{buildroot}%{_bindir} mkdir -p %{buildroot}%{_includedir}/iotjs mkdir -p %{buildroot}%{_libdir}/iotjs mkdir -p %{buildroot}%{_libdir}/pkgconfig cp ./build/noarch-tizen/%{build_mode}/bin/iotjs %{buildroot}%{_bindir}/ cp ./build/noarch-tizen/%{build_mode}/lib/*.so %{buildroot}%{_libdir}/ cp ./src/platform/tizen/iotjs_tizen_service_app.h %{buildroot}%{_includedir}/iotjs 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,-) %{_libdir}/libiotjs.so %license LICENSE %{_bindir}/* %files devel %manifest config/tizen/packaging/%{name}.manifest %defattr(-,root,root,-) %{_libdir}/libiotjs.so %{_libdir}/pkgconfig/%{name}.pc %{_includedir}/* iotjs-1.0+715/config/tizen/patch4tizenorg.sh000077500000000000000000000027231371177304000207230ustar00rootroot00000000000000#!/bin/bash # Copyright 2018-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. echo "******************************************************************" echo "* Tizen patch for obs build *" echo "******************************************************************" echo "" echo "This working folder will be copied to ../iotjs_tizen_org" cd .. echo copy from $OLDPWD to ../iotjs_tizen_org cp -ra $OLDPWD iotjs_tizen_org cd iotjs_tizen_org echo -e "\n(1) Now, cloning submodules. " git submodule init echo -e "\n(2) Update submodules... " git submodule update echo -e "\n(3) remove .git folders.. " 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(4) Patch for tizen.org... " patch -p1 < config/tizen/iotjs_tizen.patch cp -ra config/tizen/packaging . iotjs-1.0+715/config/tizen/release.sh000077500000000000000000000040071371177304000173730ustar00rootroot00000000000000#!/bin/bash ROOT=`pwd` # Copyright 2018-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. echo "******************************************************************" echo "* Tizen release script *" echo "******************************************************************" repo=$1 if [ "$repo" == "../iotjs_tizen" -o "$repo" == "../iotjs_tizen/" ]; then echo "Syncing with: tizen iotjs" else echo "Usage: $0 [ ../iotjs_tizen ]" exit 0 fi if [ ! -d ../iotjs_tizen ]; then # echo "cloning..." echo "Error: $repo not exist" exit 0 fi cd .. echo copy from $OLDPWD to ../iotjs_tizen_org cp -ra $OLDPWD iotjs_tizen_org cd iotjs_tizen_org echo -e "\n(1) Now, cloning submodules. " git submodule init echo -e "\n(2) Update submodules... " git submodule update echo -e "\n(3) Modify version... " hash=`git log | head -1 | cut -f2 -d' ' | cut -c 1-7` today=`date +%y%m%d` sed -i "s/\(IOTJS_VERSION \".*\"\)/\1 \"$today\_$hash\"/g" src/iotjs_def.h echo -e "\n(4) Patch for tizen.org... " patch -p1 < config/tizen/iotjs_tizen.patch cp -ra config/tizen/packaging . merge_filter="merge config/tizen/filter.txt" rsync -av --delete --delete-excluded --filter="$merge_filter" . $repo cd $repo git add -A echo "=======================================" echo git commit -m "IOTJS_Release_$today""_$hash" echo "=======================================" msg="IOTJS_Release_$today""_$hash" git commit -m "$msg" cd $ROOT rm -rf ../iotjs_tizen_org iotjs-1.0+715/config/tizen/sample.gbs.conf000066400000000000000000000045441371177304000203240ustar00rootroot00000000000000[general] #profile = profile.tizen40m3 #profile = profile.tizen50 #profile = profile.tizen50m1 #profile = profile.tizen50m2 profile = profile.tizen55m1 upstream_branch = ${upstreamversion} upstream_tag = ${upstreamversion} packaging_dir = config/tizen/packaging [profile.tizen55m1] obs = obs.spin repos = repo.tizen55m1_base, repo.tizen55m1_standard [repo.tizen55m1_base] url = http://download.tizen.org/releases/milestone/tizen/base/tizen-base_20190503.1/repos/standard/packages/ [repo.tizen55m1_standard] url = http://download.tizen.org/releases/milestone/tizen/unified/tizen-unified_20190523.1/repos/standard/packages/ [profile.tizen50m2] obs = obs.spin repos = repo.tizen50m2_base, repo.tizen50m2_standard [repo.tizen50m2_base] url = http://download.tizen.org/releases/milestone/tizen/base/tizen-base_20180928.1/repos/standard/packages/ [repo.tizen50m2_standard] url = http://download.tizen.org/releases/milestone/tizen/unified/tizen-unified_20181024.1/repos/standard/packages/ [profile.tizen50m1] obs = obs.spin repos = repo.tizen50m1_base, repo.tizen50m1_standard [repo.tizen50m1_base] url = http://download.tizen.org/releases/milestone/tizen/base/tizen-base_20180518.1/repos/standard/packages/ [repo.tizen50m1_standard] url = http://download.tizen.org/releases/milestone/tizen/unified/tizen-unified_20180528.1/repos/standard/packages/ # for platform developer [profile.tizen50] obs = obs.spin repos = repo.tizen_local, repo.tizen50_base, repo.tizen50_standard [repo.tizen50_base] url = http://download.tizen.org/snapshots/tizen/base/latest/repos/standard/packages/ [repo.tizen50_standard] url = http://download.tizen.org/snapshots/tizen/unified/latest/repos/standard/packages/ [profile.tizen40m3] obs = obs.spin repos = repo.tizen40m3_base, repo.tizen40m3_standard [repo.tizen40m3_base] url = http://download.tizen.org/releases/milestone/tizen/4.0-base/tizen-4.0-base_20180817.1/repos/arm/packages [repo.tizen40m3_standard] url = http://download.tizen.org/releases/milestone/tizen/4.0-unified/tizen-4.0-unified_20180821.6/repos/standard/packages/ [repo.tizen_local] url = ~/GBS-ROOT/local/repos/tizen50/ [obs.spin] url = http://168.219.209.58:81 [obs.tizen] url = https://api.tizen.org user = obs_viewer passwdx = QlpoOTFBWSZTWRP5nYMAAB6fgCAAeUA9mr+QBvzF4CAAVGAZDTRoDI0YBlCKeptQBoA0aGZIAottAkltEPOK7BAFXE9mTUzocPMzQRkPoPpNwEZx3rRQhxkXmGHS6wCjHskyVCP4u5IpwoSAn8zsGA== iotjs-1.0+715/config/tizen/template/000077500000000000000000000000001371177304000172265ustar00rootroot00000000000000iotjs-1.0+715/config/tizen/template/IoTjsApp/000077500000000000000000000000001371177304000207175ustar00rootroot00000000000000iotjs-1.0+715/config/tizen/template/IoTjsApp/description.xml000066400000000000000000000014111371177304000237610ustar00rootroot00000000000000 IoTjs App 1.0 iot-headless 4.0 org.tizen.nativecore.buildArtefactType.app False Template ic_s_service.png ic_m_service_n.png ic_m_service_s.png ic_l_service.png This is the empty template for developing IoT.js application. iotjs-1.0+715/config/tizen/template/IoTjsApp/ic_l_service.png000066400000000000000000000441211371177304000240550ustar00rootroot00000000000000‰PNG  IHDRªª=vÔ‚ pHYs  šœ9¤iTXtXML:com.adobe.xmp Adobe Photoshop CC 2015.5 (Windows) 2016-07-29T16:21:43+09:00 2016-08-17T11:54:45+09:00 2016-08-17T11:54:45+09:00 xmp.iid:1339a677-98a9-2344-8cd6-45de5232a861 xmp.did:19EA2832555D11E6B11FCA7794DD5196 xmp.iid:19EA282F555D11E6B11FCA7794DD5196 xmp.did:19EA2830555D11E6B11FCA7794DD5196 xmp.did:19EA2832555D11E6B11FCA7794DD5196 saved xmp.iid:1339a677-98a9-2344-8cd6-45de5232a861 2016-08-17T11:54:45+09:00 Adobe Photoshop CC 2015.5 (Windows) / image/png 3 1 720000/10000 720000/10000 2 65535 170 170 òƒH cHRMz%€ƒùÿ€éu0ê`:˜o’_ÅF'IDATxÚì}tTåÇ?ó–—I„†(h×€-È›šÈÊv÷° RZÚzüº²ØZíjkwÛlewO{Úݶj°Û]„TEÜŠRÖ?ôÈ)笠´ëYQ‰V¥ìÞBB&™™ÌÌÝ?æÞɽ„dfîL’ïçœ9'Ï3/Ižû™ßóþ\a O}i2¨f7•À šá.q hBÀYà(pØìNeâueýz½ßÅB(îó‰ò"ïðeæÃâ/ì~™ÂþxØt»ñ‡e[Tð—À·€¯¥raPã1kÀÀw€Nà5`½)¯1ØDõ_þ˜rÉz¿ÄKõX3®óqã(•#½Œ z(/öôC0à‘n×ûtD Ú#¡ƒ³aƒ£í ‹óÖÿÅxûx¬ï[J¥æã ð3`Ëø7$ÃmT/pð襪ö™£},ZÀ ¦]듃 hjóæ{Øx0Ê{§â—zÙGÀcf”gªšIQgkYöÌòbUò­…\?««=„øcG‚õïGXÓál÷Eí–›°¼uPÜoFTÆ•zùáœ"¸¹PWtðô¾?ÙæDgžÖuæhBÎD½ØHrh H¶-æ¹gZ®Þ0ä…¢Ôn뢫ÇáÕQànàŠšN]¼øo»¤sÆûygé5’tsÏ´ÞYz sÆ;ú镦++\ëLyêÛ|Àj ÖÊ»¦ÀÃÆE%,º! +%RüöÃîþmˆ Q‡cÏue±¬‰ê©o+þ¸3ÕƒªðÓpGªÑêÅ‹‹i:§vk;O:¼| XlÔ•E3.ª)éf`•·¼ª5ó4Ó)®ÌwÞìbõÞˆ=ëuà«W+«÷*%õKIúÏ_(–¤âªù÷ÛƒüËŸÛ³ëM·2Ö™úW’³¬š[Ì?ÝZ¤Òýâÿ´ˆUs².5ÝJ_TO}[-ðˆ•~tvß«‘¤b`|¯¦ˆGg;üyÄSßö`ZmTO}[°(¸ÿ¦Bž] ê^¤Ï·_ïb]sªÍæueMýÕSß6h&TõѸl„JXdŒš ìnI-8 Tueú[õ×[’¼Ð0¿D%+2JÃü½NVõ«ê©o›Mrî€M_)¥z¬ÆIEf©ëcÓWK”ï7Ý»²¨æÌÓZë¹9ãýÜ5I3N";Ü5)`ŸnõkM¯QïÅ\ªg-0"»M€ }¡ü,ÓÁË‹ê©oó+­ôÚyAnºNU¾È.7]çc­sòh¥éâe#ê×1Wæ+õòéZ%ÜáÓ WšÒq"ðW—ÕœÊJEÓÎÑ ¾p—9[iŸ^µGÔ/SFy´2_¸ÎßÜ\HyqÊÍ)¦“‰ú×ÖÌ”¤"w²ÚXæÕSßV,N;UmS‘–9Ý[lº™Š¨_>0ýZSËÕÓ¹aJyò¬“‘¦›)Q¿d=óMõôE®Gœ{î¾lõ6+÷K5 %rË—{ïnððĹ à@E‰—ËGª¤DΩXÛNK(uF@…¨±R5j›Šü Æ¹ªÆ L·RÓu”Èf8§îgx1לL*“¨"?˜<Êáâd/0ÁJMø”1ùAåH‡‹•^`”•U¤3IE~0&èpqŒ—äi|Œ(¨"?(/vDÔr§¨…UäAçYèA/¶sõKu¹ÈQ.½ØÎñ÷«/%ò©)þ¡øOíiSýBǰ¾°»ïÁçÇ qñ!QŸØöh¨•Á‹¨žOðʑ䑛ÇkGÚ7ŒeŒÆ–·l¸À¸R/ß¾©Ë"ŸmŽr¢3Á®e×P36óÅ¢3Áø†v^9åÛŠùlÙЈEC.¢þrO˜Xâ¢]åŒy«šà< š+ØNweç&wãJ½|sz±D²,Tõç!gº žkNFÓï~>{»h[CIÉJ0ARb»œêÊÚÝSÿûú÷£©/•DÍ#Ö4EèŽÜù¹3³xO³Ý 3¢ö_Të=gºYûûníãÎÏèŽ<µ7,Qó ûEy¨*»»h[̈Z:€ÍÖ{¬¨œ-VT9¾¼5Ox®9YÍͯ 0ïúìn§±¢á@n,l½'›àöëý̯ p¦Û`]sT¢æöŽÃ}3²¿9Ñê•ò³jq¿9"ñofS¢æ˜WŽDùð|‚¹Ÿñ³äÆì‹jI@àÎv¯ßÎâÉÌýŒß1d'Qsˆ5¸}×$w¶z[ÕvÉ:SÖ{Nw»â¬2y|O zQw,ÆžÖ8·Tøyx–;Gµ’ªàáY…Ì®ð³·5Îöc1‰š+ß•Œ *Ý™dëê1èê1ð{!0€°€/¹JÍú7X0!Y6Oì KÔ\°ïTœ­÷ðƒÙî“y*hjQjN´ºUÿþ–dÙlý¸‡}§âÕm~±;Œ<8³0-qúÕã·Ú§iü>7ýû67œYˆ<¹;,QÝäXG‚“=Ù:ï$x:¯8¸ÚNµGÕߌr¬#!QÝâ—{"Äp÷”&º¸Í;U¿5èÚEQ'Œôr÷k±JD¢ºÁùˆÁ³æí ¿[íî¡ÃéÌóçªê·°ÊêÙæç#†DÍ6k›"tF ÝÈÊšÎO"yþÞΔó³Ü¢f¬ŸE7茬iŠHÔlŽ<µ7YÈË«Ü?Â=yþ¾õl·ûmEkÁΚ½ƒk±Ê uÃ('C æ]`á÷ÏrÍDÕíA;_œ`~e€“¡/ˆJÔl0`Õ®d4]6-7'cg¢×ïæ|ÿ¥°îѰjW„Ä ªž8—úSº²üþcëÛ™'_¯»ýzk_¿øö-ÿQšw6üñŽpÞü/j£ !Q…DB¢ !Q…DB¢ !Q…DB¢ !Q…DB¢ ‰*„DB¢ ‰*„DB¢ ‰*„Dâ"ü*‚aí"ЍB(¢”|?MFU‰*„DU‰*„DU‰*$ªU‰*$ªU‰*†C~™_¾Þ¢FËQ…"êàC‘KU‰*„DU‰*$ªUˆ4ÑÌT?Ѹ¬"ªÃ7¢**¢ !Q…¨B¢ !Q…DB¢ !Q…DB¢ !Q…DÂ}墔|=TB(¢ ETbVd%ÀŸÇêjÉÞðލV¢³ÇP‰ˆ¼ Ëéb—è°R‰*òDÔŸ jT¢Šüà\8áHzs½OJT‘´„.¶x£Vêh{B%$ò‚>.õ°R8W ‰¼à°ÓÅÃ^`¿•ÚF¢Šü ù´ÃÅf/Ðh¥OJT‘4¶8\lôue'N†Rõ/rÌ¡sqZB©6êGF]Y‹5µÝÊÝòaJJä”>n‡Þ¹þ-Vî쪤DNùõ·ØEý/à¼Õ¡:pVÕ¿È ÏÆy¿·#Õnº™Õ¨+ /[Ͼx@QUä† N÷^6Ýt,ó{Ñúáé÷"*1‘žÙçpoƒõƒ]Ôÿ@r*õé}’U¸/éÙîÔÔéAÓI§¨F]™üÜJÿdGX%'\åÇNç~n:yQDØ„9¦z¢3Á¯5 \â…¢œèì;~cÞ!ªQW³GÕ‡Þèê;•%DÆi>gù¶.{Öc¦‹\.¢<4„z j DÆ©ÝÖE¨wE°¾ïk.Õ¨+‹ËÀŽã1^=¢Ù*‘^=ÒÃŽã©à™–›r¥ˆŠQWö.ðœ•^²¹“=­jˆÌ²»%Î’Íö¬u¦{\•¨&ߎô$ v«š"ÓU~ˆžÞõÑG€ºË½ö²¢ueÀ ÐØãÉ*2Ä[»ØÝ»”/ ,1럨¦¬MÀßZégöEXùV·JY¤ÅÊ·ºûÎ@ýéÕ”µX7ØæÉFMˆñdc˜Çv:üYm:FZ¢š<¼”j¼þ¾›Ÿ¾+YEÿøé»a¾ÿ{Gü’éÖñÆÕm‘öÔ·›VÞòªBÖÌ ê ˆ+²â.Ö49ªûׯueÑŒŠj“õeàkVÞì ? w©íÓÕ±»%Ní¶½ãðšÙyºê•OýÕ”Õg¶Yk­¼^ZT¢º2"Å«GzX¼¹“˜ó¸ˆ_+.5¨ŸQQm®~¤ìü³ñ~æ™q¢ëpæýÓqj·uñöqÇt}˜äØü³“Þ¯ÏLçɧ€¹ØNZyûxŒ¹›.h‡À0æÅQænºÐWÒ#À­–¤!ÝÓPw7“\Èb@rÑõ²-!>ÝÐκf-¾.¬kŽðé†v–m ÙÏ03L7ª÷Òùütªþ¾Y·™mשöÌòbÏ*âÞéüÉp=”8Ö‘àùýQVï ÛWæ[ƶßN«þLŠ É“«ï~LèûdÕh˦°pb€G©;Ø0€¦Ö8Ûõ°ñ@”¦S—ì} 5ÅËØ¿IDATxÚìMOgÇDZk#Þl/–€•Z8pŠU$ĹΠõÐôŽ„”¤¥éñàRÒ†DB|šCœzâMB*®8`©¸,Œm0/.àÎóX¸Ä6^³&^{þÒHf_‡ŸgŸgf½öØÖÖÖ(}Áö˜í[¶oؾd󰹨|uÎaû‡í/¶?Ù>°ý›¾‘ÏçûdGÇ-¸lÏÜnws}}=ÕÔÔÓé$‡ÃA6›­l‰&“I×ÅÅEk"‘hÇã}±Xl$îóª)¶I<£l9"õììõz[Y:ÄJC¦ÝÝ]Ò4mWÛl¦HÍÕÎö{ccãÓææfª­­%Ñÿu||L{{{‡ßðŸ?1ØËôõ2}ÛÒÒò´³³S€f¸€8W °ç‚:É~×ÑÑ!äò8¿|™ ꓆††ÛÛÛ…–A°Ìí9Gë“›P1Ëÿ†1´œgôb ÜÀÁzÒ¡¾àY¾¥®®N p?•èPÈC‘6‰ —â÷Œ£Õ ¨~$ö’‡ÞMàŽà©CE¥$º»ÇÇ€ú¨ººZˆ˜ Åñ ~]UU%DLâø ºív»1AŠ£[Ÿý%75GŠ£ó 0_U  ÔÊ-îëD333´µµõÙþÑ®®.*¨š¦Q0¤ñññ¼ï‚ÍÍÍÑÕÕõôô|²nccC/ ò:V2™¤±±1ݯ×[—ÿ º­xpp@ÙÊg®±ißPªƒóòS#‘­¯¯Soo¯¡ýÂá0e»‰åXoD8?ü€?–‡º¼¼L~¿ŸŒTm¸\sE*–c=¶3RíÀøci¨§§§´ººJýýý†ö‹Åbär¹²¾XŽõØÎˆàü_–…šЇ/Œ(W”ÞŒV#‚)°–„zyyI+++Ô××gxßbA…àü‚–ƒ¨»»›<OIA…?ð þY *&¥¥¥‚¢45ó j*Z MtŸêææ&555Q[[[Aû#-&Tø…•ág1„g©’™²º‹FGG-S§OLL˜>ì9JÑY¼)ÃÃ÷n7==}çóX¶L­4 T*PªH  T*¨µBT²Oú¢¨%rß@.SEU  T‘@­€”ÊÌ0J5õºw¨VÏAåò¨UdʼnÊÊc¯LTrù T*¨U ŠJ7¥²Òƒ¿–€Z ¹¨\þU ŠêýAMëKZ•&Å1¨Ñb~O³’¤8F5xvv&DLâÔÀÉɉ1AŠã߀:oôÇD™¥8ÎëP£Ñèˆ ø1Ç=~ùAŸýÙ^¡Ó‚¨p)~¯}>_"•§Njš::::*˜¢t2=ùÇï  u…ȸ·ŽÒÈÍŠêÃÃé¡d@à‡§èl¶2õçP(ôNÀæ¼À-Wí’à{ÞðÍöö¶>Vˆ2¡àNàu³ËÏmý¨^¢Ó‚ô£ºN›T?ªŠÎY£Ó0F¼çüÂöÜív?LuNKýºY™wNÓkùóósŠÇãzb|ž>vNû• 윖®T??]÷økPËËUèåwH×=þæ•%Ò7Ê©ÿ 0Þ4 ¤2 IEND®B`‚iotjs-1.0+715/config/tizen/template/IoTjsApp/ic_m_service_s.png000066400000000000000000000043431371177304000244020ustar00rootroot00000000000000‰PNG  IHDRUU8õ¨ZtEXtSoftwareAdobe ImageReadyqÉe<(iTXtXML:com.adobe.xmp 7¤QIDATxÚì[leÇÏN÷f%l· Q‘KÚÄkŒQŒ‰ -‰úBLñÑÄågBâ“‹¥õòf|ª†ôí*˜5&X‰¦lÁ*1¶Bw¡4{õüggÖ²·Ù¡ëÎîù''ùvfgæì¯ç›ï|3Ó9zãU![?ÛN¶ÇÙ6²u°¨y•d‹±Í°cûœm’-­~)w$|Û†Þ ;¸!¶}lk¨µ„€é2íI¶ƒlÿ°±0U9¨/›c§ôì:/õ¯÷Ñ3ziCH£Ž€‡‚^OÓMdrKæèR\§¯þÈÐäå4}9›¹—We{Í ¶ñbÛzŠtÿ6¶“l{ñá…M>z,H;òR«ëÌï:1• O¢…3À»lø-@?fۣϵÓþG$ºUc?$ið‹%ëãÛ€ V[ö}t÷Ý]wkôÓ+«h ø€“€o«ëU¨{ØÑøì¥U´yM›Ð+#ð™dNgÏñ…=Ë¡b”AãäŽvÚºV€V£G˜x™a°*TŒdk1( öJ—·#ð7ð39PýfjŒò"ûR¸íãhõjû휇JÚT›À üÌ RŸ•úÖû„Ž)üúµ­m÷K”:ÑÓøõjZ=2â;Qw¸À¯PCh…!ã@ ¿5úS@Õ‘~~MpÜy T*P[VuKNwZ¤ÉKéÿí‡îÚà£Oÿ»ªä~¨?Ïg)Â@õ#aª6q:»D¿]Óé‰ûnOK¾û+Cs^=¼½½ª}åØÚŽ/~Ôã’f]ºÿ›ç4¶³ìdÂјNá`ñ-:ƒ]äõÕ {ÁñáGSœSg¯ë4þkŠ^Ýlï’â  –˜`ùŒ ¨Ž?à롎œOÒ±mw‘ßF¯Cw‰—ŽT,Çúœ ?p|ø\ ·xß¿¤A›÷º®ÜÐi‰·„wXŽõøžÁø¿\ õ½ó@Wùí]W(w>U£5jó?àür%ÔT–»þT’önµ{&Ëò`Tj§5k{ßð~¥².„úá/Iz~“Ö­Öj€º2‘ Áøÿ\UçSÖð÷µEiaä¯*RkÉá×[쟞sÔÓÑ4u‡5êíª-ѾXE÷רý!øÕÃþŽ®Ì ý¯bÖ¼Sž½¸E+ñ»½è,œ;úTåÛåǾM8>Žk§©­&*Pª@ T*PEU ¶ˆöùILAjƒ\7î/çT‘@¨U$P[ ¥º“·05õª;T·ç Òýª@¹q ró¹W*éþU Šª@¨¢ÆM©Üôà¯+ ¶B.*Ý_  T‘@­ÔɬÀp"…_ PãhÅWø?‹›] ¿8 N£5½ ¡êD ¿i@Bëë?3Bƾ¹RàwP#hE.§…Œ)o2ŠXP¯žÍï±Ù¸k|­ÑKP@d_ ·wxŠž²òT¼ß•Fëðâ–f )˜*æMŽ…äÅUPp…œY¢ s’ T#pR*Sä(-ŸQ}Dù 6ÔjÑxÛ˜¨´Àœ¬€e ã¥¦©‡Ø&þ¾©Ó–®¡-*ÞåÁœ(_;åP¹¹?Âs€òÕkŒÐ~qbÑÙZ^àJ—§JU~T¡ ­ ÒÂ-õ¨6†4 5[oEs›ðŠ¥…„n¼© õ¨Ç+Á5gFçx± òž åèP ä0Û~¶{$Véª9î ›ƒ{Måè°!*…½Nù(´`ÕøÃÞš¹âò$Üh³jüELKUÚð_ü Å‚4êéîIEND®B`‚iotjs-1.0+715/config/tizen/template/IoTjsApp/ic_s_service.png000066400000000000000000000041761371177304000240720ustar00rootroot00000000000000‰PNG  IHDRAAŽ÷ÉEtEXtSoftwareAdobe ImageReadyqÉe<(iTXtXML:com.adobe.xmp Ãaq.ìIDATxÚì\KlW½v&¶ Æ@’EùBü]@„$›vƒJËQ©> Ÿ;$„Ä °¨ªÒ]@(+Äü$D»)Q*Q)"|Z„H±#ÇsÏø3 Ž=ŽM=ö¼#]éyF3wÎyï¾ÏøÝqщ·dÕl­lÍl_±-b›Éæ%û@e ±õ³ýÉv­‡m4ÛEÉÃRrÜD²íe«#{Ò l=Û~¶7lçØ:„@‘M„âbÜ”6ÏW¨ua5mš§Ð—~7ÍôºÈ§¸l£@4ž¤š¤§aîü§žg£tûE|Ÿ:ʶ[TfW¦k]¡Ší,Ûüøfq5\룦 •n>SGo”®>IGĶv¶D¶p€—Ù¶áGçÖÚ·ÆKå T\Ó‚Z:÷@¥¶ïIT,Zö÷f!Ü®CóßÖ0ÝMý8£¬0<À¼DŸ6Ÿ7‹ð[ ×¾«¥uUTIŸæeè"øŽ£ÀÎ6ÕÐêúÊÀÀ*æ~gï´è9ëÑ ¶5z©’~à ¾‚·.‚GÌôQÀ 0ñÜë:9ì-˜m™¯”å08ÕQ|ŰÅZV““`âÛ Qúú ÅQ"lœ›æÛ–¢´tV•£DXHó]ü(ù½.G‰`âëWÄè@Þ"4„æËºñ|ô³hæxn¯-lÉ9Æ×S´ŽàÁ@‚†>hú‚Ä –ý2¢÷Òs¦¥jä͇¤¾àyüÓŒœ×6þ6¢û[S¤I»X"t܋ҋk -IÔNPÀ7‚(ãÎåüÀ_±P^½Ó¨ëŸíZnM„—MQeê†PÆ1œËø?øµ§î©tdý4òXlý!:bù\€øƒ_[ˆ‰%éç‡*µç±æxJÐ,ß§"àÎYüÁ/ü—\„_ÿŽÑÎåýu›Uè-!ƒz¿²ÖÄá~ῤ"ÄùyO÷r‡¸:¿•g8‹aëq¿x}×J(Bw_ŒÖ6(´lv~CU¡}Bz˜e¿ëØ?ž£àE«TVÇ÷qŸ¶Í °çWJåüè†Ìï.ŽýÍûž…V†›$¤R)‚AŠ E"dFÉ^1cRäh¦2Ë”á E"”oŸPȪ®ýÅgÁnŸ ;†ƒ[‰ R)‚AŠ E˜tˆÄX51µ-;vú*¨c~Ç B˜­.¬&©¾&¿Í[å60|"¡¥¾á„£BÀÄ·"ô¢t÷¿¸£Døýešï}ˆD)ølÔQ"ô #ifdef LOG_TAG #undef LOG_TAG #endif #define LOG_TAG "$(appName)" #endif /* __$(appName)_H__ */ iotjs-1.0+715/config/tizen/template/IoTjsApp/project/project_def.prop000066400000000000000000000002311371177304000255470ustar00rootroot00000000000000APPNAME = $(appName) type = app profile = $(platform) USER_SRCS = src/$(appName).c USER_DEFS = USER_INC_DIRS = inc USER_OBJS = USER_LIBS = USER_EDCS = iotjs-1.0+715/config/tizen/template/IoTjsApp/project/res/000077500000000000000000000000001371177304000231565ustar00rootroot00000000000000iotjs-1.0+715/config/tizen/template/IoTjsApp/project/res/index.js000066400000000000000000000000361371177304000246220ustar00rootroot00000000000000console.log('Hello IoT.js'); iotjs-1.0+715/config/tizen/template/IoTjsApp/project/src/000077500000000000000000000000001371177304000231545ustar00rootroot00000000000000iotjs-1.0+715/config/tizen/template/IoTjsApp/project/src/main.c000066400000000000000000000034761371177304000242560ustar00rootroot00000000000000#include #include #include #include "$(appName).h" bool service_app_create(void *data) { // Todo: add your code here. return true; } void service_app_terminate(void *data) { // Todo: add your code here. return; } void service_app_control(app_control_h app_control, void *data) { // Todo: add your code here. // Emit 'appControl' event to the JavaScript side. iotjs_tizen_app_control_cb(app_control, data); return; } static void service_app_lang_changed(app_event_info_h event_info, void *user_data) { /*APP_EVENT_LANGUAGE_CHANGED*/ return; } static void service_app_region_changed(app_event_info_h event_info, void *user_data) { /*APP_EVENT_REGION_FORMAT_CHANGED*/ } static void service_app_low_battery(app_event_info_h event_info, void *user_data) { /*APP_EVENT_LOW_BATTERY*/ } static void service_app_low_memory(app_event_info_h event_info, void *user_data) { /*APP_EVENT_LOW_MEMORY*/ } int main(int argc, char* argv[]) { char ad[50] = {0,}; service_app_lifecycle_callback_s event_callback; app_event_handler_h handlers[5] = {NULL, }; event_callback.create = service_app_create; event_callback.terminate = service_app_terminate; event_callback.app_control = service_app_control; service_app_add_event_handler(&handlers[APP_EVENT_LOW_BATTERY], APP_EVENT_LOW_BATTERY, service_app_low_battery, &ad); service_app_add_event_handler(&handlers[APP_EVENT_LOW_MEMORY], APP_EVENT_LOW_MEMORY, service_app_low_memory, &ad); service_app_add_event_handler(&handlers[APP_EVENT_LANGUAGE_CHANGED], APP_EVENT_LANGUAGE_CHANGED, service_app_lang_changed, &ad); service_app_add_event_handler(&handlers[APP_EVENT_REGION_FORMAT_CHANGED], APP_EVENT_REGION_FORMAT_CHANGED, service_app_region_changed, &ad); return iotjs_service_app_start(argc, argv, "index.js", &event_callback, ad); } iotjs-1.0+715/config/tizen/template/IoTjsApp/project/tizen-manifest.xml000066400000000000000000000015541371177304000260510ustar00rootroot00000000000000 $(appName).png http://tizen.org/privilege/network.get http://tizen.org/privilege/network.set http://tizen.org/privilege/internet http://tizen.org/privilege/alarm.set http://tizen.org/privilege/network.profile http://tizen.org/privilege/peripheralio iotjs-1.0+715/config/tizen/template/IoTjsApp/sample.xml000066400000000000000000000034631371177304000227300ustar00rootroot00000000000000 iotjs-1.0+715/config/tizenrt/000077500000000000000000000000001371177304000157615ustar00rootroot00000000000000iotjs-1.0+715/config/tizenrt/Kconfig.runtime000066400000000000000000000012171371177304000207470ustar00rootroot00000000000000# # For a description of the syntax of this configuration file, # see kconfig-language at https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt # config ENABLE_IOTJS bool "IoT.js" default n select SPI_EXCHANGE select IOTBUS select IOTBUS_GPIO select IOTBUS_I2C select IOTBUS_PWM select IOTBUS_SPI select IOTBUS_UART ---help--- Enable IoT.js framework if ENABLE_IOTJS config IOTJS_PRIORITY int "IoT.js task priority" default 100 config IOTJS_STACKSIZE int "IoT.js stack size" default 32768 config IOTJS_JERRY_HEAP int "Jerryscript Heaplimit" default 128 endif #ENABLE_IOTJS iotjs-1.0+715/config/tizenrt/Makefile000066400000000000000000000035541371177304000174300ustar00rootroot00000000000000########################################################################### # # Copyright 2018 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. # ########################################################################### -include $(TOPDIR)/.config -include $(TOPDIR)/Make.defs IOTJS_ROOT_DIR ?= $(TOPDIR)/$(EXTDIR)/iotjs IOTJS_BUILD_OPTION ?= ifeq ($(CONFIG_DEBUG),y) IOTJS_BUILDTYPE = debug else IOTJS_BUILDTYPE = release endif IOTJS_OS ?= tizenrt IOTJS_ARCH ?= arm IOTJS_BUILDCONFIG ?= ${IOTJS_ARCH}-${IOTJS_OS} IOTJS_LIB_DIR ?= $(IOTJS_ROOT_DIR)/build/${IOTJS_BUILDCONFIG}/$(IOTJS_BUILDTYPE)/lib IOTJS_ROOT_DIR ?= . IOTJS_PROFILE_FILE ?= ${IOTJS_ROOT_DIR}/test/profiles/tizenrt.profile all: build .PHONY: depend clean distclean ${TOPDIR}/include/sys/uio.h: @mkdir -p ${@D} @echo "#include " > $@ build: $(IOTJS_ROOT_DIR)/tools/build.py ${IOTJS_PROFILE_FILE} ${TOPDIR}/include/sys/uio.h $(Q) python $< \ --target-arch=$(CONFIG_ARCH) \ --target-os=${IOTJS_OS} \ --sysroot=$(TOPDIR) --target-board=$(CONFIG_ARCH_BOARD) --jerry-heaplimit=$(CONFIG_IOTJS_JERRY_HEAP) \ --buildtype=$(IOTJS_BUILDTYPE) --no-init-submodule $(IOTJS_BUILD_OPTION) \ --profile ${IOTJS_PROFILE_FILE} $(Q) cp $(IOTJS_LIB_DIR)/*.a $(IOTJS_ROOT_DIR) depend: clean: $(Q) $(call DELDIR, $(IOTJS_ROOT_DIR)/build) $(Q) $(call DELFILE, $(IOTJS_ROOT_DIR)/*.a) distclean: iotjs-1.0+715/config/tizenrt/artik05x/000077500000000000000000000000001371177304000174305ustar00rootroot00000000000000iotjs-1.0+715/config/tizenrt/artik05x/configs/000077500000000000000000000000001371177304000210605ustar00rootroot00000000000000iotjs-1.0+715/config/tizenrt/artik05x/configs/debug/000077500000000000000000000000001371177304000221465ustar00rootroot00000000000000iotjs-1.0+715/config/tizenrt/artik05x/configs/debug/defconfig000066400000000000000000000741611371177304000240260ustar00rootroot00000000000000# # 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_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 CONFIG_ARCH_HAVE_CUSTOMOPT=y # CONFIG_DEBUG_NOOPT is not set # CONFIG_DEBUG_CUSTOMOPT is not set CONFIG_DEBUG_FULLOPT=y # # Hardware Configuration # # # Chip Selection # CONFIG_ARCH_ARM=y CONFIG_ARCH="arm" # CONFIG_ARCH_CHIP_LM is not set CONFIG_ARCH_CHIP_S5J=y # CONFIG_ARCH_CHIP_BCM4390X is not set CONFIG_ARCH_CHIP="s5j" # # ARM Options # # CONFIG_ARCH_CORTEXM3 is not set # CONFIG_ARCH_CORTEXM4 is not set CONFIG_ARCH_CORTEXR4=y CONFIG_ARCH_FAMILY="armv7-r" # 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 # # S5J Configuration Options # CONFIG_ARCH_CHIP_S5JT200=y CONFIG_S5J_S5JT200=y # # S5J Peripheral Support # CONFIG_S5J_HAVE_ADC=y CONFIG_S5J_HAVE_DMA=y CONFIG_S5J_HAVE_I2C=y CONFIG_S5J_HAVE_I2S=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_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_DMA is not set CONFIG_S5J_I2C=y # CONFIG_S5J_I2S is not set CONFIG_S5J_MCT=y CONFIG_S5J_TIMER0=y # 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_UART3=y 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 is not set CONFIG_S5J_SPI=y # CONFIG_S5J_WATCHDOG is not set CONFIG_S5J_SFLASH=y # CONFIG_S5J_SENSOR_PPD42NS 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_DEBUG_DISPLAY_SYMBOL is not set # 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=968704 # CONFIG_DDR is not set # CONFIG_ARCH_HAVE_SDRAM is not set # # Board Selection # CONFIG_ARCH_BOARD_ARTIK053=y # CONFIG_ARCH_BOARD_ARTIK053S is not set # CONFIG_ARCH_BOARD_ARTIK055S is not set # CONFIG_ARCH_BOARD_SIDK_S5JT200 is not set CONFIG_ARCH_BOARD_ARTIK05X_FAMILY=y CONFIG_ARCH_BOARD="artik05x" # # Common Board Options # # CONFIG_BOARD_CRASHDUMP is not set # CONFIG_BOARD_ASSERT_AUTORESET is not set CONFIG_LIB_BOARDCTL=y CONFIG_BOARDCTL_RESET=y # CONFIG_BOARDCTL_UNIQUEID is not set # CONFIG_BOARD_FOTA_SUPPORT is not set # # Board-Specific Options # CONFIG_ARTIK05X_BOOT_FAILURE_DETECTION=y CONFIG_ARTIK05X_BOOT_COUNTS_ADDR=0x80090810 CONFIG_ARTIK05X_FLASH_CAPACITY=8388608 CONFIG_ARTIK05X_FLASH_PAGE_SIZE=4096 CONFIG_ARTIK05X_FLASH_PART=y CONFIG_ARTIK05X_FLASH_MINOR=0 CONFIG_ARTIK05X_FLASH_PART_LIST="16,48,192,32,512,2400,1536,1536,1000,400,8,512," CONFIG_ARTIK05X_FLASH_PART_TYPE="none,ftl,none,none,none,none,none,ftl,smartfs,romfs,config,none," CONFIG_ARTIK05X_FLASH_PART_NAME="bl1,sssro,bl2,sssfw,wlanfw,os,factory,ota,user,rom,nvram,sssrw," CONFIG_ARTIK05X_AUTOMOUNT=y CONFIG_ARTIK05X_AUTOMOUNT_USERFS=y CONFIG_ARTIK05X_AUTOMOUNT_USERFS_DEVNAME="/dev/smart0p8" CONFIG_ARTIK05X_AUTOMOUNT_USERFS_MOUNTPOINT="/mnt" # CONFIG_ARTIK05X_AUTOMOUNT_SSSRW is not set CONFIG_ARTIK05X_AUTOMOUNT_ROMFS=y CONFIG_ARTIK05X_AUTOMOUNT_ROMFS_DEVNAME="/dev/mtdblock9" CONFIG_ARTIK05X_AUTOMOUNT_ROMFS_MOUNTPOINT="/rom" # # Kernel 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_NPTHREAD_DESTRUCTOR_ITERATIONS=4 # CONFIG_PTHREAD_CLEANUP is not set # CONFIG_CANCELLATION_POINTS is not set # # Performance Monitoring # # CONFIG_SCHED_CPULOAD 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 # # 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_MPU_STACKGAURD is not set CONFIG_PTHREAD_STACK_MIN=256 CONFIG_PTHREAD_STACK_DEFAULT=2048 # # Device Drivers # # CONFIG_DISABLE_POLL is not set CONFIG_DEV_NULL=y CONFIG_DEV_ZERO=y # 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=y # CONFIG_SPI_CMDDATA is not set # CONFIG_SPI_BITBANG is not set CONFIG_GPIO=y # CONFIG_I2S is not set # CONFIG_AUDIO_DEVICES is not set CONFIG_BCH=y 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_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_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_SENSOR 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 CONFIG_NET_IPv6=y CONFIG_NET_IPv6_NUM_ADDRESSES=3 # CONFIG_NET_IPv6_FORWARD is not set # CONFIG_NET_IPv6_FRAG is not set CONFIG_NET_IPv6_REASS=y CONFIG_NET_IPV6_REASS_MAXAGE=60 CONFIG_NET_IPv6_SEND_ROUTER_SOLICIT=y CONFIG_NET_IPv6_AUTOCONFIG=y CONFIG_NET_IPv6_DUP_DETECT_ATTEMPTS=1 # CONFIG_NET_IPv6_PMTU_FOR_MULTICAST is not set # # Socket support # CONFIG_NET_SOCKET=y CONFIG_NSOCKET_DESCRIPTORS=20 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_IPv6_ND=y CONFIG_NET_IPv6_ND_QUEUEING=y CONFIG_NET_IPv6_ND_QUEUE=20 CONFIG_NET_IPv6_ND_NUM_NEIGHBORS=10 CONFIG_NET_IPv6_ND_NUM_DESTINATIONS=10 CONFIG_NET_IPv6_ND_NUM_PREFIXES=5 CONFIG_NET_IPv6_ND_NUM_ROUTERS=3 CONFIG_NET_IPv6_ND_MAX_MULTICAST_SOLICIT=3 CONFIG_NET_IPv6_ND_MAX_UNICAST_SOLICIT=3 CONFIG_NET_IPv6_ND_MAX_SOLICIT_INTERVAL=4000 CONFIG_NET_IPv6_ND_REACHABLE_TIME=30000 CONFIG_NET_IPv6_ND_RETRANS_TIMER=1000 CONFIG_NET_IPv6_ND_DELAY_FIRST_PROBE_TIME=5000 CONFIG_NET_IPv6_ND_ALLOW_RA_UPDATES=y CONFIG_NET_IPv6_ND_TCP_REACHABILITY_HINTS=y CONFIG_NET_IPv6_ND_RDNSS_MAX_DNS_SERVERS=0 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_THRESHOLD=536 CONFIG_NET_ICMP=y CONFIG_NET_ICMP_TTL=255 # CONFIG_NET_BROADCAST_PING is not set # CONFIG_NET_MULTICAST_PING4 is not set CONFIG_NET_IPv6_ICMP=y CONFIG_NET_IPv6_ICMP_DATASIZE=8 CONFIG_NET_IPv6_ICMP_HL=255 # CONFIG_NET_MULTICAST_PING6 is not set CONFIG_NET_LWIP_IGMP=y CONFIG_NET_LWIP_MEMP_NUM_IGMP_GROUP=8 CONFIG_NET_IPv6_MLD=y CONFIG_NET_IPv6_MLD_GROUP=4 # CONFIG_NET_IPv6_DHCP is not set # # 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_ASSERT is not set # CONFIG_NET_LWIP_ERROR is not set # 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_IPv6_STATS is not set # CONFIG_NET_IPv6_ICMP_STATS is not set # CONFIG_NET_IPv6_MLD_STATS is not set # CONFIG_NET_IPv6_ND_STATS is not set # 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 # # Interface Name # CONFIG_NET_ETH_IFNAME="en" CONFIG_NET_LOOP_IFNAME="lo" CONFIG_NET_STA_IFNAME="wl" CONFIG_NET_SOFTAP_IFNAME="sa" CONFIG_NET_LWIP_NETDB=y CONFIG_NET_DNS_TABLE_SIZE=4 CONFIG_NET_DNS_MAX_NAME_LENGTH=256 CONFIG_NET_DNS_MAX_SERVERS=2 # CONFIG_NET_DNS_DOES_NAME_CHECK is not set CONFIG_NET_DNS_SECURE=0 # CONFIG_NET_DNS_LOCAL_HOSTLIST is not set # # Driver buffer configuration # CONFIG_NET_MULTIBUFFER=y CONFIG_NET_ETH_MTU=590 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 # # Protocols # 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_XMLRPC is not set # CONFIG_NETUTILS_NTPCLIENT is not set # CONFIG_NETUTILS_WEBSERVER is not set # CONFIG_NETUTILS_FTPC is not set # CONFIG_NETUTILS_MDNS is not set # CONFIG_NETUTILS_FTPD is not set CONFIG_NETUTILS_DHCPC=y # CONFIG_NETUTILS_WEBSOCKET is not set # CONFIG_NETUTILS_LIBCOAP is not set # CONFIG_NETUTILS_TFTPC is not set # CONFIG_NETUTILS_TELNETD is not set # CONFIG_NETUTILS_SMTP is not set # CONFIG_NETUTILS_MQTT is not set CONFIG_NET_SECURITY_TLS=y CONFIG_TLS_MPI_MAX_SIZE=512 # # Wireless # CONFIG_WIFI_MANAGER=y CONFIG_SELECT_WPA_SUPPLICANT=y # CONFIG_SELECT_PROPIETARY_SUPPLICANT is not set # CONFIG_SELECT_NO_DRIVER is not set CONFIG_SELECT_SCSC_WLAN=y # CONFIG_SELECT_PROPIETARY_WLAN 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 # # 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 CONFIG_DRIVER_T20=y # CONFIG_ENABLE_EAP_FOR_SUPPLICANT is not set CONFIG_WIFIMGR_SOFTAP_IFNAME="wl1" CONFIG_WIFIMGR_STA_IFNAME="wl1" # CONFIG_WIFIMGR_DISABLE_AUTO_GET_IP is not set # CONFIG_DISABLE_EXTERNAL_AUTOCONNECT is not set # # Network utilities # CONFIG_NETUTILS_NETLIB=y CONFIG_NET_NETMON=y # # Audio Support # # CONFIG_AUDIO is not set # # Media Support # # # File Systems # # CONFIG_DISABLE_MOUNTPOINT 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 # CONFIG_FS_AUTOMOUNT_PROCFS is not set # # 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 # CONFIG_FS_TMPFS is not set # # 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=512 # 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 # CONFIG_MTD_W25 is not set # # System Logging # # CONFIG_SYSLOG is not set # CONFIG_SYSLOG_TIMESTAMP is not set # # Database # # CONFIG_ARASTORAGE is not set # # Memory Management # # CONFIG_REALLOC_DISABLE_NEIGHBOR_EXTENSION is not set # CONFIG_MM_SMALL is not set CONFIG_MM_REGIONS=1 # 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 # # Debug Options # CONFIG_DEBUG=y CONFIG_DEBUG_ERROR=y # CONFIG_DEBUG_WARN is not set CONFIG_DEBUG_VERBOSE=y # # Subsystem Debug Options # # CONFIG_DEBUG_LIB is not set # CONFIG_DEBUG_FS is not set # CONFIG_DEBUG_IOTBUS 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_TASH 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_INFO 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_INFO 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_INFO 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_I2S is not set # CONFIG_DEBUG_PWM is not set # CONFIG_DEBUG_RTC is not set # CONFIG_DEBUG_SPI is not set # CONFIG_DEBUG_WATCHDOG is not set # # System Debug Options # # CONFIG_DEBUG_SYSTEM 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 # # 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 # # Built-in Libraries # # # 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_FLOATPRECISION=6 CONFIG_LIBC_SCANSET=y # CONFIG_NOPRINTF_LONGLONG_TO_ASCII is not set CONFIG_LIBC_IOCTL_VARIADIC=y # CONFIG_LIBC_WCHAR is not set # CONFIG_LIBC_LOCALE is not set 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_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_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 # # Non-standard Library Support # # # Basic CXX Support # # CONFIG_C99_BOOL8 is not set # CONFIG_HAVE_CXX is not set # # External Libraries # # CONFIG_AVS_DEVICE_SDK is not set # CONFIG_AWS_SDK is not set # CONFIG_NETUTILS_CODECS is not set # # CURL Options # # CONFIG_ENABLE_CURL is not set # CONFIG_ERROR_REPORT is not set # CONFIG_ENABLE_IOTIVITY is not set CONFIG_NETUTILS_JSON=y # CONFIG_LIBTUV is not set # CONFIG_LWM2M_WAKAAMA is not set # CONFIG_STRESS_TOOL is not set # CONFIG_VOICE_SOFTWARE_EPD is not set # # Application Configuration # # # Application entry point list # # CONFIG_ENTRY_MANUAL is not set # CONFIG_ENTRY_HELLO is not set CONFIG_ENTRY_IOTJS_STARTUP=y CONFIG_USER_ENTRYPOINT="iotjs_startup_main" CONFIG_BUILTIN_APPS=y # # Examples # # CONFIG_EXAMPLES_AVS_TEST is not set # CONFIG_EXAMPLES_AWS is not set # CONFIG_EXAMPLES_CURLTEST 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_EVENTLOOP is not set # CONFIG_EXAMPLES_FOTA_SAMPLE is not set # CONFIG_FILESYSTEM_HELPER_ENABLE is not set CONFIG_EXAMPLES_HELLO=y # CONFIG_EXAMPLES_HELLOXX is not set # CONFIG_EXAMPLES_IOTBUS_TEST is not set CONFIG_EXAMPLES_IOTJS_STARTUP=y CONFIG_EXAMPLES_IOTJS_STARTUP_JS_FILE="/rom/example/index.js" # CONFIG_EXAMPLES_IOTJS_STARTUP_WIFI is not set # CONFIG_EXAMPLES_KERNEL_SAMPLE is not set # CONFIG_EXAMPLES_LIBTUV 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_SETJMP_TEST 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_SPEECH_DETECTOR_TEST is not set # CONFIG_EXAMPLES_ST_THINGS is not set # CONFIG_EXAMPLES_TESTCASE is not set # CONFIG_EXAMPLES_TLS_BENCHMARK 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_WIFIMANAGER_TEST is not set # # Platform-specific Support # # CONFIG_PLATFORM_CONFIGDATA is not set # # Shell # CONFIG_TASH=y CONFIG_TASH_MAX_COMMANDS=132 # CONFIG_TASH_USLEEP is not set CONFIG_TASH_COMMAND_INTERFACE=y CONFIG_TASH_CMDTASK_STACKSIZE=4096 CONFIG_TASH_CMDTASK_PRIORITY=100 # CONFIG_TASH_SCRIPT is not set # # System Libraries and Add-Ons # # CONFIG_SYSTEM_CLE is not set # CONFIG_SYSTEM_CUTERM is not set # CONFIG_SYSTEM_FLASH_ERASEALL is not set # CONFIG_SYSTEM_FOTA_HAL is not set # CONFIG_SYSTEM_I2CTOOL is not set # CONFIG_SYSTEM_INIFILE is not set CONFIG_SYSTEM_PREAPP_INIT=y CONFIG_SYSTEM_PREAPP_STACKSIZE=2048 # CONFIG_SYSTEM_INSTALL is not set CONFIG_SYSTEM_IPERF=y # CONFIG_SYSTEM_NETDB is not set CONFIG_SYSTEM_RAMTEST=y CONFIG_SYSTEM_RAMTEST_PRIORITY=100 CONFIG_SYSTEM_RAMTEST_STACKSIZE=1024 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_NET_PING_CMD=y CONFIG_NET_PING_CMD_ICOUNT=5 CONFIG_ENABLE_DATE_CMD=y CONFIG_ENABLE_ENV_GET_CMD=y CONFIG_ENABLE_ENV_SET_CMD=y CONFIG_ENABLE_ENV_UNSET_CMD=y CONFIG_ENABLE_FREE_CMD=y CONFIG_ENABLE_HEAPINFO_CMD=y # CONFIG_HEAPINFO_USER_GROUP is not set # CONFIG_ENABLE_IRQINFO_CMD is not set CONFIG_ENABLE_KILL_CMD=y CONFIG_ENABLE_KILLALL_CMD=y CONFIG_ENABLE_PS_CMD=y CONFIG_ENABLE_STACKMONITOR_CMD=y CONFIG_STACKMONITOR_PRIORITY=100 CONFIG_STACKMONITOR_INTERVAL=5 CONFIG_ENABLE_UPTIME_CMD=y # CONFIG_SYSTEM_VI is not set # # Runtime Environment # CONFIG_ENABLE_IOTJS=y CONFIG_IOTJS_PRIORITY=100 CONFIG_IOTJS_STACKSIZE=32768 CONFIG_IOTJS_JERRY_HEAP=128 # # Device Management # # CONFIG_DM is not set # # Task manager # # CONFIG_TASK_MANAGER is not set # # Event Loop Framework # # CONFIG_EVENTLOOP is not set # # Things Management # # CONFIG_ST_THINGS is not set # # IoTBus Framework # CONFIG_IOTBUS=y CONFIG_IOTBUS_GPIO=y CONFIG_IOTBUS_I2C=y CONFIG_IOTBUS_PWM=y CONFIG_IOTBUS_SPI=y CONFIG_IOTBUS_UART=y iotjs-1.0+715/config/tizenrt/artik05x/configs/release/000077500000000000000000000000001371177304000225005ustar00rootroot00000000000000iotjs-1.0+715/config/tizenrt/artik05x/configs/release/defconfig000066400000000000000000000743521371177304000243620ustar00rootroot00000000000000# # 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_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 CONFIG_ARCH_HAVE_CUSTOMOPT=y # CONFIG_DEBUG_NOOPT is not set # CONFIG_DEBUG_CUSTOMOPT is not set # CONFIG_DEBUG_FULLOPT is not set # # Hardware Configuration # # # Chip Selection # CONFIG_ARCH_ARM=y CONFIG_ARCH="arm" # CONFIG_ARCH_CHIP_LM is not set CONFIG_ARCH_CHIP_S5J=y # CONFIG_ARCH_CHIP_BCM4390X is not set CONFIG_ARCH_CHIP="s5j" # # ARM Options # # CONFIG_ARCH_CORTEXM3 is not set # CONFIG_ARCH_CORTEXM4 is not set CONFIG_ARCH_CORTEXR4=y CONFIG_ARCH_FAMILY="armv7-r" # 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 # # S5J Configuration Options # CONFIG_ARCH_CHIP_S5JT200=y CONFIG_S5J_S5JT200=y # # S5J Peripheral Support # CONFIG_S5J_HAVE_ADC=y CONFIG_S5J_HAVE_DMA=y CONFIG_S5J_HAVE_I2C=y CONFIG_S5J_HAVE_I2S=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_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_DMA is not set CONFIG_S5J_I2C=y # CONFIG_S5J_I2S is not set CONFIG_S5J_MCT=y CONFIG_S5J_TIMER0=y # 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_UART3=y 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 is not set CONFIG_S5J_SPI=y # CONFIG_S5J_WATCHDOG is not set CONFIG_S5J_SFLASH=y # CONFIG_S5J_SENSOR_PPD42NS 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_DEBUG_DISPLAY_SYMBOL is not set # 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=968704 # CONFIG_DDR is not set # CONFIG_ARCH_HAVE_SDRAM is not set # # Board Selection # CONFIG_ARCH_BOARD_ARTIK053=y # CONFIG_ARCH_BOARD_ARTIK053S is not set # CONFIG_ARCH_BOARD_ARTIK055S is not set # CONFIG_ARCH_BOARD_SIDK_S5JT200 is not set CONFIG_ARCH_BOARD_ARTIK05X_FAMILY=y CONFIG_ARCH_BOARD="artik05x" # # Common Board Options # # CONFIG_BOARD_CRASHDUMP is not set # CONFIG_BOARD_ASSERT_AUTORESET is not set CONFIG_LIB_BOARDCTL=y CONFIG_BOARDCTL_RESET=y # CONFIG_BOARDCTL_UNIQUEID is not set # CONFIG_BOARD_FOTA_SUPPORT is not set # # Board-Specific Options # CONFIG_ARTIK05X_BOOT_FAILURE_DETECTION=y CONFIG_ARTIK05X_BOOT_COUNTS_ADDR=0x80090810 CONFIG_ARTIK05X_FLASH_CAPACITY=8388608 CONFIG_ARTIK05X_FLASH_PAGE_SIZE=4096 CONFIG_ARTIK05X_FLASH_PART=y CONFIG_ARTIK05X_FLASH_MINOR=0 CONFIG_ARTIK05X_FLASH_PART_LIST="16,48,192,32,512,2400,1536,1536,1000,400,8,512," CONFIG_ARTIK05X_FLASH_PART_TYPE="none,ftl,none,none,none,none,none,ftl,smartfs,romfs,config,none," CONFIG_ARTIK05X_FLASH_PART_NAME="bl1,sssro,bl2,sssfw,wlanfw,os,factory,ota,user,rom,nvram,sssrw," CONFIG_ARTIK05X_AUTOMOUNT=y CONFIG_ARTIK05X_AUTOMOUNT_USERFS=y CONFIG_ARTIK05X_AUTOMOUNT_USERFS_DEVNAME="/dev/smart0p8" CONFIG_ARTIK05X_AUTOMOUNT_USERFS_MOUNTPOINT="/mnt" # CONFIG_ARTIK05X_AUTOMOUNT_SSSRW is not set CONFIG_ARTIK05X_AUTOMOUNT_ROMFS=y CONFIG_ARTIK05X_AUTOMOUNT_ROMFS_DEVNAME="/dev/mtdblock9" CONFIG_ARTIK05X_AUTOMOUNT_ROMFS_MOUNTPOINT="/rom" # # Kernel 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_NPTHREAD_DESTRUCTOR_ITERATIONS=4 # CONFIG_PTHREAD_CLEANUP is not set # CONFIG_CANCELLATION_POINTS is not set # # Performance Monitoring # # CONFIG_SCHED_CPULOAD 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 # # 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_MPU_STACKGAURD is not set CONFIG_PTHREAD_STACK_MIN=256 CONFIG_PTHREAD_STACK_DEFAULT=2048 # # Device Drivers # # CONFIG_DISABLE_POLL is not set CONFIG_DEV_NULL=y CONFIG_DEV_ZERO=y # 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=y # CONFIG_SPI_CMDDATA is not set # CONFIG_SPI_BITBANG is not set CONFIG_GPIO=y # CONFIG_I2S is not set # CONFIG_AUDIO_DEVICES is not set CONFIG_BCH=y 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_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_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_SENSOR 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 CONFIG_NET_IPv6=y CONFIG_NET_IPv6_NUM_ADDRESSES=3 # CONFIG_NET_IPv6_FORWARD is not set # CONFIG_NET_IPv6_FRAG is not set CONFIG_NET_IPv6_REASS=y CONFIG_NET_IPV6_REASS_MAXAGE=60 CONFIG_NET_IPv6_SEND_ROUTER_SOLICIT=y CONFIG_NET_IPv6_AUTOCONFIG=y CONFIG_NET_IPv6_DUP_DETECT_ATTEMPTS=1 # CONFIG_NET_IPv6_PMTU_FOR_MULTICAST is not set # # Socket support # CONFIG_NET_SOCKET=y CONFIG_NSOCKET_DESCRIPTORS=20 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_IPv6_ND=y CONFIG_NET_IPv6_ND_QUEUEING=y CONFIG_NET_IPv6_ND_QUEUE=20 CONFIG_NET_IPv6_ND_NUM_NEIGHBORS=10 CONFIG_NET_IPv6_ND_NUM_DESTINATIONS=10 CONFIG_NET_IPv6_ND_NUM_PREFIXES=5 CONFIG_NET_IPv6_ND_NUM_ROUTERS=3 CONFIG_NET_IPv6_ND_MAX_MULTICAST_SOLICIT=3 CONFIG_NET_IPv6_ND_MAX_UNICAST_SOLICIT=3 CONFIG_NET_IPv6_ND_MAX_SOLICIT_INTERVAL=4000 CONFIG_NET_IPv6_ND_REACHABLE_TIME=30000 CONFIG_NET_IPv6_ND_RETRANS_TIMER=1000 CONFIG_NET_IPv6_ND_DELAY_FIRST_PROBE_TIME=5000 CONFIG_NET_IPv6_ND_ALLOW_RA_UPDATES=y CONFIG_NET_IPv6_ND_TCP_REACHABILITY_HINTS=y CONFIG_NET_IPv6_ND_RDNSS_MAX_DNS_SERVERS=0 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_THRESHOLD=536 CONFIG_NET_ICMP=y CONFIG_NET_ICMP_TTL=255 # CONFIG_NET_BROADCAST_PING is not set # CONFIG_NET_MULTICAST_PING4 is not set CONFIG_NET_IPv6_ICMP=y CONFIG_NET_IPv6_ICMP_DATASIZE=8 CONFIG_NET_IPv6_ICMP_HL=255 # CONFIG_NET_MULTICAST_PING6 is not set CONFIG_NET_LWIP_IGMP=y CONFIG_NET_LWIP_MEMP_NUM_IGMP_GROUP=8 CONFIG_NET_IPv6_MLD=y CONFIG_NET_IPv6_MLD_GROUP=4 # CONFIG_NET_IPv6_DHCP is not set # # 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_ASSERT is not set # CONFIG_NET_LWIP_ERROR is not set # 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_IPv6_STATS is not set # CONFIG_NET_IPv6_ICMP_STATS is not set # CONFIG_NET_IPv6_MLD_STATS is not set # CONFIG_NET_IPv6_ND_STATS is not set # 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 # # Interface Name # CONFIG_NET_ETH_IFNAME="en" CONFIG_NET_LOOP_IFNAME="lo" CONFIG_NET_STA_IFNAME="wl" CONFIG_NET_SOFTAP_IFNAME="sa" CONFIG_NET_LWIP_NETDB=y CONFIG_NET_DNS_TABLE_SIZE=4 CONFIG_NET_DNS_MAX_NAME_LENGTH=256 CONFIG_NET_DNS_MAX_SERVERS=2 # CONFIG_NET_DNS_DOES_NAME_CHECK is not set CONFIG_NET_DNS_SECURE=0 # CONFIG_NET_DNS_LOCAL_HOSTLIST is not set # # Driver buffer configuration # CONFIG_NET_MULTIBUFFER=y CONFIG_NET_ETH_MTU=590 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 # # Protocols # 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_XMLRPC is not set # CONFIG_NETUTILS_NTPCLIENT is not set # CONFIG_NETUTILS_WEBSERVER is not set # CONFIG_NETUTILS_FTPC is not set # CONFIG_NETUTILS_MDNS is not set # CONFIG_NETUTILS_FTPD is not set CONFIG_NETUTILS_DHCPC=y # CONFIG_NETUTILS_WEBSOCKET is not set # CONFIG_NETUTILS_LIBCOAP is not set # CONFIG_NETUTILS_TFTPC is not set # CONFIG_NETUTILS_TELNETD is not set # CONFIG_NETUTILS_SMTP is not set # CONFIG_NETUTILS_MQTT is not set CONFIG_NET_SECURITY_TLS=y CONFIG_TLS_MPI_MAX_SIZE=512 # # Wireless # CONFIG_WIFI_MANAGER=y CONFIG_SELECT_WPA_SUPPLICANT=y # CONFIG_SELECT_PROPIETARY_SUPPLICANT is not set # CONFIG_SELECT_NO_DRIVER is not set CONFIG_SELECT_SCSC_WLAN=y # CONFIG_SELECT_PROPIETARY_WLAN 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 # # 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 CONFIG_DRIVER_T20=y # CONFIG_ENABLE_EAP_FOR_SUPPLICANT is not set CONFIG_WIFIMGR_SOFTAP_IFNAME="wl1" CONFIG_WIFIMGR_STA_IFNAME="wl1" # CONFIG_WIFIMGR_DISABLE_AUTO_GET_IP is not set # CONFIG_DISABLE_EXTERNAL_AUTOCONNECT is not set # # Network utilities # CONFIG_NETUTILS_NETLIB=y CONFIG_NET_NETMON=y # # Audio Support # # CONFIG_AUDIO is not set # # Media Support # # # File Systems # # CONFIG_DISABLE_MOUNTPOINT 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 # CONFIG_FS_AUTOMOUNT_PROCFS is not set # # 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 # CONFIG_FS_TMPFS is not set # # 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=512 # 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 # CONFIG_MTD_W25 is not set # # System Logging # # CONFIG_SYSLOG is not set # CONFIG_SYSLOG_TIMESTAMP is not set # # Database # # CONFIG_ARASTORAGE is not set # # Memory Management # # CONFIG_REALLOC_DISABLE_NEIGHBOR_EXTENSION is not set # CONFIG_MM_SMALL is not set CONFIG_MM_REGIONS=1 # 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 # # Debug Options # # CONFIG_DEBUG is not set # CONFIG_DEBUG_ERROR is not set # CONFIG_DEBUG_WARN is not set # CONFIG_DEBUG_VERBOSE is not set # # Subsystem Debug Options # # CONFIG_DEBUG_LIB is not set # CONFIG_DEBUG_FS is not set # CONFIG_DEBUG_IOTBUS is not set # CONFIG_DEBUG_MM is not set # CONFIG_DEBUG_NET is not set # CONFIG_DEBUG_NET_ERROR is not set # CONFIG_DEBUG_NET_INFO is not set # CONFIG_DEBUG_SCHED is not set # CONFIG_DEBUG_TASH is not set # CONFIG_DEBUG_WLAN is not set # # SLSI WLAN FW Debug Options # # CONFIG_SCSC_ENABLE_FWFAULT_LOG is not set # # SLSI WLAN Driver Debug Options # # CONFIG_DEBUG_WLAN_DRIVER_ERROR is not set # CONFIG_DEBUG_WLAN_DRIVER_DEBUG is not set # CONFIG_DEBUG_WLAN_DRIVER_MORE is not set # CONFIG_DEBUG_WLAN_DRIVER_INFO is not set # # SLSI WPA Supplicant Debug Options # # CONFIG_DEBUG_WLAN_SUPPLICANT_ERROR is not set # CONFIG_DEBUG_WLAN_SUPPLICANT_DEBUG is not set # CONFIG_DEBUG_WLAN_SUPPLICANT_MORE is not set # CONFIG_DEBUG_WLAN_SUPPLICANT_INFO is not set # # SLSI Wi-Fi API Debug Options # # CONFIG_DEBUG_WLAN_API_ERROR is not set # CONFIG_DEBUG_WLAN_API_DEBUG is not set # CONFIG_DEBUG_WLAN_API_INFO is not set # # OS Function Debug Options # # CONFIG_ARCH_HAVE_HEAPCHECK is not set # CONFIG_DEBUG_MM_HEAPINFO is not set # CONFIG_DEBUG_IRQ is not set # # Driver Debug Options # # CONFIG_DEBUG_I2S is not set # CONFIG_DEBUG_PWM is not set # CONFIG_DEBUG_RTC is not set # CONFIG_DEBUG_SPI is not set # CONFIG_DEBUG_WATCHDOG is not set # # System Debug Options # # CONFIG_DEBUG_SYSTEM is not set # # Stack Debug Options # CONFIG_ARCH_HAVE_STACKCHECK=y CONFIG_STACK_COLORATION=y # # Build Debug Options # # CONFIG_DEBUG_SYMBOLS is not set # CONFIG_FRAME_POINTER is not set # # 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 # # Built-in Libraries # # # 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_FLOATPRECISION=6 CONFIG_LIBC_SCANSET=y # CONFIG_NOPRINTF_LONGLONG_TO_ASCII is not set CONFIG_LIBC_IOCTL_VARIADIC=y # CONFIG_LIBC_WCHAR is not set # CONFIG_LIBC_LOCALE is not set 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_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_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 # # Non-standard Library Support # # # Basic CXX Support # # CONFIG_C99_BOOL8 is not set # CONFIG_HAVE_CXX is not set # # External Libraries # # CONFIG_AVS_DEVICE_SDK is not set # CONFIG_AWS_SDK is not set # CONFIG_NETUTILS_CODECS is not set # # CURL Options # # CONFIG_ENABLE_CURL is not set # CONFIG_ERROR_REPORT is not set # CONFIG_ENABLE_IOTIVITY is not set CONFIG_NETUTILS_JSON=y # CONFIG_LIBTUV is not set # CONFIG_LWM2M_WAKAAMA is not set # CONFIG_STRESS_TOOL is not set # CONFIG_VOICE_SOFTWARE_EPD is not set # # Application Configuration # # # Application entry point list # # CONFIG_ENTRY_MANUAL is not set # CONFIG_ENTRY_HELLO is not set CONFIG_ENTRY_IOTJS_STARTUP=y CONFIG_USER_ENTRYPOINT="iotjs_startup_main" CONFIG_BUILTIN_APPS=y # # Examples # # CONFIG_EXAMPLES_AVS_TEST is not set # CONFIG_EXAMPLES_AWS is not set # CONFIG_EXAMPLES_CURLTEST 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_EVENTLOOP is not set # CONFIG_EXAMPLES_FOTA_SAMPLE is not set # CONFIG_FILESYSTEM_HELPER_ENABLE is not set CONFIG_EXAMPLES_HELLO=y # CONFIG_EXAMPLES_HELLOXX is not set # CONFIG_EXAMPLES_IOTBUS_TEST is not set CONFIG_EXAMPLES_IOTJS_STARTUP=y CONFIG_EXAMPLES_IOTJS_STARTUP_JS_FILE="/rom/example/index.js" # CONFIG_EXAMPLES_IOTJS_STARTUP_WIFI is not set # CONFIG_EXAMPLES_KERNEL_SAMPLE is not set # CONFIG_EXAMPLES_LIBTUV 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_SETJMP_TEST 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_SPEECH_DETECTOR_TEST is not set # CONFIG_EXAMPLES_ST_THINGS is not set # CONFIG_EXAMPLES_TESTCASE is not set # CONFIG_EXAMPLES_TLS_BENCHMARK 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_WIFIMANAGER_TEST is not set # # Platform-specific Support # # CONFIG_PLATFORM_CONFIGDATA is not set # # Shell # CONFIG_TASH=y CONFIG_TASH_MAX_COMMANDS=132 # CONFIG_TASH_USLEEP is not set CONFIG_TASH_COMMAND_INTERFACE=y CONFIG_TASH_CMDTASK_STACKSIZE=4096 CONFIG_TASH_CMDTASK_PRIORITY=100 # CONFIG_TASH_SCRIPT is not set # # System Libraries and Add-Ons # # CONFIG_SYSTEM_CLE is not set # CONFIG_SYSTEM_CUTERM is not set # CONFIG_SYSTEM_FLASH_ERASEALL is not set # CONFIG_SYSTEM_FOTA_HAL is not set # CONFIG_SYSTEM_I2CTOOL is not set # CONFIG_SYSTEM_INIFILE is not set CONFIG_SYSTEM_PREAPP_INIT=y CONFIG_SYSTEM_PREAPP_STACKSIZE=2048 # CONFIG_SYSTEM_INSTALL is not set CONFIG_SYSTEM_IPERF=y # CONFIG_SYSTEM_NETDB is not set CONFIG_SYSTEM_RAMTEST=y CONFIG_SYSTEM_RAMTEST_PRIORITY=100 CONFIG_SYSTEM_RAMTEST_STACKSIZE=1024 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_NET_PING_CMD=y CONFIG_NET_PING_CMD_ICOUNT=5 CONFIG_ENABLE_DATE_CMD=y CONFIG_ENABLE_ENV_GET_CMD=y CONFIG_ENABLE_ENV_SET_CMD=y CONFIG_ENABLE_ENV_UNSET_CMD=y CONFIG_ENABLE_FREE_CMD=y CONFIG_ENABLE_HEAPINFO_CMD=y # CONFIG_HEAPINFO_USER_GROUP is not set # CONFIG_ENABLE_IRQINFO_CMD is not set CONFIG_ENABLE_KILL_CMD=y CONFIG_ENABLE_KILLALL_CMD=y CONFIG_ENABLE_PS_CMD=y CONFIG_ENABLE_STACKMONITOR_CMD=y CONFIG_STACKMONITOR_PRIORITY=100 CONFIG_STACKMONITOR_INTERVAL=5 CONFIG_ENABLE_UPTIME_CMD=y # CONFIG_SYSTEM_VI is not set # # Runtime Environment # CONFIG_ENABLE_IOTJS=y CONFIG_IOTJS_PRIORITY=100 CONFIG_IOTJS_STACKSIZE=32768 CONFIG_IOTJS_JERRY_HEAP=128 # # Device Management # # CONFIG_DM is not set # # Task manager # # CONFIG_TASK_MANAGER is not set # # Event Loop Framework # # CONFIG_EVENTLOOP is not set # # Things Management # # CONFIG_ST_THINGS is not set # # IoTBus Framework # CONFIG_IOTBUS=y CONFIG_IOTBUS_GPIO=y CONFIG_IOTBUS_I2C=y CONFIG_IOTBUS_PWM=y CONFIG_IOTBUS_SPI=y CONFIG_IOTBUS_UART=y iotjs-1.0+715/deps/000077500000000000000000000000001371177304000137505ustar00rootroot00000000000000iotjs-1.0+715/deps/http-parser/000077500000000000000000000000001371177304000162215ustar00rootroot00000000000000iotjs-1.0+715/deps/jerry/000077500000000000000000000000001371177304000151035ustar00rootroot00000000000000iotjs-1.0+715/deps/libtuv/000077500000000000000000000000001371177304000152555ustar00rootroot00000000000000iotjs-1.0+715/deps/mbedtls/000077500000000000000000000000001371177304000154025ustar00rootroot00000000000000iotjs-1.0+715/docs/000077500000000000000000000000001371177304000137455ustar00rootroot00000000000000iotjs-1.0+715/docs/Developer's-Guide.md000066400000000000000000000007221371177304000175020ustar00rootroot00000000000000To 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 iotjs-1.0+715/docs/Getting-Started.md000066400000000000000000000053041371177304000172760ustar00rootroot00000000000000### Supported platforms Current supported platforms are **Linux, [NuttX][nuttx-site], [Tizen][tizen-site] and [TizenRT][tizenrt-site]** 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 Raspberry Pi 2 / Linux](build/Build-for-RPi2-Linux.md) * [Build for Raspberry Pi 3 / Tizen](build/Build-for-RPi3-Tizen.md) * [Build for Stm32f4 / NuttX](build/Build-for-STM32F4-NuttX.md) * [Build for ARTIK053 / TizenRT](build/Build-for-ARTIK053-TizenRT.md) * [Build for ARTIK530 / Tizen](build/Build-for-RPi3-Tizen.md) * [Build for OpenWrt (non-tested)](build/Build-for-OpenWrt.md) * [Build for Windows (experimental)](build/Build-for-Windows.md) #### H/W boards * Current supporting * STM32F4-Discovery + BB * Raspberry Pi 2 * Raspberry Pi 3 * Samsung ARTIK 053 * Samsung ARTIK 530 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](build/Build-Script.md) to help you build IoT.js called "[build.py](https://github.com/jerryscript-project/iotjs/blob/master/tools/build.py)" in source repository. Run `tools/build.py --help` command to check all of the build options. #### How to Build ```bash tools/build.py --clean ``` #### Frequently used build options `--clean` Clean build directory before build (default: False). `--no-snapshot` Disable snapshot generation for IoT.js. It is useful for debugging sessions. `--profile PROFILE` Specify the module profile file for IoT.js. It is used for enable and disable modules. See also ["How to write a new module"](devs/Writing-New-Module.md#profile) `--run-test [{full,quiet}]` Execute tests after build, optional argument specifies the level of output for the test runner. `--jerry-debugger` Enable JerryScript debugger, so JavaScript could can be investigated with an available debugger client (eg.: [Python Debugger Console](https://github.com/jerryscript-project/jerryscript/blob/master/jerry-debugger/jerry_client.py) or [IoT.js Code](https://github.com/jerryscript-project/iotjscode/)). See also ["Use JerryScript Debugger"](devs/Use-JerryScript-Debugger.md). `--js-backtrace {ON,OFF}` Enable/disable backtrace information of JavaScript code (default: ON in debug and OFF in release build). [nuttx-site]: http://nuttx.org/ [tizen-site]: https://www.tizen.org/ [tizenrt-site]: https://wiki.tizen.org/Tizen_RT iotjs-1.0+715/docs/License.md000066400000000000000000000021561371177304000156550ustar00rootroot00000000000000### Introduce License Policy 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. > 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. ※ [IoT.js Developer's Certificate of Origin 1.0](IoT.js-Developer's-Certificate-of-Origin-1.0) applies from _15th June in 2015_ ### Open Source Software The following Open Source software supports IoT.js: * **_[libuv](https://github.com/libuv/libuv)_** licensed under [MIT License](http://opensource.org/licenses/MIT) iotjs-1.0+715/docs/README.md000066400000000000000000000025501371177304000152260ustar00rootroot00000000000000Welcome to the IoT.js! > 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) - [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) - [Raspberry Pi 3 / Tizen](build/Build-for-RPi3-Tizen.md) - [Stm32f4 / NuttX](build/Build-for-STM32F4-NuttX.md) - [ARTIK053 / TizenRT](build/Build-for-ARTIK053-TizenRT.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) iotjs-1.0+715/docs/api/000077500000000000000000000000001371177304000145165ustar00rootroot00000000000000iotjs-1.0+715/docs/api/IoT.js-API-ADC.md000066400000000000000000000057731371177304000171560ustar00rootroot00000000000000### Platform Support The following table shows ADC module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | adc.open | X | X | X | O | O | | adc.openSync | X | X | X | O | O | | adcpin.read | X | X | X | O | O | | adcpin.readSync | X | X | X | O | O | | adcpin.close | X | X | X | O | O | | adcpin.closeSync | X | X | X | O | O | # ADC This module allows reading analogue data from hardware pins. The hardware pins can be read from or written to, therefore they are called bidirectional IO pins. This module provides the reading part. 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#adc-pin) ### adc.open(configuration, callback) * `configuration` {Object} * `device` {string} Mandatory configuration on Linux. * `pin` {number} Mandatory configuration on NuttX and TizenRT. * `callback` {Function} * `err`: {Error|null} * `adcpin` {Object} An instance of AdcPin. * Returns: {Object} An instance of AdcPin. Opens an ADC pin with the specified configuration asynchronously. **Example** ```js var adc = require('adc'); var adc0 = adc.open({ device: '/sys/devices/12d10000.adc/iio:device0/in_voltage0_raw' }, function(err) { if (err) { throw err; } }); ``` ### adc.openSync(configuration) * `configuration` {Object} * `device` {string} Mandatory configuration on Linux. * `pin` {number} Mandatory configuration on NuttX and TizenRT. * `callback` {Function} * `err`: {Error|null} * Returns: {Object} An instance of AdcPin. Opens an ADC pin with the specified configuration synchronously. **Example** ```js var adc = require('adc'); var adc0 = adc.openSync({ device: '/sys/devices/12d10000.adc/iio:device0/in_voltage0_raw' }); ``` ## Class: AdcPin ### adcpin.read(callback) * `callback` {Function} * `err`: {Error|null} * `{number}` Analog value. Reads the analog value from the pin asynchronously. `callback` will be called having read the analog value. **Example** ```js adc0.read(function(err, value) { if (err) { throw err; } console.log('value:', value); }); ``` ### adcpin.readSync() * Returns: `{number}` Analog value. Reads the analog value from the pin synchronously. **Example** ```js var value = adc0.readSync(); console.log('value:', value); ``` ### adcpin.close([callback]) * `callback` {Function} * `err`: {Error|null} Closes ADC pin asynchronously. This function must be called after the work of ADC finished. `callback` will be called after ADC device is released. **Example** ```js adc0.close(function(err) { if (err) { throw err; } }); ``` ### adcpin.closeSync() Closes ADC pin synchronously. This function must be called after the work of ADC finished. **Example** ```js adc0.closeSync(); console.log('adc pin is closed'); ``` iotjs-1.0+715/docs/api/IoT.js-API-Assert.md000066400000000000000000000117641371177304000200250ustar00rootroot00000000000000### Platform Support The following shows Assert module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | assert.assert | O | O | O | O | O | | assert.doesNotThrow | O | O | O | O | O | | assert.equal | O | O | O | O | O | | assert.fail | O | O | O | O | O | | assert.notEqual | O | O | O | O | O | | assert.notStrictEqual | O | O | O | O | O | | assert.strictEqual | O | O | O | O | O | | assert.throws | O | O | O | O | O | # Assert Assert module is designed for writing tests for applications. You can access the functions of the module by adding `require('assert')` to your file. ## Class: AssertionError Assert module will produce `AssertionError` in case of an assertion failure. `AssertionError` inherits standard `Error` thus it has properties provided by `Error` object including additional properties. * `actual` {any} This property contains the actual value. * `expected` {any} This property contains the expected value. * `message` {any} The error message, default value is the error itself. * `name` {string} The name is `AssertionError` string. * `operator` {string} This property contains the operator used for comparing `actual` with `expected`. ### assert(value[, message]) * `value` {any} Value to test. * `message` {any} Message displayed in the thrown error. Checks if the `value` is truthy. If it is not, throws an AssertionError, with the given optional `message`. **Example** ```js var assert = require('assert'); assert.assert(1); // OK assert.assert(true); // OK assert.assert(false); // throws "AssertionError: false == true" assert.assert(0); // throws "AssertionError: 0 == true" assert.assert(false, "it's false"); // throws "AssertionError: it's false" ``` ### doesNotThrow(block[, message]) * `block` {Function} * `message` {any} Message to be displayed. Tests if the given `block` does not throw any exception. Otherwise throws an exception with the given optional `message`. **Example** ```js var assert = require('assert'); assert.doesNotThrow( function() { assert.assert(1); } ); // OK assert.doesNotThrow( function() { assert.assert(0); } ) // throws "AssertionError: Got unwanted exception." ``` ### equal(actual, expected[, message]) * `actual` {any} The actual value. * `expected` {any} The expected value. * `message` {any} Message to be displayed. Tests if `actual == expected` is evaluated to `true`. Otherwise throws an exception with the given optional `message`. **Example** ```js var assert = require('assert'); assert.equal(1, 1); assert.equal(1, '1'); ``` ### fail(actual, expected, message, operator) * `actual` {any} The actual value. * `expected` {any} The expected value. * `message` {any} Message to be displayed. * `operator` {string} The operator. Throws an `AssertionError` exception with the given `message`. **Example** ```js var assert = require('assert'); assert.fail(1, 2, undefined, '>'); // AssertionError: 1 > 2 ``` ### notEqual(actual, expected[, message]) * `actual` {any} The actual value. * `expected` {any} The expected value. * `message` {any} Message to be displayed. Tests if `actual != expected` is evaluated to `true`. Otherwise throws an exception with the given optional `message`. **Example** ```js var assert = require('assert'); assert.notEqual(1, 2); ``` ### notStrictEqual(actual, expected[, message]) * `actual` {any} The actual value. * `expected` {any} The expected value. * `message` {any} Message to be displayed. Tests if `actual !== expected` is evaluated to `true`. Otherwise throws an exception with the given optional `message`. **Example** ```js var assert = require('assert'); assert.notStrictEqual(1, 2); // OK assert.notStrictEqual(1, 1); // AssertionError: 1 !== 1 assert.notStrictEqual(1, '1'); // OK ``` ### strictEqual(actual, expected[, message]) * `actual` {any} The actual value. * `expected` {any} The expected value. * `message` {any} Message to be displayed. Tests if `actual === expected` is evaluated to `true`. Otherwise throws an exception with the given optional `message`. **Example** ```js var assert = require('assert'); assert.strictEqual(1, 1); // OK assert.strictEqual(1, 2); // AssertionError: 1 === 2 assert.strictEqual(1, '1'); // AssertionError: 1 === '1' ``` ### throws(block[, expected, message]) * `block` {Function} The function that throws an error. * `expected` {Function} The expected error type. * `message` {any} Message to be displayed. Tests if the given `block` throws an `expected` error. Otherwise throws an exception with the given optional `message`. **Example** ```js var assert = require('assert'); assert.throws( function() { assert.equal(1, 2); }, assert.AssertionError ); // OK assert.throws( function() { assert.equal(1, 1); }, assert.AssertionError ); // Uncaught error: Missing exception assert.throws( function() { assert.equal(1, 2); }, TypeError ); // AssertionError ``` iotjs-1.0+715/docs/api/IoT.js-API-BLE.md000066400000000000000000000121661371177304000171630ustar00rootroot00000000000000### Platform Support The following shows BLE module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | ble.startAdvertising | O | X | O | X | X | | ble.stopAdvertising | O | X | O | X | X | | ble.setServices | O | X | O | X | X | # BLE - Bluetooth Low Energy ### Event: 'advertisingStart' * `callback` {Function} * error {Error} Emitted when advertisement starts. **Example** ```js var ble = require('ble'); ble.on('advertisingStart', function(error) { console.log('on -> advertisingStart: ' + (error ? 'error ' + error : 'success')); if (!error) { ble.setServices([ // service data ]); } }); ``` ### Event: 'stateChange' * `callback` {Function} * `state` {String} Can be 'unknown', 'resetting', 'unsupported', 'unauthorized', 'poweredOff' or 'poweredOn'. Emitted when adapter state is changed. **Example** ```js var ble = require('ble'); ble.on('stateChange', function(state){ console.log('onStateChange: ' + state); if (state == 'poweredOn') { ble.startAdvertising('iotjs', ['data'], function(err) { }); } else { ble.stopAdvertising(function(err) { }); } }); ``` ### ble.startAdvertising(name, serviceUuids[, callback]) * `name` {string} Maximum 26 bytes. * `serviceUuids` {Array[String]} * 1 128-bit service UUID * 1 128-bit service UUID + 2 16-bit service UUIDs * 7 16-bit service UUID * `callback` {Function} Error handler. * `error` {Error} Starts advertising. `ble.state` must be in poweredOn state before advertising is started. `ble.on('stateChange', callback(state));` can be used to register for state change events. **Example** ```js var name = 'name'; var serviceUuids = ['fffffffffffffffffffffffffffffff0'] ble.startAdvertising(name, serviceUuids[, callback(error)]); ``` ### ble.stopAdvertising(callback) * `callback` {Function} Error handler. * `error` {Error} Stops advertising. ### ble.setServices(services[, callback]) * `services` {Array[PrimaryService]} * `callback` {Function} Error handler. * `error` {Error} Sets the primary services available on the peripheral. ## Class: Descriptor Descriptors are defined attributes that describe a characteristic value. ### new Descriptor(options) * `options` {Object} * `uuid:` {string} A Universally Unique ID (UUID) is a 16 or 128-bit hex value used to identify the type of every attribute. * `value` {string|Buffer} **Example** ```js var descriptor = new Descriptor({ uuid: '2901', value: 'value' }); ``` ## Class: Characteristic Characteristics are defined attribute types that contain a single logical value. ### new Characteristic(options) * `options` {Object} * `uuid:` {string} A Universally Unique ID (UUID) is a 16 or 128-bit hex value used to identify the type of every attribute. * `properties` {Array[string]} Can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify' and 'indicate'. * `secure` {Array[string]} Enables security for properties, can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify' and 'indicate'. * `value` {Buffer} * `descriptors` {Array[Descriptor]} * `onReadRequest` {Function} Read request handler. (optional) * `offset` {number} (0x0000 - 0xffff) * `callback` {Function} * `result` {Characteristic.RESULT_*} * `data` {Buffer} * `onWriteRequest` {Function} Write request handler. (optional) * `data` {Buffer} * `offset` {number} (0x0000 - 0xffff) * `withoutResponse` {boolean} * `callback` {Function} * `result` {Characteristic.RESULT_*} * `onSubscribe` {Function} Notify/indicate subscribe handler. (optional) * `maxValueSize` {number} Maximum data size. * `updateValueCallback` {Function} * `onUnsubscribe` {Function} Notify/indicate unsubscribe handler. (optional) * `onNotify` {Function} Notify sent handler. (optional) * `onIndicate` {Function} Indicate confirmation received handler. (optional) Returns: {Characteristic} **Example** ```js var characteristic = new Characteristic({ uuid: 'fffffffffffffffffffffffffffffff1', // or 'fff1' for 16-bit properties: ['read', 'write'], secure: [], value: null, descriptors: [descriptor], onReadRequest: null, onWriteRequest: null, onSubscribe: null, onUnsubscribe: null, onNotify: null, onIndicate: null }); ``` ### Characteristic.RESULT_SUCCESS ### Characteristic.RESULT_INVALID_OFFSET ### Characteristic.RESULT_INVALID_ATTRIBUTE_LENGTH ### Characteristic.RESULT_UNLIKELY_ERROR ## Class: PrimaryService PrimaryService is a collection of characteristics and relationships to other services that encapsulate the behavior of part of a device. ### new PrimaryService(options) * `options` {Object} * `uuid` {string} A Universally Unique ID (UUID) is a 16 or 128-bit hex value used to identify the type of every attribute. * `characteristics` {Array[Characteristic]} **Example** ```js var primaryService = new PrimaryService({ uuid: 'fffffffffffffffffffffffffffffff0', // or 'fff0' for 16-bit characteristics: [ // see Characteristic for data type ] }); ``` iotjs-1.0+715/docs/api/IoT.js-API-Buffer.md000066400000000000000000000361021371177304000177660ustar00rootroot00000000000000### Platform Support The following shows Buffer module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | buf.compare | O | O | O | O | O | | buf.copy | O | O | O | O | O | | buf.equals | O | O | O | O | O | | buf.fill | O | O | O | O | O | | buf.from | O | O | O | O | O | | buf.slice | O | O | O | O | O | | buf.toString | O | O | O | O | O | | buf.write | O | O | O | O | O | | buf.writeUInt8 | O | O | O | O | O | | buf.writeUInt16LE | O | O | O | O | O | | buf.writeUInt32LE | O | O | O | O | O | | buf.readInt8 | O | O | O | O | O | | buf.readUInt8 | O | O | O | O | O | | buf.readUInt16LE | O | O | 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 buf1 = new Buffer(10); // Creates a Buffer containing [0x1, 0x2, 0x3]. var buf2 = new Buffer([1, 2, 3]); // Creates a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74]. 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(65)); // prints: 1 console.log(buffer); var buffer = new Buffer(String.fromCharCode(128)); // prints: 2 console.log(buffer); var buffer = new Buffer(String.fromCharCode(2048)); // prints: 3 console.log(buffer); 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([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.from(array) * `array` {Array} Array of numbers. * Returns: {Buffer} containing the elements from `array` 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 = require('buffer'); var source = new Buffer[65, 66, 67]; var buffer = Buffer.from(source); //prints: ABC console.log(buffer.toString()); ``` ### Buffer.from(string[,encoding]) * `str` {String} Source string. * `encoding` {String} Encoding format. * Returns: {Buffer} containing the elements from `str` 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 = Buffer.from('4142','hex'); //prints: AB console.log(buffer.toString()); ``` ### Buffer.from(buffer) * `buffer` {Buffer} Source buffer. * Returns: {Buffer} which is the copy of `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 source = new Buffer(12); var buffer = Buffer.from(source); ``` ### Buffer.from(arrayBuffer[, byteOffset[, length]]) * `arrayBuffer` {ArrayBuffer} Arraybuffer, or a buffer of a TypedArray * `byteOffset` {Number} Index of first byte to expose. Default: 0. * `length` {Number} Number of bytes to expose. Default: arrayBuffer.length - byteOffset. * Returns: {Buffer} containing the data of `arraybuffer` from read `offset` with `length` **Example** ```js var source = new ArrayBuffer(12); var buffer = Buffer.from(source, 0, 2); //prints: 2 console.log(buffer.length); ``` ```js var typed_source = new Uint8Array([65,66]); var arr_buff = Buffer.from(typed_source1.buffer, 0, 2); //prints: AB console.log(buff.toString('utf-8')); ``` ### 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(''); 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)); ``` iotjs-1.0+715/docs/api/IoT.js-API-Crypto.md000066400000000000000000000063021371177304000200340ustar00rootroot00000000000000### Platform Support The following chart shows the availability of each Crypto module API function on each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | Nuttx
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | crypto.createHash | O | O | O | O | O | | crypto.createVerify | O | O | O | O | O | | crypto.getHashes | O | O | O | O | O | # Crypto The module provides limited cryptographic functionality, namely hashing and signature verification. To access this module use `require('crypto')`. ### crypto.createVerify(hashType) Creates and returns a `Verify` object. This object can not be created with the `new` keyword. - `hashType` {string} Hash type of the signature. {`sha1 | sha256`} Note: We currently only support `rsa-sha1` and `rsa-sha256` signatures. ### crypto.createHash(hashType) Creates and returns a `Hash` object. This object can not be created with the `new` keyword. - `hashType` {string} Type of the hash. {`sha1 | sha256`} Note: We currently only support `sha1` and `sha256` hashes. ### crypto.getHashes() Returns the available hashing methods. ## Class: Verify The `Verify` class allows the user to verify a signature against a public key. ### verify.update(data) Updates the `Verify` object with the given `data`. - `data` {Buffer | string} Updates the object with the `data`. If there is already `data` in the object, concatenates them. **Example** ```js var crypto = require('crypto'); var myVerifyObject = crypto.createVerify('sha256'); myVerifyObject.update('This data should be verified'); myVerifyObject.update('\nAnd this belongs there too.'); ``` ### verify.verify(publicKey, signature) Verifies the `signature` against the `publicKey` using the `data` added with `verify.update()`. - `publicKey` {string | Buffer} A valid RSA Public key. - `signature` {string | Buffer} A base64 encoded `rsa-sha1` or `rsa-sha256` signature. Returns `true` if the verification succeeds, `false` otherwise. **Example** ```js var crypto = require('crypto'); var myVerifyObject = crypto.createVerify('sha256'); var myKey = getPublicKeySomehow(); var myData = getSomeStringToVerify(); var mySignature = getSignatureSomehow(); myVerifyObject.update(myData); var success = myVerifyObject.verify(myKey, mySignature); if (!success) { throw new Error('Invalid signature !'); } ``` ## Class: Hash The `Hash` class creates hashes from the data given. ### hash.update(data) Updates the `Hash` object with the given `data`. - `data` {Buffer | String} Updates the object with the `data`. If there is already `data` in the object, concatenates them. ### hash.digest(encoding) Returns an `encoded` hash of the input `data` as a `string` or `Buffer`. - `encoding` {string} Encodes the result of the hashing to the given format. Can be {`hex | base64`}. If no `encoding` is given, or the given `encoding` doesn't match the known formats, returns the raw `hash` in a `Buffer`. Digest can only be called once on a given `Hash` object. **Example** ```js var crypto = require('crypto'); var myData = 'Some data to hash'; var myHashObj = crypto.createHash('sha1'); myHashObj.update(myData); var myHash = myHashObj.digest('hex'); ``` iotjs-1.0+715/docs/api/IoT.js-API-DGRAM.md000066400000000000000000000254701371177304000174150ustar00rootroot00000000000000### Platform Support The following shows dgram module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | dgram.createSocket | O | O | O | △ ¹ | △ ¹ | | dgram.Socket.addMembership | O | X | O | X | O | | dgram.Socket.address | O | O | O | X | O | | dgram.Socket.bind | O | O | O | △ ¹ | △ ¹ | | dgram.Socket.close | O | O | O | △ ² | O | | dgram.Socket.dropMembership | O | X | O | X | O | | dgram.Socket.send | O | O | O | △ ¹ | △ ¹ | | dgram.Socket.setBroadcast | O | X | O | X | X | | dgram.Socket.setMulticastLoopback | O | O | O | X | O | | dgram.Socket.setMulticastTTL | X | X | X | X | O | | dgram.Socket.setTTL | O | X | O | X | O | 1. On NuttX/STM32F4-Discovery and TizenRT/Artik053, even a couple of sockets/server/requests might not work properly. 2. On NuttX/STM32F4-Discovery, close() may block due to a bug in poll(). # Dgram The dgram module provides an implementation of UDP Datagram sockets. The following example creates a UDP Datagram server. **Example** ```js var dgram = require('dgram'); var server = dgram.createSocket('udp4'); server.on('error', function (err) { console.log('Error: ' + err); server.close(); }); server.on('message', function(msg, rinfo) { // prints: message received console.log('server got: ' + msg); }); server.on('listening', function() { console.log('server listening at ' + server.address().port); }); server.bind(41234); ``` ### dgram.createSocket(options[, callback]) * `options` {Object} * `type` {string} * `reuseAddr` {boolean} * `callback` {Function} (optional) Creates a new `dgram.Socket` object. The type of the connection is specified by `options.type`. Currently only `udp4` is supported. If `reuseAddr` is true the `socket.bind()` call reuses the address even if this address has been bound by another process. The optional 'callback' function is attached to the [`'message'`](#event-message) event. **Example** ```js var dgram = require('dgram'); var server = dgram.createSocket({ type: 'udp4', reuseAddr: true}); ``` ### dgram.createSocket(type[, callback]) * `type` {string} * `callback` {Function} (optional) Creates a new `dgram.Socket` object. The type of the connection is specified by the `type` argument. Currently only `udp4` is supported. The optional 'callback' function is attached to the [`'message'`](#event-message) event. **Example** ```js var dgram = require('dgram'); var server = dgram.createSocket('udp4'); ``` ## Class: dgram.Socket The `dgram.Socket` object is an `EventEmitter` that encapsulates the datagram functionality. New instances of `dgram.Socket` are created using `dgram.createSocket()`. The new keyword must not be used to create dgram.Socket instances. Supported events: ### Event: 'close' The `'close'` event is emitted after a socket is closed with `close()`. Once triggered, no new `'message'` events will be emitted on this socket. ### Event: 'error' * `exception` {Error} The `'error'` event is emitted whenever any error occurs. A single Error object is passed to the event handler. ### Event: 'listening' The `'listening'` event is emitted whenever a socket begins listening for datagram messages. This occurs as soon as UDP sockets are created. ### Event: 'message' * `msg` {Buffer} The message. * `rinfo` {Object} Remote address information. * `address` {string} The sender address. * `family` {string} The address family ('IPv4'). * `port` {number} The sender port. * `size` {number} The message size. The `'message'` event is emitted when a new datagram is received by the socket. The `msg` argument contains the message data and the `rinfo` argument contains the message properties. ### socket.addMembership(multicastAddress[, multicastInterface]) * `multicastAddress` {string} * `multicastInterface` {string} Joins the multicast group specified by `multicastAddress` and `multicastInterface`. If `multicastInterface` is undefined the operating system will choose one add interface and will add membership to it. To add membership to every available interface, call addMembership multiple times, once per interface. **Example** ```js var dgram = require('dgram'); var multicast_address = '230.255.255.250'; var server = dgram.createSocket('udp4'); server.bind(12345 /* port */, function() { server.addMembership(multicast_address); }); ``` ### socket.address() * Returns: {Object} Returns an object with the properties `address`, `port` and `family`. **Example** ```js var dgram = require('dgram'); var server = dgram.createSocket('udp4'); server.on('listening', function () { var address = server.address(); // prints: address and port of the server address console.log('Addr: ' + address.address + ' port: ' + address.port); }); server.bind(12345 /* port */); ``` ### socket.bind([port][, address][, bindListener]) * `port` {number} * `address` {string} **Default:** `0.0.0.0` * `bindListener` {Function} Assign the `port` and `address` to an UDP socket. If `port` is not specified the operating system selects a random unused port. The optional 'bindListener' function is attached to the [`'listening'`](#event-listening) event. **Example** ```js var dgram = require('dgram'); var socket = dgram.createSocket({ type: 'udp4', reuseAddr: true }); var port = 12345; socket.bind(port, function () { // prints: Listening for packets console.log('Listening for packets'); }); ``` ### socket.bind(options[, bindListener]) * `options` {Object} * `port` {number} * `address` {string} **Default:** `0.0.0.0` * `bindListener` {Function} Assign `options.port` and `options.address` to an UDP socket. If `options.port` is not specified the operating system selects a random unused port. The optional 'bindListener' function is attached to the [`'listening'`](#event-listening) event. **Example** ```js var dgram = require('dgram'); var socket = dgram.createSocket({ type: 'udp4', reuseAddr: true }); socket.bind({ port:12345 }, function () { // prints: Listening for packets console.log('Listening for packets'); }); ``` ### socket.close([closeListener]) * `closeListener` {Function} Close the underlying socket and stop listening for data on it. The optional 'closeListener' function is attached to the [`'close'`](#event-close) event. **Example** ```js var dgram = require('dgram'); var socket = dgram.createSocket({ type: 'udp4', reuseAddr: true }); // prints: Close! socket.close(function () { // prints: Socket is closed console.log('Socket is closed'); }); ``` ### socket.dropMembership(multicastAddress[, multicastInterface]) * `multicastAddress` {string} * `multicastInterface` {string} Leaves for socket the given multicast group with given `multicastAddress` and `multicastInterface`. **Example** ```js var dgram = require('dgram'); var server = dgram.createSocket('udp4'); var multicast_address = '230.255.255.250'; server.bind(12345 /* port */, function() { server.addMembership(multicast_address); }); server.on('message', function(data, rinfo) { // Drop membership when a message arrived. server.dropMembership(multicast_address); }); ``` ### socket.setBroadcast(flag) * `flag` {boolean} Sets or clears the `SO_BROADCAST` socket option. When `flag` is true UDP packets may be sent to a local interface's broadcast address. **Example** ```js var dgram = require('dgram'); var socket = dgram.createSocket({ type: 'udp4', reuseAddr: true }); var port = 41237; socket.bind(port, function() { socket.setBroadcast(true); }); ``` ### socket.send(msg, [offset, length,] port [, address] [, sendListener]) * `msg` {Buffer|string|array} * `offset` {integer} Only valid if `msg` is Buffer. * `length` {integer} Only valid if `msg` is Buffer. * `port` {integer} * `address` {string} **Default:** `127.0.0.1` or `::1` * `sendListener` {Function} * `Error` {Object|null} * `code` {string} Currently it is always `"error"`. * `errno` {string} Same as `code`. * `syscall` {integer} * `address` {string} * `port` {integer} * `length` {integer} Length of data. Transmits a message to the destination socket specified by `address` and `port` arguments. The `msg` argument contains the data to be sent. It can be a {Buffer}, a {string} converted to UTF-8 bytes, or an array of {Buffer} and {string} values. In the latter case the items of the array are concatenated into a single {Buffer} before sending. If send operation is successfully completed, `sendListener` will be called with `null` and the length of data. Otherwise an Error {Object} is passed along with the length of data. **Example** ```js var dgram = require('dgram'); var socket = dgram.createSocket({ type: 'udp4', reuseAddr: true }); var broadcast_address = '255.255.255.255'; var port = 41237; socket.bind(port, function() { socket.setBroadcast(true); socket.send('Hello IoT.js', port, broadcast_address); }); ``` ### socket.sendto(msg, offset, length, port [, address] [, sendListener]) * `msg` {Buffer|string|array} * `offset` {integer} * `length` {integer} * `port` {integer} * `address` {string} **Default:** `127.0.0.1` or `::1` * `sendListener` {Function} Legacy function. It is the same as [`socket.send`](#socket-send-msg-offset-length-port-address-sendListener) except `offset` and `length` arguments are mandatory. ### socket.setMulticastLoopback(flag) * `flag` {boolean} Sets or clears the `IP_MULTICAST_LOOP` socket option. When `flag` is `true` multicast packets will also be received on the local interface. **Example** ```js var dgram = require('dgram'); var socket = dgram.createSocket({ type: 'udp4', reuseAddr: true }); var port = 41237; socket.bind(port, function() { socket.setMulticastLoopback(true); }); ``` ### socket.setMulticastTTL(ttl) * `ttl` {integer} This value must be between 0 and 255. Sets the `IP_MULTICAST_TTL` socket option which pecifies the number of IP hops that a packet is allowed to travel through, specifically for multicast traffic. Each router or gateway that forwards a packet decrements its TTL. When TTL reaches zero the packet is not forwarded anymore. The default on most systems is 1 but can vary. **Example** ```js var dgram = require('dgram'); var socket = dgram.createSocket({ type: 'udp4', reuseAddr: true }); var port = 41237; socket.bind(port, function() { socket.setMulticastTTL(1); }); ``` ### socket.setTTL(ttl) * `ttl` {integer} This value must be between 1 and 255. Sets the `IP_TTL` socket option which specifies the number of IP hops that a packet is allowed to travel through. Each router or gateway that forwards a packet decrements its TTL. When TTL reaches zero the packet is not forwarded anymore. The default on most systems is 64 but can vary. **Example** ```js var dgram = require('dgram'); var socket = dgram.createSocket({ type: 'udp4', reuseAddr: true }); var port = 41237; socket.bind(port, function() { socket.setTTL(64); }); ``` iotjs-1.0+715/docs/api/IoT.js-API-DNS.md000066400000000000000000000055771371177304000172150ustar00rootroot00000000000000### Platform Support The following shows dns module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | dns.lookup | O | O | O | X | O | ※ dns.lookup currently only returns IPv4 addresses. Support for IPv6 addresses are on the roadmap. # DNS The `dns` module provides a method to perform host name resolution. The functionality is implemented on top of the underlying operation system facilities. Please see [Implementation considerations section](#implementation-considerations). The following properties are flags which can be passed as hints for the [`dns.lookup()`](#dnslookuphostname-options-callback) method. ### dns.ADDRCONFIG * `{number}` Returned address types are determined by the types of addresses supported by the current system. ### dns.V4MAPPED * `{number}` If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. ### dns.lookup(hostname[, options], callback) * `hostname` {string} Hostname to be resolved. * `options` {Object|number} * `family` {number} The record family. If specified must be 4. Specifies that IPv4 addresses should be returned. * `hints` {number} One or more supported getaddrinfo flags. Multiple flags may be passed by bitwise `OR`ing their values. * `callback` {Function} * `err` {Error|null} If there is no error the value is `null`. * `address` {string} A string representation of an IPv4 address. * `family` {number} 4, denoting the family of `address`. Resolves a hostname (e.g. `iotjs.net`) into the first found A (IPv4) or AAAA (IPv6) record. All `option` properties are option. If `option` is a number, then it must be `4`. If `options` is not provided, then IPv4 addresses are returned if found. On error, `err` is an `Error` object where `err.code` is the error code returned by the underlying system call. The `dns.lookup()` does not necessarily do DNS requests to resolve a hostname. The implementation uses an operating system facility to associate names with addresses. Please read the [Implementation considerations section](#implementation-considerations) for more system dependent information. **Example** ```js var dns = require('dns'); dns.lookup ('localhost', 4, function(err, ip, family) { console.log('ip: ' + ip + ' family: ' + family); }); // ip: 127.0.0.1 family: 4 var options = { family: 4, hints: dns.ADDRCONFIG, }; dns.lookup ('iotjs.net', options, function(err, ip, family) { console.log('ip: ' + ip + ' family: ' + family); }); // ip: 192.30.252.154 family: 4 ``` # Implementation considerations The current implementation only supports host name resolution to IPv4 addresses. On NuttX currently only valid IPv4 addresses are allowed for the [`dns.lookup()`](#dnslookuphostname-options-callback) method. iotjs-1.0+715/docs/api/IoT.js-API-Events.md000066400000000000000000000122551371177304000200240ustar00rootroot00000000000000### Platform Support The following shows Event module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | emitter.addListener | O | O | O | O | O | | emitter.on | O | O | O | O | O | | emitter.emit | O | O | O | O | O | | emitter.once | O | O | O | O | O | | emitter.removeListener | O | O | O | O | O | | emitter.removeAllListeners | O | O | O | O | O | # Events IoT.js is based on event-driven programming where objects (called "emitters") periodically emit named events. # Class: EventEmitter The `EventEmitter` plays a role as base class for "emitters". User application would not directly create an instance of `EventEmitter` since `EventEmitter` is an abstract trait which defines its behavior and grants to sub-classes. ### new EventEmitter() * Returns {EventEmitter}. Returns with a new EventEmitter object. **Example** ```js var EventEmitter = require('events'); var emitter = new EventEmitter(); ``` ### emitter.addListener(event, listener) * `event` {string} The name of the event. * `listener` {Function} The callback function. * `args` {any}. * Returns `emitter` {EventEmitter}. It is an alias for `emitter.on(eventName, listener)`. 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'); var emitter = new EventEmitter(); var eventSequence = ''; var listener1 = function() { eventSequence += '2'; }; emitter.addListener('test', listener1); emitter.addListener('test', listener1); emitter.emit('test'); console.log(eventSequence); // prints '22' ``` ### emitter.on(event, listener) * `event` {string} The name of the event. * `listener` {Function} The callback function. * `args` {any}. * Returns `emitter` {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'); var emitter = new EventEmitter(); emitter.on('event', function() { console.log('emit event'); }); emitter.emit('event'); ``` ### emitter.emit(event[, args..]) * `event` {string} The name of the event. * `args` {any}. * Returns {boolean}. Synchronously calls each of the listeners registered for the `event`, in the order they were registered, passing the supplied arguments to each. Returns true if the event had listeners, false otherwise. **Example** ```js var EventEmitter = require('events'); var emitter = new EventEmitter(); emitter.addListener('event', function() { console.log('emit event'); }); emitter.emit('event'); // true emitter.emit('not_an_event'); // false ``` ### emitter.once(event, listener) * `event` {string} The name of the event. * `listener` {Function} The callback function. * `args` {any}. * Returns `emitter` {EventEmitter}. Adds the `listener` as a one time listener for the `event`. Using this method, it is possible to register a listener that is called at most once for a particular `event`. The listener will be invoked only once, when the first `event` is emitted. **Example** ``` js var EventEmitter = require('events'); var assert = require('assert'); var emitter = new EventEmitter(); var onceCnt = 0; emitter.once('once', function() { onceCnt += 1; }); assert.equal(onceCnt, 0); emitter.emit('once'); assert.equal(onceCnt, 1); emitter.emit('once'); assert.equal(onceCnt, 1); ``` ### emitter.removeListener(event, listener) * `event` {string} The name of the event. * `listener` {Function} The callback function. * `args` {any}. * Returns `emitter` {EventEmitter}. Removes `listener` from the list of event listeners. If you add the same `listener` multiple times, this removes only one instance of them. **Example** ```js var EventEmitter = require('events'); var emitter = new EventEmitter(); var listener = function() { console.log('listener'); }; emitter.addListener('event', listener); emitter.removeListener('event', listener); ``` ### emitter.removeAllListeners([event]) * `event` {string} The name of the event. * Returns `emitter` {EventEmitter}. Removes all listeners. If `event` was specified, it only removes the listeners for that event. **Example** ``` js var EventEmitter = require('events'); var emitter = new EventEmitter(); function removableListener() { console.log("listener called"); } emitter.addListener('event1', removableListener); emitter.addListener('event2', removableListener); emitter.addListener('event2', removableListener); emitter.addListener('event3', removableListener); emitter.removeAllListeners('event2'); var res = emitter.emit('event2'); // res == false res = emitter.emit('event1'); // res == true, prints "listener called" emitter.removeAllListeners(); res = emitter.emit('event1'); // res == false res = emitter.emit('event3'); // res == false ``` iotjs-1.0+715/docs/api/IoT.js-API-File-System.md000066400000000000000000000446301371177304000207230ustar00rootroot00000000000000### Platform Support The following shows fs module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | fs.close | O | O | O | O | O | | fs.closeSync | O | O | O | O | O | | fs.createReadStream | O | O | O | O | O | | fs.createWriteStream | O | O | O | O | O | | fs.exists | O | O | O | O | O | | fs.existsSync | O | O | O | O | O | | fs.fstat | O | O | O | X | X | | fs.fstatSync | O | O | O | X | X | | fs.mkdir | O | O | O | O | O | | fs.mkdirSync | O | O | O | O | O | | fs.open | O | O | O | O | O | | fs.openSync | O | O | O | O | O | | fs.read | O | O | O | O | O | | fs.readSync | O | O | O | O | O | | fs.readdir | O | O | O | O | O | | fs.readdirSync | O | O | O | O | O | | fs.readFile | O | O | O | O | O | | fs.readFileSync | O | O | O | O | O | | fs.rename | O | O | O | O | O | | fs.renameSync | O | O | O | O | O | | fs.rmdir | O | O | O | O | O | | fs.rmdirSync | O | O | O | O | O | | fs.stat | O | O | O | O | O | | fs.statSync | O | O | O | O | O | | fs.unlink | O | O | O | O | O | | fs.unlinkSync | O | O | O | O | O | | fs.write | O | O | O | O | O | | fs.writeSync | O | O | O | O | O | | fs.writeFile | O | O | O | O | O | | fs.writeFileSync | O | O | O | O | O | ※ On NuttX path should be passed with a form of **absolute path**. # File System ## Class: fs.Stats fs.Stats class is an object returned from `fs.stat()`,`fs.fstat()` and their synchronous counterparts. ### stats.isDirectory() * Returns: {boolean} Returns true if stated file is a directory. ### stats.isFile() * Returns: {boolean} Returns true if stated file is a file. **Example** ```js var assert = require('assert'); var fs = require('fs'); fs.stat('test.txt', function(err, stat) { if (err) { throw err; } assert.equal(stat.isFile(), true); assert.equal(stat.isDirectory(), false); }); ``` ### fs.close(fd, callback) * `fd` {integer} File descriptor. * `callback` {Function} * `err` {Error|null} Closes the file of `fd` asynchronously. **Example** ```js var fs = require('fs'); fs.open('test.txt', 'r', function(err, fd) { if (err) { throw err; } // do something fs.close(fd, function(err) { if (err) { throw err; } }); }); ``` ### fs.closeSync(fd) * `fd` {integer} File descriptor. Closes the file of `fd` synchronously. **Example** ```js var fs = require('fs'); var fd = fs.openSync('test.txt', 'r'); // do something fs.closeSync(fd); ``` ## Class: fs.ReadStream A successful call to `fs.createReadStream()` will return a new `fs.ReadStream` object. `fs.ReadStream` inherits from `stream.Readable`. ### Event: 'open' * `fd` {integer} File descriptor used by the `fs.ReadStream`. Emitted when the `fs.ReadStream`'s file descriptor has been opened. ### Event: 'ready' Emitted when the `fs.ReadStream` is ready to be used. Emitted immediately after `open`. ### Event: 'data' * `chunk` {Buffer|string} Inherited from `stream.Readable`. Emitted when the stream passes the ownership of the data to a consumer. Only streams in flowing mode emit this event. A stream can be switched to flowing mode by calling the readable.resume() function or by adding a 'data' event handler. ### Event: 'close' Emitted when the `fs.ReadStream`'s file descriptor has been closed. ### ReadStream.bytesRead * {integer} Number of bytes that have been read so far. ### ReadStream.path * {string} The path to the file of the `fs.ReadStream`. ### fs.createReadStream(path[, options]) * `path` {string} File path to open for reading. * `options` {Object} * `flags` {string} Flags to open file with. **Default:** `'r'` * `encoding` {string} **Default:** `null` * `fd` {integer} File descriptor to be used. **Default:** `null` * `mode` {integer} Permission mode. **Default:** `0666` * `autoClose` {boolean} Should the file be closed automatically. **Default:** `true` * `bufferSize` {integer} Size of buffer in bytes. **Default:** `4096` * Returns: `fs.ReadStream` If `fd` is specified, `path` will be ignored and the specified file descriptor will be used instead. If `autoClose` is `false`, the file will not be closed automatically, even if there is an error, it will be the application's responsibility. If it is `true` (as by default), the file will be closed automatically when end of file is reached or the stream ends. **Example** ```js var fs = require('fs'); var rStream = fs.createReadStream('example.txt'); rStream.on('data', function(data) { console.log(data.toString()); }); ``` `fs.ReadStream` inherits from `stream.Readable`, so it is possible to pipe it into any `stream.Writable`. **Example** ```js var fs = require('fs'); var readableFileStream = fs.createReadStream('in.txt'); var writableFileStream = fs.createWriteStream('out.txt'); // The content of in.txt will be copied to out.txt readableFileStream.pipe(writableFileStream); ``` ## Class: fs.WriteStream A successful call to `fs.createWriteStream()` will return a new `fs.WriteStream` object. `fs.WriteStream` inherits from `stream.Writable`. ### Event: 'open' * `fd` {integer} File descriptor used by the `fs.WriteStream`. Emitted when the `fs.WriteStream`'s file descriptor has been opened. ### Event: 'ready' Emitted when the `fs.WriteStream` is ready to be used. Emitted immediately after `open`. ### Event: 'close' Emitted when the `fs.WriteStream`'s file descriptor has been closed. ### WriteStream.bytesWritten The number of bytes written so far. Does not include data that is still queued for writing. ### WriteStream.path The path to the file of the `fs.WriteStream`. ### fs.createWriteStream * `path` {string} File path to be opened for writing. * `options` {Object} * `flags` {string} Flags to open the file with. **Default:** `'w'` * `fd` {integer} File descriptor to be used. **Default:** `null` * `mode` {integer} Permission mode. **Default:** `0666` * `autoClose` {boolean} Should the file be closed automatically. **Default:** `true` * Returns `fs.WriteStream` Works similarly to `fs.createReadStream()`, but returns an `fs.WriteStream`. If `fd` is specified, `path` will be ignored and the specified file descriptor will be used instead. If `autoClose` is `false`, the file will not be closed automatically, even if there is an error, it will be the application's responsibility. If it is `true` (as by default), the file will be closed automatically when end of file is reached or the stream ends. **Example** ```js var fs = require('fs'); var wStream = fs.createWriteStream('example.txt'); wStream.on('ready', function() { wStream.write('test data'); // 'test data' will be written into example.txt }); ``` ### fs.exists(path, callback) * `path` {string} File path to be checked. * `callback` {Function} * `exists` {boolean} Checks the file specified by `path` exists asynchronously. **Example** ```js var assert = require('assert'); var fs = require('fs'); fs.exists('test.txt', function(exists) { assert.equal(exists, true); }); ``` ### fs.existsSync(path) * `path` {string} File path to be checked. * Returns: {boolean} True if the file exists, otherwise false. Checks the file specified by `path` exists synchronously. ```js var assert = require('assert'); var fs = require('fs'); var result = fs.existsSync('test.txt'); assert.equal(result, true); ``` ### fs.fstat(fd, callback) * `fd` {integer} File descriptor to be stated. * `callback` {Function} * `err` {Error|null} * `stat` {Object} An instance of `fs.Stats`. Get information about a file what specified by `fd` into `stat` asynchronously. **Example** ```js var assert = require('assert'); var fs = require('fs'); fs.open('test.txt', 'r', function(err, fd) { if (err) { throw err; } fs.fstat(fd, function(err, stat) { if (err) { throw err; } assert.equal(stat.isFile(), true); assert.equal(stat.isDirectory(), false); }); }); ``` ### fs.fstatSync(fd) * `fd` {integer} - File descriptor to be stated. * Returns: {Object} An instance of `fs.Stats`. Get information about a file what specified by `fd` synchronously. **Example** ```js var assert = require('assert'); var fs = require('fs'); fs.open('test.txt', 'r', function(err, fd) { if (err) { throw err; } var stat = fs.fstatSync(fd); assert.equal(stat.isFile(), true); assert.equal(stat.isDirectory(), false); }); ``` ### fs.mkdir(path[, mode], callback) * `path` {string} Path of the directory to be created. * `mode` {string|number} Permission mode. **Default:** `0777` * `callback` {Function} * `err` {Error|null} Creates the directory specified by `path` asynchronously. **Example** ```js var fs = require('fs'); fs.mkdir('testdir', function(err) { if (err) { throw err; } }); ``` ### fs.mkdirSync(path[, mode]) * `path` {string} Path of the directory to be created. * `mode` {string|number} Permission mode. **Default:** `0777` Creates the directory specified by `path` synchronously. **Example** ```js var fs = require('fs'); fs.mkdirSync('testdir'); ``` ### fs.open(path, flags[, mode], callback) * `path` {string} File path to be opened. * `flags` {string} Open flags. * `mode` {string|number} Permission mode. **Default:** `0666` * `callback` {Function} * `err` {Error|null} * `fd` {number} Opens file asynchronously. `flags` can be: * `r` Opens file for reading. Throws an exception if the file does not exist. * `rs` or `sr` Opens file for reading in synchronous mode. Throws an exception if the file does not exist. * `r+` Opens file for reading and writing. Throws an exception if the file does not exist. * `rs+` or `sr+` Opens file for reading and writing in synchronous mode. Throws an exception if the file does not exist. * `w` Opens file for writing. The file is overwritten if it exists. * `wx` or `xw` Opens file for writing. Throws an exception if it exists. * `w+` Opens file for reading and writing. The file is overwritten if it exists. * `wx+` or `xw+` Opens file for reading and writing. Throws an exception if it exists. * `a` Opens file for appending. The file is created if it does not exist. * `ax` or `xa` Opens file for appending. Throws an exception if it exists. * `a+` Opens file for reading and appending. The file is created if it does not exist. * `ax+` or `xa+` Opens file for reading and appending. Throws an exception if it exists. **Example** ```js var fs = require('fs'); fs.open('test.txt', 'r', 755, function(err, fd) { if (err) { throw err; } // do something }); ``` ### fs.openSync(path, flags[, mode]) * `path` {string} File path to be opened. * `flags` {string} Open flags. * `mode` {string|number} Permission mode. **Default:** `0666` * Returns: {number} File descriptor. Opens file synchronously. For available options of the `flags` see [fs.open()](#class-method-fsopenpath-flags-mode-callback). **Example** ```js var fs = require('fs'); var fd = fs.openSync('test.txt', 'r', 755); // do something ``` ### fs.read(fd, buffer, offset, length, position, callback) * `fd` {integer} File descriptor. * `buffer` {Buffer} Buffer that the data will be written to. * `offset` {number} Offset of the buffer where to start writing. * `length` {number} Number of bytes to read. * `position` {number} Specifying where to start read data from the file, if `null` or `undefined`, read from current position. * `callback` {Function} * `err` {Error|null} * `bytesRead` {number} * `buffer` {Buffer} Reads data from the file specified by `fd` asynchronously. **Example** ```js var fs = require('fs'); fs.open('test.txt', 'r', 755, function(err, fd) { if (err) { throw err; } var buffer = new Buffer(64); fs.read(fd, buffer, 0, buffer.length, 0, function(err, bytesRead, buffer) { if (err) { throw err; } }); }); ``` ### fs.readSync(fd, buffer, offset, length, position) * `fd` {integer} File descriptor. * `buffer` {Buffer} Buffer that the data will be written to. * `offset` {number} Offset of the buffer where to start writing. * `length` {number} Number of bytes to read. * `position` {number} Specifying where to start read data from the file, if `null` or `undefined`, read from current position. * Returns: {number} Number of read bytes. Reads data from the file specified by `fd` synchronously. **Example** ```js var fs = require('fs'); var buffer = new Buffer(16); var fd = fs.openSync('test.txt', 'r'); var bytesRead = fs.readSync(fd, buffer, 0, buffer.length, 0); ``` ### fs.readdir(path, callback) * `path` {string} Directory path to be checked. * `callback` {Function} * `err` {Error|null} * `files` {Object} Reads the contents of the directory specified by `path` asynchronously, `.` and `..` are excluded from `files`. **Example** ```js var fs = require('fs'); fs.readdir('testdir', function(err, items) { if (err) { throw err; } // prints: file1,file2,... from 'testdir' console.log(items); }); ``` ### fs.readdirSync(path) * `path` {string} Directory path to be checked. * Returns: {Object} Array of filenames. Reads the contents of the directory specified by `path` synchronously, `.` and `..` are excluded from filenames. **Example** ```js var fs = require('fs'); var items = fs.readdirSync('testdir'); // prints: file1,file2,... from 'testdir' console.log(items); ``` ### fs.readFile(path, callback) * `path` {string} File path to be opened. * `callback` {Function} * `err` {Error|null} * `data` {Buffer} Reads entire file asynchronously into `data`. **Example** ```js var fs = require('fs'); fs.readFile('test.txt', function(err, data) { if (err) { throw err; } // prints: the content of 'test.txt' console.log(data); }); ``` ### fs.readFileSync(path) * `path` {string} File path to be opened. * Returns: {Object} Contents of the file. Reads entire file synchronously. **Example** ```js var fs = require('fs'); var data = fs.readFileSync('test.txt'); ``` ### fs.rename(oldPath, newPath, callback) * `oldPath` {string} Old file path. * `newPath` {string} New file path. * `callback` {Function} * `err` {Error|null} Renames `oldPath` to `newPath` asynchronously. **Example** ```js var fs = require('fs'); fs.rename('test.txt', 'test.txt.async', function(err) { if (err) { throw err; } }); ``` ### fs.renameSync(oldPath, newPath) * `oldPath` {string} Old file path. * `newPath` {string} New file path. Renames `oldPath` to `newPath` synchronously. **Example** ```js var fs = require('fs'); fs.renameSync('test.txt', 'test.txt.sync'); ``` ### fs.rmdir(path, callback) * `path` {string} Directory path to be removed. * `callback` {Function} * `err` {Error|null} Removes the directory specified by `path` asynchronously. **Example** ```js var fs = require('fs'); fs.rmdir('testdir', function() { // do something }); ``` ### fs.rmdirSync(path) * `path` {string} Directory path to be removed. Removes the directory specified by `path` synchronously. ```js var fs = require('fs'); fs.rmdirSync('testdir'); ``` ### fs.stat(path, callback) * `path` {string} File path to be stated. * `callback` {Function} * `err` {Error|null} * `stat` {Object} Get information about a file into `stat` asynchronously. **Example** ```js var assert = require('assert'); var fs = require('fs'); fs.stat('test.txt', function(err, stat) { if (err) { throw err; } assert.equal(stat.isFile(), true); assert.equal(stat.isDirectory(), false); }); ``` ### fs.statSync(path) * `path` {string} File path to be stated. * Returns: {Object} An instance of `fs.Stats`. Get information about a file synchronously. **Example** ```js var assert = require('assert'); var fs = require('fs'); var stat = fs.statSync('test.txt'); assert.equal(stat.isFile(), true); assert.equal(stat.isDirectory(), false); ``` ### fs.unlink(path, callback) * `path` {string} File path to be removed. * `callback` {Function} * `err` {Error|null} Removes the file specified by `path` asynchronously. **Example** ```js var fs = require('fs'); fs.unlink('test.txt', function(err) { if (err) { throw err; } }); ``` ### fs.unlinkSync(path) * `path` {string} File path to be removed. Removes the file specified by `path` synchronously. **Example** ```js var fs = require('fs'); fs.unlinkSync('test.txt'); ``` ### fs.write(fd, buffer, offset, length[, position], callback) * `fd` {integer} File descriptor. * `buffer` {Buffer} Buffer that the data will be written from. * `offset` {number} Offset of the buffer where from start reading. * `length` {number} Number of bytes to write. * `position` {number} Specifying where to start write data to the file, if `null` or `undefined`, write at the current position. * `callback` {Function} * `err` {Error|null} * `bytesWrite` {integer} * `buffer` {Object} Writes `buffer` to the file specified by `fd` asynchronously. **Example** ```js var fs = require('fs'); var file = 'test.txt' var data = new Buffer('IoT.js'); fs.open(file, 'w', function(err, fd) { if (err) { throw err; } fs.write(fd, data, 0, data.length, function(err, bytesWrite, buffer) { if (err) { throw err; } // prints: 6 console.log(bytesWrite); // prints: IoT.js console.log(buffer); }); }); ``` ### fs.writeSync(fd, buffer, offset, length[, position]) * `fd` {integer} File descriptor. * `buffer` {Buffer} Buffer that the data will be written from. * `offset` {number} Offset of the buffer where from start reading. * `length` {number} Number of bytes to write. * `position` {number} Specifying where to start write data to the file, if `null` or `undefined`, write at the current position. * Returns: {number} Number of bytes written. Writes buffer to the file specified by `fd` synchronously. ```js var fs = require('fs'); var file = 'test.txt' var data = new Buffer('IoT.js'); var fd = fs.openSync(file, 'w'); var bytes = fs.writeSync(fd, data, 0, data.length); //prints: 6 console.log(bytes); ``` ### fs.writeFile(path, data, callback) * `path` {string} File path that the `data` will be written. * `data` {string|Buffer} String or buffer that contains data. * `callback` {Function} * `err` {Error|null} Writes entire `data` to the file specified by `path` asynchronously. **Example** ```js var fs = require('fs'); fs.writeFile('test.txt', 'IoT.js', function(err) { if (err) { throw err; } }); ``` ### fs.writeFileSync(path, data) * `path` {string} File path that the `data` will be written. * `data` {string|Buffer} String or buffer that contains data. Writes entire `data` to the file specified by `path` synchronously. **Example** ```js var fs = require('fs'); fs.writeFileSync('test.txt', 'IoT.js'); ``` iotjs-1.0+715/docs/api/IoT.js-API-GPIO.md000066400000000000000000000135201371177304000173120ustar00rootroot00000000000000### Platform Support The following shows GPIO module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | gpio.open | X | O | O | O | O | | gpio.openSync | X | O | O | O | O | | gpiopin.setDirectionSync | X | O | O | O | O | | gpiopin.write | X | O | O | O | O | | gpiopin.writeSync | X | O | O | O | O | | gpiopin.read | X | O | O | O | O | | gpiopin.readSync | X | O | O | O | O | | gpiopin.close | X | O | O | O | O | | gpiopin.closeSync | X | O | O | O | O | # GPIO The GPIO module provides access the General Purpose Input Output pins of the hardware. On Linux each pin has a logical number starting from `1`. The logical number might be different from the physical pin number of the board. The mapping is available in the documentation of a given board. * On Tizen, the pin number is defined in [this documentation](../targets/tizen/SystemIO-Pin-Information-Tizen.md#gpio). * On NuttX, the pin number is defined in the documentation of the target board. For more information, please check the following list: [STM32F4-discovery](../targets/nuttx/stm32f4dis/IoT.js-API-Stm32f4dis.md#gpio-pin) ### DIRECTION * `IN` Input pin. * `OUT` Output pin. An enumeration which can be used to specify the direction of the pin. ### MODE * `NONE` None. * `PULLUP` Pull-up (pin direction must be [`IN`](#direction)). * `PULLDOWN` Pull-down (pin direction must be [`IN`](#direction)). * `FLOAT` Float (pin direction must be [`OUT`](#direction)). * `PUSHPULL` Push-pull (pin direction must be [`OUT`](#direction)). * `OPENDRAIN` Open drain (pin direction must be [`OUT`](#direction)). An enumeration which can be used to specify the mode of the pin. These options are only supported on NuttX. ### EDGE * `NONE` None. * `RISING` Rising. * `FALLING` Falling. * `BOTH` Both. An enumeration which can be used to specify the edge of the pin. ### gpio.open(configuration, callback) * `configuration` {Object} Configuration for open GPIOPin. * `pin` {number} Pin number. Mandatory field. * `direction` {[gpio.DIRECTION](#direction)} Pin direction. **Default:** `gpio.DIRECTION.OUT` * `mode` {[gpio.MODE](#mode)} Pin mode. **Default:** `gpio.MODE.NONE` * `edge` {[gpio.EDGE](#edge)} Pin edge. **Default:** `gpio.EDGE.NONE` * `callback` {Function} * `error` {Error|null} * `gpioPin` {Object} An instance of GPIOPin. * Returns: {Object} An instance of GPIOPin. Get GPIOPin object with configuration asynchronously. The `callback` function will be called after opening is completed. The `error` argument is an `Error` object on failure or `null` otherwise. **Example** ```js var gpio = require('gpio'); var gpio10 = gpio.open({ pin: 10, direction: gpio.DIRECTION.OUT, mode: gpio.MODE.PUSHPULL, edge: gpio.EDGE.RISING }, function(err, pin) { if (err) { throw err; } }); ``` ### gpio.openSync(configuration) * `configuration` {Object} Configuration for open GPIOPin. * `pin` {number} Pin number. Mandatory field. * `direction` {[gpio.DIRECTION](#direction)} Pin direction. **Default:** `gpio.DIRECTION.OUT` * `mode` {[gpio.MODE](#mode)} Pin mode. **Default:** `gpio.MODE.NONE` * `edge` {[gpio.EDGE](#edge)} Pin edge. **Default:** `gpio.EDGE.NONE` * Returns: {Object} An instance of GPIOPin. Get GPIOPin object with configuration synchronously. **Example** ```js var gpio = require('gpio'); var gpio10 = gpio.openSync({ pin: 10, direction: gpio.DIRECTION.IN, mode: gpio.MODE.PULLUP }); ``` ## Class: GPIOPin This class represents an opened and configured GPIO pin. It allows getting and setting the status of the pin. ### gpiopin.setDirectionSync(direction) * `direction` {[gpio.DIRECTION](#direction)} Pin direction. Set the direction of a GPIO pin. **Example** ```js gpio10.setDirectionSync(gpio.DIRECTION.OUT); gpio10.writeSync(1); gpio10.setDirectionSync(gpio.DIRECTION.IN); var value = gpio10.readSync(); ``` ### gpiopin.write(value[, callback]) * `value` {number|boolean} * `callback` {Function} * `error` {Error|null} Asynchronously writes out a boolean `value` to a GPIO pin (a number `value` is converted to boolean first). The optional `callback` function will be called after the write is completed. The `error` argument is an `Error` object on failure or `null` otherwise. **Example** ```js gpio10.write(1, function(err) { if (err) { throw err; } }); ``` ### gpiopin.writeSync(value) * `value` {number|boolean} Writes out a boolean `value` to a GPIO pin synchronously (a number `value` is converted to boolean first). **Example** ```js gpio10.writeSync(1); ``` ### gpiopin.read([callback]) * `callback` {Function} * `error` {Error|null} * `value` {boolean} Asynchronously reads a boolean value from a GPIO pin. The optional `callback` function will be called after the read is completed. The `error` argument is an `Error` object on failure or `null` otherwise. The `value` argument contains the boolean value of the pin. **Example** ```js gpio10.read(function(err, value) { if (err) { throw err; } console.log('value:', value); }); ``` ### gpiopin.readSync() * Returns: {boolean} Returns the boolean value of a GPIO pin. **Example** ```js console.log('value:', gpio10.readSync()); ``` ### gpiopin.close([callback]) * `callback` {Function} * `error` {Error|null} Asynchronously closes a GPIO pin. The optional `callback` function will be called after the close is completed. The `error` argument is an `Error` object on failure or `null` otherwise. **Example** ```js gpio10.close(function(err) { if (err) { throw err; } // prints: gpio pin is closed console.log('gpio pin is closed'); }); ``` ### gpiopin.closeSync() Synchronously closes a GPIO pin. **Example** ```js gpio10.closeSync(); // prints: gpio pin is closed console.log('gpio pin is closed'); ``` iotjs-1.0+715/docs/api/IoT.js-API-HTTP-Signature.md000066400000000000000000000027441371177304000213000ustar00rootroot00000000000000### Platform Support The following chart shows the availability of each HTTP Signature module API function on each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | Nuttx
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | httpSignature.parseRequest | O | O | O | O | O | | httpSignature.verify | O | O | O | O | O | # HTTP Signature The module makes it possible to verify the signature on HTTP Requests as stated in the RFC Standard (https://tools.ietf.org/html/draft-cavage-http-signatures-10). ### httpSignature.parseRequest(request) Parses an `HTTP request` and returns with the parsed object. - `request` {Object} A valid `HTTP Request` The returned object can be used to later to `verify` the `signature` of the `request`. ### httpSignature.verify(parsedRequest, publicKey) Verifies the `parsedRequest`'s `signature` against the given `publicKey`. Returns `true` if the verification succeeds, `false` otherwise. - `parsedRequest` {Object} An `HTTP Request` parsed by `httpSignature.parseRequest()` function. - `publicKey` {Buffer | string} The RSA Public key. **Example** ```js var httpSign = require('http_signature'); ... function myHTTPListener(req, res) { var parsedRequest = httpSign.parseRequest(req); if (!httpSign.verify(parsedRequest)) // Verification failed return res.send(401); } // Signature is OK, handle the request normally requestHandler(req, res); } ``` iotjs-1.0+715/docs/api/IoT.js-API-HTTP.md000066400000000000000000000520541371177304000173400ustar00rootroot00000000000000### Platform Support The following shows Http module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :--- | :---: | :---: | :---: | :---: | :---: | | http.createServer | O | O | O | △ ¹ | △ ¹ | | http.request | O | O | O | △ ¹ | △ ¹ | | http.get | O | O | O | △ ¹ | △ ¹ | | http.METHODS | O | O | O | O | O | | http.Server | O | O | O | △ ¹ | △ ¹ | | http.Server.close | O | O | O | △ ¹ | △ ¹ | | http.Server.listen | O | O | O | △ ¹ | △ ¹ | | http.Server.setTimeout | O | O | O | △ ¹ | △ ¹ | | http.ClientRequest | O | O | O | △ ¹ | △ ¹ | | http.ClientRequest.abort | O | O | O | △ ¹ | △ ¹ | | http.ClientRequest.end | O | O | O | △ ¹ | △ ¹ | | http.ClientRequest.setTimeout | O | O | O | △ ¹ | △ ¹ | | http.ClientRequest.write | O | O | O | △ ¹ | △ ¹ | | http.IncomingMessage | O | O | O | △ ¹ | △ ¹ | | http.IncomingMessage.headers | O | O | O | △ ¹ | △ ¹ | | http.IncomingMessage.method | O | O | O | △ ¹ | △ ¹ | | http.IncomingMessage.httpVersion | O | O | O | △ ¹ | △ ¹ | | http.IncomingMessage.socket | O | O | O | △ ¹ | △ ¹ | | http.IncomingMessage.statusCode | O | O | O | △ ¹ | △ ¹ | | http.IncomingMessage.url | O | O | O | △ ¹ | △ ¹ | | http.IncomingMessage.statusMessage | O | O | O | △ ¹ | △ ¹ | | http.IncomingMessage.setTimeout | O | O | O | △ ¹ | △ ¹ | | http.ServerResponse | O | O | O | △ ¹ | △ ¹ | | http.ServerResponse.end | O | O | O | △ ¹ | △ ¹ | | http.ServerResponse.getHeader | O | O | O | △ ¹ | △ ¹ | | http.ServerResponse.setHeader | O | O | O | △ ¹ | △ ¹ | | http.ServerResponse.setTimeout | O | O | O | △ ¹ | △ ¹ | | http.ServerResponse.write | O | O | O | △ ¹ | △ ¹ | | http.ServerResponse.writeHead | O | O | O | △ ¹ | △ ¹ | 1. On NuttX/STM32F4-Discovery and TizenRT/Artik053, even a couple of sockets/server/requests might not work properly. # Http IoT.js provides HTTP to support HTTP server and client enabling users to receive/send HTTP request easily. ### http.createServer([options][, requestListener]) * `options` {Object} * `IncomingMessage` {Function} Specifies the `IncomingMessage` constructor to be used when creating an http incoming message object. Useful when extending the original {http.IncommingMessge}. Default: `http.IncommingMessage`. * `ServerResponse` {Function} Specifies the `ServerResponse` constructor to be used when creating the server response object. Useful when extending the original {http.ServerResponse}. Default: 'http.ServerResponse`. * `requestListener` {Function} * `request` {http.IncomingMessage} * `response` {http.ServerResponse} * Returns: {http.Server} This call only creates the HTTP server instance and does not start the server. To start the server and listen for connections use the `server.listen` method. If a server is no longer needed, all request and response streams should be closed and the `server.close` method should be used to stop the server listening for connections. The `requestListener` is a function which is automatically added to the `'request'` event of the http server. **Example** ```js var console = require('console'); var http = require('http'); var server = http.createServer(function(request, response) { console.log('Request for path: ' + request.url); var message = '

Hello

'; response.setHeader('Content-Type', 'text/html'); response.setHeader('Content-Length', message.length); response.writeHead(200); response.write(message); response.end(); }); var port = 8081 server.listen(port, function() { console.log('HTTP server listening on port: ' + port); }); ``` ### http.request(options[, callback]) * `options` {Object} * `host` {string} A domain name or IP address of the server to issue the request to. Defaults to 'localhost'. * `hostname` {string} Alias for host. * `port` {number} Port of remote server. Defaults to 80. * `method` {string} A string specifying the HTTP request method. Defaults to 'GET'. * `path` {string} Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. * `headers` {Object} An object containing request headers. * `callback` {Function} * `response` {http.IncomingMessage} * Returns: {http.ClientRequest} The function creates a `http.ClientRequest` instance with the `options` defined. This can be used to get data from a server or to send data for a server. In case of data send the `'Content-Length'` header should be specifed so the server can properly handle the request. **Example** ```js var http = require('http'); var data_A = 'Data to upload..'; var data_B = 'more data'; var request = http.request({ method: 'POST', port: 8081, headers: { 'Content-Length': data_A.length + data_B.length } }); request.write(data_A); request.write(data_B); request.end(); ``` Note that in the example `request.end()` was called. With `http.request()` one must always call `request.end()` to signify that you're done with the request - even if there is no data being written to the request body. ### http.get(options[, callback]) * `options` {Object} * `callback` {Function} * `response` {http.IncomingMessage} * Returns: {http.ClientRequest} Same as `http.request` except that `http.get` automatically calls `request.end()` before returning the `http.ClientRequest` instance thus calling the `write` method on the return value is invalid. This method is usefuly when there is no HTTP body to send. **Example** ```js var http = require('http'); http.get({ port: 80, }, function(response) { console.log('Got response'); response.on('data', function(chunk) { console.log('Chunk: '); console.log(chunk.toString()); }); }); ``` ### http.METHODS * {string[]} A list of HTTP methods supported by the parser as a `string` array. ## Class: http.Server This class inherits from `net.Server` and represents a HTTP server. ### Event: 'clientError' Event callback arguments: * `exception` {Error} Describes what kind of error occured. * `socket` {net.Socket} The socket which triggered the error. If a client connection emits an 'error' event, it will be forwarded here. Listener of this event is responsible for closing/destroying the underlying socket. Default behavior is to destroy the socket immediately on malformed request. **Example** ```js var http = require('http'); var server = http.createServer(function(req, res) { res.end(); }); server.on('clientError', function(err, socket) { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); }); server.listen(8000); ``` ### Event: 'close' This event is emitted when the HTTP server is closed. **Example** ```js var console = require('console'); var http = require('http'); var server = http.createServer(); server.on('close', function() { console.log('Server closed'); }); server.listen(8081, function() { console.log('HTTP server listening'); server.close(); }); ``` When the example is executed the following will text will be printed: ``` HTTP server listening Server closed ``` ### Event: 'connection' Event callback argument: * `socket` {net.Socket} This event is emitted when new TCP connection is established. This event is triggered before the `request` event. At this stage no HTTP header or data is processed. Usually there is no need to listen for this event. ### Event: 'request' * `request` {http.IncomingMessage} Represents the HTTP request sent by the client. * `response` {http.ServerResponse} Represents the HTTP response which will be sent by the server. After HTTP request headers are parsed, the `'request'` event will be fired. **Example** ```js var console = require('console'); var http = require('http'); var server = http.createServer(); server.on('request', function(request, response) { console.log('Request for path: ' + request.url); var message = '

Hello

'; response.setHeader('Content-Type', 'text/html'); response.setHeader('Content-Length', message.length); response.writeHead(200); response.write(message); response.end(); }); var port = 8081 server.listen(port, function() { console.log('HTTP server listening on port: ' + port); }); ``` ### server.timeout * {number} The number of milliseconds of inactivity before a socket is presumed to have timed out. Default value is 120000 (2 minutes). ### server.listen(port[, hostname][, backlog][, callback]) * `port` {number} Port number to listen on. * `host` {string} Host IP or name where the server should listen. Default: `'0.0.0.0'`. * `backlog` {number} The number of maximum pending connections. Default backlog length is 511 (not 512). * `callback` {Function} Callback called when the `'listening'` event is emitted by the underlying `net.Server`. * Returns {http.Server} The same server instance which was used to call the `listen` method. Wait for new TCP connections with specified port and hostname. If no hostname is provided, server listens on all available IP address. **Example** ```js var console = require('console'); var http = require('http'); var server = http.createServer(function(req, res) { res.end(); }); server.listen(8080, function() { console.log('Started listening'); }); ``` ### server.close([callback]) * `callback` {Function} Function which to be registered for the `'close'` event. * Returns {http.Server} The same server instance which was used to call the `close` method. Stop accepting new connections to this server. However, the existing connections are preserved. When the server is finally closed after all connections was closed, the `'close'` event is triggered. See the `'close`' event. ### server.setTimeout(ms[, callback]) * `ms` {number} * `callback` {Function} The callback function registered for the `'timeout'` event. Registers cb for `'timeout'` event and sets socket's timeout value to ms. This event will be triggered by the underlying socket's `'timeout'` event. If `callback` is not provided, the socket will be destroyed automatically after timeout. If the `callback` function is provided, that function should should handle the socket's timeout. Default timeout for server is 2 minutes. **Example** ```js var http = require('http'); var server = http.createServer(); server.setTimeout(100, function(socket) { socket.destroy(); server.close(); }); ``` ## Class: http.ClientRequest This object is created internally and returned from `http.request()`. It represents an in-progress request whose headers have already been queued. ### Event: 'close' This event is fired when the underlying socket is closed. ### Event: 'error' Event callback arguments: * `err` {Error} Emitted if something went wrong with making or parsing the request. ### Event: 'finish' This event is emitted after all the data was sent, meaning header and body all finished sending. ### Event: 'response' Event callback arguments: * `response` {http.IncomingMessage} The incoming HTTP response from the server. This event is emitted when server's HTTP response header is parsed. The event is called only once. The developer should attach at least one event handler for this event to correctly process any data sent back by the target server. **Example** ```js var http = require('http'); var options = { host: 'localhost', port: 8081, method: 'GET', }; var client_request = http.request(options); client_request.on('response', function(response) { console.log('HTTP status: ' + response.statusCode); console.log('Headers:'); console.log(response.headers); response.on('data', function(chunk) { console.log(chunk.toString()); }); }); client_request.end(); ``` ### Event: 'socket' Event callback arguments: * `socket` {net.Socket} This event is emitted when a socket is assigned to this request. After response header is parsed, this event will be fired. ### request.abort() Will abort the outgoing request, dropping any data to be sent/received and destroying the underlying socket. ### request.end([data][, callback]) * `data` {Buffer | string} Data to be sent. * `callback` {Function} Callback function invoked when all data is processed. Finishes sending the request. If `data` is provided, it sends `data` first, and finishes. If `callback` is specified, it is called when the request stream is finished. This method must be called to close the request and to make sure all data is sent. **Example** ```js var http = require('http'); var message = 'HTTP Body POST Data'; var options = { host: 'localhost', port: 8081, method: 'POST', headers: {'Content-Length': message.length}, }; var client_request = http.request(options, function(response) { console.log('HTTP status: ' + response.statusCode); }); client_request.end(message); ``` ### request.setTimeout(ms[, callback]) * `ms` {number} * `callback` {Function} The callback function registered for the `'timeout'` event. Registers `callback` for 'timeout' event and set socket's timeout value to ms. This event will be triggered by the underlying socket's `'timeout'` event. If `callback` is not provided, the socket will be destroyed automatically after timeout. If `callback` is provied, the method should handle the socket's timeout. ### request.write(data[, callback]) * `data` {Buffer | string} Data to be sent. * `callback` {Function} Sends `data` as a request body. `callback` will be called when data is flushed. **Example** ```js var http = require('http'); var message = "This is the data"; var options = { method: 'POST', port: 8383, path: '/', headers: {'Content-Length': message.length}, }; var client_request = http.request(options); client_request.write(message); client_request.end(); ``` ## Class: http.IncomingMessage This object is created internally and returned to the callback for the http.ClientRequest `'response'` event and for the `'request'` event in the http.Server class. In case of the `http.ClientRequest` class this `IncomingMessage` will represent the response sent by a server for the given request. In case of the `http.Server` class this will represent the request sent by a client for the server. http.IncomingMessage inherits [`Stream.readable`](IoT.js-API-Stream.md). See it's documentation to read incoming data from an HTTP request. Notable events are `'data'` (fired when there is data to read), `'close'`, `'end'` (Request has ended) and the method `readable.read()`. ### Event: 'close' When underlying connection is closed, 'close' event is emitted. ### Event: 'data' Event callback arguments: * `chunk` {Buffer} the buffer containing the data. Raised when there is data to be processed from the underlying socket. It is highly possible that this chunk of data is not the whole data, thus if the developer needs the whole data in one, each chunk must be stored. (See the example for a naive approach.) The HTTP headers are already parsed before this event is triggered. Please note that the total size of the data could be bigger than the memory available on the device where the code is running. **Example** ```js var console = require('console'); var http = require('http'); var options = { host: 'localhost', port: 8081, method: 'GET', path: '/' }; var client_request = http.request(options, function(response) { var parts = []; response.on('data', function(chunk) { parts.push(chunk); }); response.on('end', function() { var body = Buffer.concat(parts); console.log(body.toString()); }); }); client_request.end(); ``` ### Event: 'end' This event is fired when no more data to be received. At this point it is safe to assume all data was received from the other end. ### message.headers A JavaScript object containing all HTTP headers sent by the other end. ### message.method Requests method as `string` ### message.httpVersion The HTTP version sent by the client. One of the following value: `'1.1'` or `'1.0'`. ### message.socket Underlying network socket (`net.Socket`). ### message.statusCode HTTP response status code as `number` of 3-digit. ### message.url Request URL as `string`. Only contains the URL present in the HTTP request. Note: only valid if the `IncomingMessage` was constructed by a `http.Server`. **Example** If the HTTP request is the following: ``` GET /page/1?data=a HTTP/1.1 \r\n Accept: text/html\r\n \r\n ``` the `message.url` will be: `/page/1?data=a`. ### message.statusMessage HTTP response status message as `string`. ### message.setTimeout(ms, cb) * `ms` {number} * `cb` {Function} Registers cb for 'timeout' event set socket's timeout value to ms. This event will be triggered by the underlying socket's 'timeout' event. ## Class: http.ServerResponse Created internally when the `'request'` event is triggered by the `http.Server` class and represents the response sent by the server to a client. ### Event: 'close' When underlying connection is closed, 'close' event is emitted. ### Event: 'end' This event is fired when no more data to be sent. ### Event: 'finish' This event is emitted when the response has been sent. It does not guarantee that client has received data yet. ### response.end([data][, callback]) * `data` {Buffer | string} Data which should be sent. * `callback` {Function} Finishes sending the response. If `data` is provided, it sends `data` first, and finishes. If `callback` is specified, it is called when the response stream is finished. The method should be called to correctly finish up a response. Any method which sets headers must be called before this method and before any `write` calls. **Example** ```js var console = require('console'); var http = require('http'); var server = http.createServer(function(request, response) { console.log('Request for path: ' + request.url); var message = '

Hello

'; response.setHeader('Content-Type', 'text/html'); response.setHeader('Content-Length', message.length); response.writeHead(200); response.end(message); }); var port = 8081 server.listen(port, function() { console.log('HTTP server listening on port: ' + port); }); ``` ### response.getHeader(name) * `name` {string} Case-sensitive HTTP header field name. Returns the value of the `name` HTTP header field. ### response.removeHeader(name) * `name` {string} Case-sensitive HTTP header field name. Remove the HTTP header which has the `name` field name. HTTP headers can not be modified after the first `write`, `writeHead` or `end` method call. ### response.setHeader(name, value) * `name` {string} The name of the HTTP header field to set. * `value` {string} The value of the field. Sets response's header field(`name`) to `value`. If the field exists, it overwrites the existing value. HTTP headers can not be modified after the first `write`, `writeHead` or `end` method call. ### response.setTimeout(ms, cb) * `ms` {number} * `cb` {Function} Registers cb for 'timeout' event and set socket's timeout value to ms. This event will be triggered by the underlying socket's 'timeout' event. ### response.write(data[, callback]) * `data` {Buffer | string} * `callback` {Function} Sends `data` as a response body. `callback` will be called when data is flushed. It is advised to set at least the `Content-Length` HTTP header field correctly before any `write` calls. This is so the client could properly handle the server response. After a `write` method was called there is no possibility to change any headers. **Example** ```js var console = require('console'); var http = require('http'); var server = http.createServer(function(request, response) { console.log('Request for path: ' + request.url); var message = '

Hello

'; response.setHeader('Content-Type', 'text/html'); response.setHeader('Content-Length', message.length); response.writeHead(200); response.write(message); response.end(); }); var port = 8081 server.listen(port, function() { console.log('HTTP server listening on port: ' + port); }); ``` ### response.writeHead(statusCode[, statusMessage][, headers]) * `statusCode` {number} * `statusMessage` {string} Optional. If not set the HTTP status message will be inferred from the status code. * `headers` {Object} Optional. An object containing HTTP header field names and values. Sets response status code, the status message and configures a set of HTTP header values. **Example** ```js var console = require('console'); var http = require('http'); var server = http.createServer(function(request, response) { console.log('Request for path: ' + request.url); var message = '

Hello

'; response.writeHead(200, 'OK', { 'Content-Type': 'text/html', 'Content-Length': message.length, }); response.write(message); response.end(); }); var port = 8081 server.listen(port, function() { console.log('HTTP server listening on port: ' + port); }); ``` iotjs-1.0+715/docs/api/IoT.js-API-HTTPS.md000066400000000000000000000113041371177304000174540ustar00rootroot00000000000000### Platform Support The following shows Https module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | https.createServer | O | O | O | △ ¹ | △ ¹ | | https.request | O | O | O | △ ¹ | △ ¹ | | https.get | O | O | O | △ ¹ | △ ¹ | 1. On NuttX/STM32F4-Discovery and TizenRT/Artik053, even a couple of sockets/server/requests might not work properly. # Https IoT.js provides HTTPS to support HTTPS clients enabling users to send HTTPS requests easily. ### https.createServer([options][, requestListener]) * `options` {Object} Accepts the same `options` as [tls.createServer](IoT.js-API-TLS.md#tlscreateserveroptions-secureconnectionlistener) and [http.createServer](IoT.js-API-HTTP.md#httpcreateserverrequestlistener) methods. * `requestListener` {Function} * request {http.IncomingMessage} * response {http.ServerResponse} * Returns: {https.Server} To create a server the certificates should be specified via the `options` object. The `requestListener` is a function which is automatically added to the `'request'` event. **Example** ```js var options = { key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.cert') }; var server = https.createServer(options, function(request, response) { ... }); ``` ### https.request(options[, callback]) * `options` {Object} * `host` {string} A domain name or IP address of the server to issue the request to. **Default:** 'localhost'. * `hostname` {string} Alias for host. * `port` {number} Port of remote server. **Default:** 443. * `method` {string} A string specifying the HTTPS request method. **Default:** 'GET'. * `path` {string} Request path. **Default:** '/'. Should include query string if any. E.G. '/index.html?page=12'. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. * `headers` {Object} An object containing request headers. * `auth` {string} Optional Basic Authentication in the form `username:password`. Used to compute HTTPS Basic Authentication header. * `ca` {string} Optional file path to CA certificate. Allows to override system trusted CA certificates. * `cert` {string} Optional file path to client authentication certificate in PEM format. * `key` {string} Optional file path to private keys for client cert in PEM format. * `rejectUnauthorized` {boolean} Optional Specify whether to verify the Server's certificate against CA certificates. WARNING - Making this `false` may be a security risk. **Default:** `true` * `callback` {Function} * `response` {http.IncomingMessage} * Returns: {http.ClientRequest} Example: ```javascript var https = require('https'); var request = https.request({ method: 'POST', port: 443, headers: {'Content-Length': 3} }); ... request.end(); ``` Note that in the example `req.end()` was called. With `https.request()` one must always call `req.end()` to signify that you're done with the request - even if there is no data being written to the request body. ### https.get(options[, callback]) * `options` {Object} * `host` {string} A domain name or IP address of the server to issue the request to. **Default:** 'localhost'. * `hostname` {string} Alias for host. * `port` {number} Port of remote server. **Default:** 443. * `method` {string} A string specifying the HTTPS request method. **Default:** 'GET'. * `path` {string} Request path. **Default:** '/'. Should include query string if any. E.G. '/index.html?page=12'. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. * `headers` {Object} An object containing request headers. * `auth` {string} Optional Basic Authentication in the form `username:password`. Used to compute HTTPS Basic Authentication header. * `ca` {string} Optional file path to CA certificate. Allows to override system trusted CA certificates. * `cert` {string} Optional file path to client authentication certificate in PEM format. * `key` {string} Optional file path to private keys for client cert in PEM format. * `rejectUnauthorized` {boolean} Optional Specify whether to verify the Server's certificate against CA certificates. WARNING - Making this `false` may be a security risk. **Default:** `true` * `callback` {Function} * `response` {http.IncomingMessage} * Returns: {http.ClientRequest} Same as `https.request` except that `https.get` automatically call `req.end()` at the end. Example: ```javascript var https = require('https'); https.get({ port: 443, }, function(res) { ... }); ``` iotjs-1.0+715/docs/api/IoT.js-API-I2C.md000066400000000000000000000072141371177304000171340ustar00rootroot00000000000000## Platform Support The following shows I2C module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | i2c.open | X | O | O | O | O | | i2c.openSync | X | O | O | O | O | | i2cbus.read | X | O | O | O | O | | i2cbus.readSync | X | O | O | O | O | | i2cbus.write | X | O | O | O | O | | i2cbus.writeSync | X | O | O | O | O | | i2cbus.close | X | O | O | O | O | | i2cbus.closeSync | X | O | O | O | O | # I2C The I2C module supports the I2C protocol. I2C bus has two signals - SDA and SCL. * On Tizen, the bus number is defined in [this documentation](../targets/tizen/SystemIO-Pin-Information-Tizen.md#i2c). ### i2c.open(configuration, callback) * `configuration` {Object} Configuration for open I2CBus. * `device` {string} Device path. (only on Linux) * `bus` {number} The specified bus number. (Tizen, TizenRT and NuttX only) * `address` {number} Device address. * `callback` {Function} * `err` {Error|null} * `i2cBus` {Object} An instance of I2CBus. * Returns: {Object} An instance of I2CBus. Get I2CBus object with configuration asynchronously. **Example** ```js var i2c = require('i2c'); i2c.open({device: '/dev/i2c-1', address: 0x23}, function(err, wire) { if (err) { throw err; } }); ``` ### i2c.openSync(configuration) * `configuration` {Object} Configuration for open I2CBus. * `device` {string} Device path. (only on Linux) * `bus` {number} The specified bus number. (Tizen, TizenRT and NuttX only) * `address` {number} Device address. * Returns: {Object} An instance of I2CBus. Get I2CBus object with configuration synchronously. **Example** ```js var i2c = require('i2c'); var wire = i2c.openSync({device: '/dev/i2c-1', address: 0x23}); ``` ## Class: I2CBus ### i2cbus.read(length[, callback]) * `length` {number} Number of bytes to read. * `callback` {Function} * `err` {Error|null} * `res` {Array} Array of bytes. Read bytes from I2C device asynchronously. **Example** ```js var i2c = require('i2c'); i2c.open({device: '/dev/i2c-1', address: 0x23}, function(err, wire) { wire.read(2, function(err, res) { if (!err) { console.log('read result: ' + res); } }); }); ``` ### i2cbus.readSync(length) * `length` {number} Number of bytes to read. * Returns: {Array} Array of bytes. Read bytes from I2C device synchronously. **Example** ```js var i2c = require('i2c'); var wire = i2c.openSync({device: '/dev/i2c-1', address: 0x23}); var res = wire.readSync(2); console.log(res); ``` ### i2cbus.write(bytes[, callback]) * `bytes` {Array} Array of bytes to write. * `callback` {Function} * `err` {Error|null} Write bytes to I2C device asynchronously. **Example** ```js var i2c = require('i2c'); i2c.open({device: '/dev/i2c-1', address: 0x23}, function(err, wire){ wire.write([0x10], function(err) { if(!err) { console.log('write done'); } }); }); ``` ### i2cbus.writeSync(bytes) * `bytes` {Array} Array of bytes to write. Write bytes to I2C device synchronously. **Example** ```js var i2c = require('i2c'); var wire = i2c.openSync({device: '/dev/i2c-1', address: 0x23}); wire.writeSync([0x10]); ``` ### i2cbus.close([callback]) * `callback` {Function} * `err` {Error|null} Close I2C device asynchronously. **Example** ```js var i2c = require('i2c'); i2c.open({device: '/dev/i2c-1', address: 0x23}, function(err, wire) { wire.close(); }); ``` ### i2cbus.closeSync() Close I2C device synchronously. **Example** ```js var i2c = require('i2c'); var wire = i2c.openSync({device: '/dev/i2c-1', address: 0x23}); wire.closeSync(); ```iotjs-1.0+715/docs/api/IoT.js-API-MQTT.md000066400000000000000000000160351371177304000173450ustar00rootroot00000000000000### Platform Support The following chart shows the availability of each MQTT module API function on each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | Nuttx
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | mqtt.connect | O | O | O | X | O | | mqtt.end | O | O | O | X | O | | mqtt.publish | O | O | O | X | O | | mqtt.subscribe | O | O | O | X | O | | mqtt.unsubscribe | O | O | O | X | O | # MQTT MQTT is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium. ### QoS The QoS level can be 0, 1 or 2. - Level 0 means the packet arrives at most once. - Level 1 means the packet arrives at least once (duplications might occur, it is the user's responsibility to take care of them). - Level 2 means that the package is delivered exactly once. ### Topic separating and wildcarding Topics can be wildcarded and they also can be structured into multiple levels. These levels are divided by the `/` sign (eg. `iotjs/jerryscript/jerry-core`). There are multiple wildcarding possibilities: - `Multi-level wildcard` The `#` sign is a wildcard character that matches any number of levels within a topic. This character MUST be the last character in a topic name. Typing `iotjs/#` means the client subscribes to anything that is under the `iotjs` topic. - `Single-level wildcard` The `+` sign is a wildcard character that matches only one topic level. It can be used more at than one level in the topic name. It MUST be used so it occupies an entire level of the name. Typing `iotjs/+/jerry-core` subscribes you to `jerry-core` topic. - Topics that are beginning with `$` can not be matched with wildcard filters such as `#` or `+`. Subscriptions with wildcards to these topics means that they receive no data at all. ## Class: MQTTClient The `MQTTClient` can subscribe or publish data to a broker. It sends data over a `net.socket`. ### mqtt.connect([url], [options], [callback]) - `url` {string} host name optionally prefixed by `mqtt://` or `mqtts://`. - `options` {Object} - `clientId` {Buffer | string} Optional. The broker identifies each client by its `clientId`. If not specified, a randomly generated `clientId` is created. - `host` {Buffer | string} The address of the broker. - `port` {number} The port of the broker. - `socket` {net.Socket | TLSSocket} If a `TLSSocket` is given for secure communication it is the user's responsibility to connect it to establish the TLS connection first. Otherwise the client automatically connects the socket to the server. - `username` {Buffer | string} Optional. Use username when connecting to a broker. - `password` {Buffer | string} Optional. Use password authentication when connecting to a broker. - `keepalive` {number} Keepalive time in seconds. If no data is sent on the connection in the given time window the broker disconnects the client. - `will` {boolean} Optional. If this flag is set to `true`, a `message` and a `topic` must follow with a QoS value between 0 and 2. - `qos` {number} If `will` is set to `true`, the message will be sent with the given QoS. - `topic` {Buffer | string} Only processed when `will` is set to `true`. The topic the `message` should be sent to. - `message` {Buffer | string} Only processed when `will` is set to `true`. The message to be sent to the broker when connecting. - `callback` {function} the function which will be executed when the client successfully connected to the broker. Returns with an MQTTClient object and starts connecting to a broker. Emits a `connect` event after the connection is completed. **Example** ```js var mqtt = require('mqtt'); var opts = { port: 443, keepalive: 10, clientId: 'IoT.js Client', } var client = mqtt.connect('mqtt://127.0.0.1', opts, function () { client.end(); }); ``` ### mqtt.end([force]) - `force` {boolean} force network connection abort Disconnects the client from the broker. ### mqtt.subscribe(topic, [options], [callback]) - `topic` {Buffer | string} topic to subscribe to - `options` {Object} - `qos` {number} Optional. Defaults to 0. - `retain` {boolean} Optional. If retain is `true` the client receives the messages that were sent to the desired `topic` before it connected. Defaults to `false`. - `callback` {function} the function which will be executed when the subscribe is completed. The client subscribes to a given `topic`. If there are messages available on the `topic` the client emits a `data` event with the message received from the broker. **Example** ```js var mqtt = require('mqtt'); var opts = { host: '127.0.0.1', port: 443, keepalive: 10, clientId: 'IoT.js Client', } var subscribe_opts = { retain: false, qos: 2 } var client = mqtt.connect(opts, function () { client.subscribe('hello/#/iotjs', subscribe_opts, function(error) { if (error) { console.log('Subscribe is failed'); } else { console.log('Subscribe is successfully completed'); } }); }); client.on('message', function(data) { console.log('I received something: ' + data.message.toString()); }); ``` ### mqtt.unsubscribe(topic, [callback]) - `topic` {Buffer | string} topic to unsubscribe from - `callback` {function} the function which will be executed when the unsubscribe is completed. Unsubscribes the client from a given topic. If QoS was turned on on the subscription the remaining packets will be sent by the server. ### mqtt.publish(topic, message, [options], [callback]) - `topic` {Buffer | string} topic to publish to - `message` {Buffer | string} message to send - `options` {Object} - `qos` {number} Optional. Defaults to 0. - `retain` {boolean} Optional. If retain is `true` the broker stores the message for clients subscribing with retain `true` flag, therefore they can receive it later. - `callback` {function} the function which will be executed when the publish is completed Publishes a `message` to the broker under the given `topic`. **Example** ```js var mqtt = require('mqtt'); var opts = { host: '127.0.0.1', port: 443, keepalive: 10, clientId: 'IoT.js Client', } var client = mqtt.connect(opts, function () { client.publish('hello/#/iotjs', 'Hello MQTT clients!', { qos:1 }, function() { console.log('Message has been published'); }); }); ``` ## Events ### `connect` Emitted when the client successfully connects to a broker. ### `disconnect` A `disconnect` event is emitted when the broker disconnects the client gracefully. ### `error` If an error occurred an `error` event is emitted with the error data. ### `message` When data is received from the server a `message` event is emitted with a `data` object. It has the following properties: - `message`: The message the broker sent. - `topic`: The topic the message was sent from. - `qos`: The QoS level the message was sent with. - `packet_id`: The id of the packet if QoS was enabled. iotjs-1.0+715/docs/api/IoT.js-API-Module.md000066400000000000000000000040221371177304000177760ustar00rootroot00000000000000### Platform Support The following shows module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | require | O | O | O | O | O | # Module The `require` function is always available there is no need to import `module` explicitly. ### require(id) * `id` {string} Module name to be loaded. Loads the module named `id`. **Example** ```js var assert = require('assert'); assert.equal(2, 2); ``` **Loading a module** If a native module named `id` exists, load it and return. (_Native module:_ which module came from the IoT.js itself) `require` function searches for modules in the following order: 1. Current working directory. 2. `iotjs_modules` folder under current working directory. 3. `$HOME/iotjs_modules` 4. `$IOTJS_PATH/iotjs_modules` 5. `$IOTJS_EXTRA_MODULE_PATH` For each directory in search paths above: - If a file `id` exists, load it and return. - If a file `id.js` exists, load it and retun. - If a directory `id` exists, module system consider the directory as a package: - If `id/package.json` contains **main** property, load the file named **main** property. - If `id/package.json` exists, but neither the **main** property nor the file named **main** property exist, load `index.js`. - Extra step for Linux/Tizen targets: - If a file with `id.node` exists, try to load it as an N-API native addon and return. **Changing current working directory** You can explicitly change current working directory by setting `IOTJS_WORKING_DIR_PATH` environment variable. It is not recommended that you set this variable, if possible. **Adding extra paths for module loading** In order to add more directories to look for modules, you can set `IOTJS_EXTRA_MODULE_PATH` as an environment variable of your system. For instance, `./node_modules` and `./my_modules` will be referred if they're declared as follows. `IOTJS_EXTRA_MODULE_PATH=./node_modules:./my_modules` iotjs-1.0+715/docs/api/IoT.js-API-N-API.md000066400000000000000000000531271371177304000173670ustar00rootroot00000000000000### Platform Support The following chart shows the availability of each N-API function on each platform. The functions point to the related part of the official N-API documentation. | Supported features | Linux
(Ubuntu) | | :---: | :---: | | [napi_add_env_cleanup_hook](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_add_env_cleanup_hook) | O | | [napi_async_complete_callback](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_async_complete_callback) | O | | [napi_async_destroy](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_async_destroy) | O | | [napi_async_execute_callback](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_async_execute_callback) | O | | [napi_async_init](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_async_init) | O | | [napi_callback](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_callback_info) | O | | [napi_callback_info](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_callback_info) | O | | [napi_call_function](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_call_function) | O | | [napi_cancel_async_work](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_cancel_async_work) | O | | [napi_close_callback_scope](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_close_callback_scope) | O | | [napi_close_escapable_handle_scope](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_close_escapable_handle_scope) | O | | [napi_close_handle_scope](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_close_handle_scope) | O | | [napi_coerce_to_bool](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_coerce_to_bool) | O | | [napi_coerce_to_number](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_coerce_to_number) | O | | [napi_coerce_to_object](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_coerce_to_object) | O | | [napi_coerce_to_string](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_coerce_to_string) | O | | [napi_create_array](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_array) | O | | [napi_create_arraybuffer](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_arraybuffer) | O | | [napi_create_array_with_length](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_array_with_length) | O | | [napi_create_async_work](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_async_work) | O | | [napi_create_buffer](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_buffer) | O | | [napi_create_buffer_copy](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_buffer_copy) | O | | [napi_create_dataview](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_dataview) | O | | [napi_create_double](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_double) | O | | [napi_create_error](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_error) | O | | [napi_create_external](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_external) | O | | [napi_create_external_arraybuffer](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_external_arraybuffer) | O | | [napi_create_external_buffer](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_external_buffer) | O | | [napi_create_function](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_function) | O | | [napi_create_int32](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_int32) | O | | [napi_create_int64](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_int64) | O | | [napi_create_object](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_object) | O | | [napi_create_promise](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_promise) | O | | [napi_create_range_error](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_range_error) | O | | [napi_create_reference](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_reference) | O | | [napi_create_string_latin1](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_string_latin1) | O | | [napi_create_string_utf16](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_string_utf16) | O | | [napi_create_string_utf8](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_string_utf8) | O | | [napi_create_symbol](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_symbol) | O | | [napi_create_threadsafe_function](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_threadsafe_function) | O | | [napi_create_typedarray](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_typedarray) | O | | [napi_create_type_error](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_type_error) | O | | [napi_create_uint32](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_uint32) | O | | [napi_define_class](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_define_class) | O | | [napi_define_properties](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_define_properties) | O | | [napi_delete_async_work](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_delete_async_work) | O | | [napi_delete_element](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_delete_element) | O | | [napi_delete_property](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_delete_property) | O | | [napi_delete_reference](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_delete_reference) | O | | [napi_env](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_env) | O | | [napi_escapable_handle_scope](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_escapable_handle_scope) | O | | [napi_escape_handle](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_escape_handle) | O | | [napi_extended_error_info](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_extended_error_info) | O | | [napi_fatal_error](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_fatal_error) | O | | [napi_fatal_exception](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_fatal_exception) | O | | [napi_finalize](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_finalize) | O | | [napi_get_and_clear_last_exception](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_and_clear_last_exception) | O | | [napi_get_arraybuffer_info](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_arraybuffer_info) | O | | [napi_get_array_length](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_array_length) | O | | [napi_get_boolean](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_boolean) | O | | [napi_get_buffer_info](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_buffer_info) | O | | [napi_get_cb_info](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_cb_info) | O | | [napi_get_dataview_info](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_dataview_info) | O | | [napi_get_element](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_element) | O | | [napi_get_global](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_global) | O | | [napi_get_last_error_info](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_last_error_info) | O | | [napi_get_named_property](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_named_property) | O | | [napi_get_new_target](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_new_target) | O | | [napi_get_node_version](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_node_version) | O | | [napi_get_null](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_null) | O | | [napi_get_property](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_property_names) | O | | [napi_get_property_names](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_property_names) | O | | [napi_get_prototype](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_prototype) | O | | [napi_get_reference_value](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_reference_value) | O | | [napi_get_typedarray_info](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_typedarray_info) | O | | [napi_get_undefined](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_undefined) | O | | [napi_get_uv_event_loop](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_uv_event_loop) | O | | [napi_get_value_bool](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_bool) | O | | [napi_get_value_double](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_double) | O | | [napi_get_value_external](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_external) | O | | [napi_get_value_int32](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_int32) | O | | [napi_get_value_int64](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_int64) | O | | [napi_get_value_string_latin1](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_string_latin1) | O | | [napi_get_value_string_utf16](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_string_utf16) | O | | [napi_get_value_string_utf8](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_string_utf8) | O | | [napi_get_value_uint32](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_uint32) | O | | [napi_get_version](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_version) | O | | [napi_handle_scope](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_handle_scope) | O | | [napi_has_element](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_has_element) | O | | [napi_has_named_property](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_has_named_property) | O | | [napi_has_own_property](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_has_own_property) | O | | [napi_has_property](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_has_property) | O | | [napi_instanceof](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_instanceof) | O | | [napi_is_array](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_is_array) | O | | [napi_is_arraybuffer](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_is_arraybuffer) | O | | [napi_is_buffer](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_is_buffer) | O | | [napi_is_dataview](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_is_dataview) | O | | [napi_is_error](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_is_error) | O | | [napi_is_exception_pending](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_is_exception_pending) | O | | [napi_is_promise](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_is_promise) | O | | [napi_is_typedarray](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_is_typedarray) | O | | [napi_make_callback](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_make_callback) | O | | [napi_new_instance](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_new_instance) | O | | [napi_open_callback_scope](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_open_callback_scope) | O | | [napi_open_escapable_handle_scope](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_open_escapable_handle_scope) | O | | [napi_open_handle_scope](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_open_handle_scope) | O | | [napi_property_attributes](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_property_attributes) | O | | [napi_property_descriptor](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_property_descriptor) | O | | [napi_queue_async_work](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_queue_async_work) | O | | [napi_ref](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_ref) | O | | [napi_reference_ref](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_reference_ref) | O | | [napi_reference_unref](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_reference_unref) | O | | [napi_reject_deferred](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_reject_deferred) | O | | [napi_remove_env_cleanup_hook](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_remove_env_cleanup_hook) | O | | [napi_remove_wrap](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_remove_wrap) | O | | [napi_resolve_deferred](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_resolve_deferred) | O | | [napi_set_element](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_set_element) | O | | [napi_set_named_property](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_set_named_property) | O | | [napi_set_property](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_set_property) | O | | [napi_status](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_status) | O | | [napi_strict_equals](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_strict_equals) | O | | [napi_throw](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_throw) | O | | [napi_throw_error](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_throw_error) | O | | [napi_throw_range_error](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_throw_range_error) | O | | [napi_throw_type_error](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_throw_type_error) | O | | [napi_typedarray_type](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_typedarray_type) | O | | [napi_typeof](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_typeof) | O | | [napi_unwrap](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_unwrap) | O | | [napi_value](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_value) | O | | [napi_valuetype](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_valuetype) | O | | [napi_wrap](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_wrap) | O | ### The API does not support the following features: - [napi_threadsafe_function](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_threadsafe_function) - [napi_threadsafe_function_release_mode](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_threadsafe_function_release_mode) - [napi_threadsafe_function_call_mode](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_threadsafe_function_call_mode) - [napi_threadsafe_function_call_js](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_threadsafe_function_call_js) - [napi_create_bigint_int64](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_bigint_int64) - [napi_create_bigint_uint64](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_bigint_uint64) - [napi_create_bigint_words](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_bigint_words) - [napi_get_value_bigint_int64](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_bigint_int64) - [napi_get_value_bigint_uint64](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_bigint_uint64) - [napi_get_value_bigint_words](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_value_bigint_words) - [napi_add_finalizer](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_add_finalizer) - [Asynchronous Thread-safe Function Calls:](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_asynchronous_thread_safe_function_calls) - [napi_create_threadsafe_function](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_create_threadsafe_function) - [napi_get_threadsafe_function_context](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_get_threadsafe_function_context) - [napi_call_threadsafe_function](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_call_threadsafe_function) - [napi_acquire_threadsafe_function](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_acquire_threadsafe_function) - [napi_release_threadsafe_function](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_release_threadsafe_function) - [napi_ref_threadsafe_function](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_ref_threadsafe_function) - [napi_unref_threadsafe_function](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_napi_unref_threadsafe_function) # N-API Based on Node.js v10.15 (LTS) N-API (pronounced N as in the letter, followed by API) is an API for building native Addons. N-API is generally used to create and manipulate JavaScript values. You can read more about N-API [here](https://nodejs.org/dist/latest-v10.x/docs/api/n-api.html#n_api_n_api). Our implementation works with either ES2015 enabled or disabled. All of the N-API ES2015 features throw an exception when IoT.js isn't compiled with ES2015 yet they are used. ### Building N-API with IoT.js You need to append the `--n-api` parameter to the build command (e.g. `tools/build.py --n-api`). This automatically adds the N-API module to IoT.js. To run N-API test you should also append `--n-api` after the `testrunner.py`. ### Building a simple module ### node-gyp C++ code needs to be compiled into executable form whether it be as an object file to linked with others, a shared library, or a standalone executable. The main reason for this is that we need to link to the Node.js dependencies and headers correctly, another reason is that we need a cross platform way to build C++ source into binary for the target platform. Until now **node-gyp** is the **de-facto** standard build tool for writing Node.js addons. It's based on Google's **gyp** build tool, which abstract away many of the tedious issues related to cross platform building. **node-gyp** uses a file called ```binding.gyp``` that is located on the root of your addon project. ```binding.gyp``` file, contains all building configurations organized with a JSON like syntax. The most important parameter is the **target** that must be set to the same value used on the initialization code of the addon as in the examples reported below: #### **binding.gyp** ```gyp { "targets": [ { # myModule is the name of your native addon "target_name": "myModule", "sources": ["src/my_module.cc", ...], ... ] } ``` #### **my_module.cc** ```cpp #include // ... /** * This code is our entry-point. We receive two arguments here, the first is the * environment that represent an independent instance of the JavaScript runtime, * the second is exports, the same as module.exports in a .js file. * You can either add properties to the exports object passed in or create your * own exports object. In either case you must return the object to be used as * the exports for the module when you return from the Init function. */ Napi::Object Init(Napi::Env env, Napi::Object exports) { // ... return exports; } /** * This code defines the entry-point for the Node addon, it tells Node where to go * once the library has been loaded into active memory. The first argument must * match the "target" in our *binding.gyp*. Using NODE_GYP_MODULE_NAME ensures * that the argument will be correct, as long as the module is built with * node-gyp (which is the usual way of building modules). The second argument * points to the function to invoke. The function must not be namespaced. */ NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) ``` #### **node-gyp** reference - [Installation](https://www.npmjs.com/package/node-gyp#installation) - [How to use](https://www.npmjs.com/package/node-gyp#how-to-use) - [The binding.gyp file](https://www.npmjs.com/package/node-gyp#the-bindinggyp-file) - [Commands](https://www.npmjs.com/package/node-gyp#commands) - [Command options](https://www.npmjs.com/package/node-gyp#command-options) - [Configuration](https://www.npmjs.com/package/node-gyp#configuration) Sometimes finding the right settings for ```binding.gyp``` is not easy so to accomplish at most complicated task please refer to: - [GYP documentation](https://gyp.gsrc.io/index.md) - [node-gyp wiki](https://github.com/nodejs/node-gyp/wiki) The most important parameter is the target that must be set to the same value used on the initialization code of the addon. To use the N-API functions you need to include `node-api.h` in your native module.iotjs-1.0+715/docs/api/IoT.js-API-Net.md000066400000000000000000000426311371177304000173070ustar00rootroot00000000000000### Platform Support The following shows net module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | net.createServer | O | O | O | △ ¹ | △ ¹ | | net.connect | O | O | O | △ ¹ | △ ¹ | | net.createConnection | O | O | O | △ ¹ | △ ¹ | | net.Server.listen | O | O | O | △ ¹ | △ ¹ | | net.Server.close | O | O | O | △ ²| O | | net.Socket.connect | O | O | O | △ ¹ | △ ¹ | | net.Socket.write | O | O | O | △ ¹ | △ ¹ | | net.Socket.end | O | O | O | △ ¹ ³ | △ ¹ ³ | | net.Socket.destroy | O | O | O | △ ¹ ³ | △ ¹ ³ | | net.Socket.pause | O | O | O | △ ¹ | △ ¹ | | net.Socket.resume | O | O | O | △ ¹ | △ ¹ | | net.Socket.setTimeout | O | O | O | △ ¹ | △ ¹ | | net.Socket.setKeepAlive | X | X | X | X | X | 1. On NuttX/STM32F4-Discovery and TizenRT/Artik053, even a couple of sockets/server/requests might not work properly. 2. On NuttX/STM32F4-Discovery, close() may block due to a bug in poll(). 3. When writable stream is finished but readable stream is still alive, IoT.js tries to shutdown the socket, not destroy. However on `NuttX` and `TizenRT` due to lack of implementation, it does nothing inside. # Net IoT.js provides asynchronous networking through Net module. You can use this module with `require('net')` and create both servers and clients. ### net.connect(options[, connectListener]) * `options` {Object} An object which specifies the connection options. * `connectListener` {Function} Listener for the `'connect'` event. * Returns {net.Socket}. Creates a new `net.Socket` and automatically connects with the supplied `options`. The `options` object specifies the following information: * `port` {number} Port connect to (required). * `host` {string} Host connect to (optional, **Default:** `localhost`). * `family` {number} Version of IP stack. The `options` are passed to both the `net.Socket` constructor and the `socket.connect` method. The `connectListener` is automatically registered as a `'connect'` event listener. **Example** ```js var net = require('net'); var port = 22702; var echo_msg = ''; var socket = net.connect({port: port, family: 4}, function() { socket.end('Hello IoT.js'); }); socket.on('data', function(data) { echo_msg += data; }); socket.on('end', function() { console.log(echo_msg); }); ``` ### 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. **Example** ```js var net = require('net'); var port = 22702; var host = '127.0.0.1'; var echo_msg = ''; var socket = net.connect(port, host, function() { socket.end('Hello IoT.js'); }); socket.on('data', function(data) { echo_msg += data; }); socket.on('end', function() { console.log(echo_msg); }); ``` ### net.createConnection(options[, connectListener]) * `options` {Object} An object which specifies the connection options. * `connectListener` {Function} Listener for the `'connect'` event. * Returns {net.Socket}. Creates a new `net.Socket` and automatically connects with the supplied `options`. The `options` are passed to both the `net.Socket` constructor and the `socket.connect` method. The `options` object specifies the following information: * `port` {number} Port connect to (required). * `host` {string} Host connect to (optional, **Default:** `localhost`). * `family` {number} Version of IP stack. The `connectionListener` is automatically registered as a `'connect'` event listener. **Example** ```js var net = require('net'); var port = 80; var echo_msg = ''; var socket = net.createConnection({port: port, family: 4}, function() { socket.end('Hello IoT.js'); }); socket.on('data', function(data) { echo_msg += data; }); socket.on('end', function() { console.log(echo_msg); }); ``` ### net.createConnection(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`. It is equivalent to `new net.Socket()` followed by `socket.connect()`. If host is omitted, `localhost` will be assumed. The `connectionListener` is automatically registered as a `'connect'` event listener. **Example** ```js var net = require('net'); var port = 22702; var host = '127.0.0.1'; var echo_msg = ''; var socket = net.createConnection(port, host, function() { socket.end('Hello IoT.js'); }); socket.on('data', function(data) { echo_msg += data; }); socket.on('end', function() { console.log(echo_msg); }); ``` ### net.createServer([options][, connectionListener]) * `options` {Object} An object which specifies the connection options **Default:** `{ allowHalfOpen: false }`. * `connectListener` {Function} Listener for the `'connection'` event. * Returns {net.Server}. Creates a TCP server according to `options`. The `connectionListener` is automatically registered as a `'connection'` event listener. If `allowHalfOpen` is true, then the socket becomes non-readable, but still writable. You should call the `socket.end()` method explicitly. **Example** ```js var net = require('net'); var port = 22702; var server = net.createServer( { allowHalfOpen: true }, function(socket) { server.close(); } ); server.listen(port); server.on('connection', function(socket) { var msg = ''; socket.on('data', function(data) { msg += data; }); socket.on('end', function() { socket.end(msg); }); }); ``` ## Class: net.Server This class is used to create a TCP or local server. You can create `net.Server` instance with `net.createServer()`. ### server.close([closeListener]) * `closeListener` {Function} Listener for the `'close'` event. Stops listening new arriving connection. Server socket will be finally closed when all existing connections are closed, then emits `'close'` event. The `closeListener` is registered as a `'close'` event listener. **Example** ```js var net = require('net'); var server = net.createServer(); var port = 22704; var timeout = 1000; server.listen(port); /* ... */ server.close(); ``` ### server.listen(port[, host][, backlog][, listenListener]) * `port` {number} Port the client should connect to. * `host` {string} Host the client should connect to. * `backlog` {number} The maximum length of the queue of pending connections. **Default:** `511`. * `listenListener` {Function} Listener for the `'listening'` event. * Returns: {Object} The self instance of `net.Server`. Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections on any IPv4 address (0.0.0.0). **Example** ```js var net = require('net'); var server = net.createServer(); var port = 22709; server.listen(port); ``` ### server.listen(options[, listenListener]) * options {Object} An object which specifies the connection options. * `listenListener` {Function} Listener for the `'listening'` event. It behaves as the `server.listen(port[, host][, backlog][, listenListener])` function above. The option object supports the following properties: * `port` {number} Port the client should connect to. * `host` {string} Host the client should connect to. * `backlog` {number} The maximum length of the queue of pending connections. **Default:** `511`. **Example** ```js var net = require('net'); var server = net.createServer(); server.listen({port: 80, host: 'localhost'}); ``` ### Event: 'close' * `callback` {Function} Emitted when server has closed the connection. Note that this event will be emitted after all existing connections are closed. **Example** ```js var net = require('net'); var serverCloseEvent = 0; var server = net.createServer(); var port = 80; server.listen(port); server.on('connection', function(socket) { server.on('close', function() { serverCloseEvent++; }); }); ``` ### Event: 'connection(socket)' * `callback` {Function} * `socket` {Net.Socket} Emitted when new connection is established. **Example** ```js var net = require('net'); var server = net.createServer(); var port = 80; server.listen(port); server.on('connection', function(socket) { var msg = ''; socket.on('data', function(data) { msg += data; }); }); ``` ### Event: 'error' * `callback` {Function} Emitted when an error occurs. **Example** ```js var assert = require('assert'); var net = require('net'); var port = 80; var msg = 'Hello IoT.js'; var server = net.createServer(); /* ... */ server.on('error', function() { assert.fail(); server.close(); }); ``` ### Event: 'listening' * `callback` {Function} Emitted when server has been started listening. **Example** ```js var net = require('net'); var port = 80; var server = net.createServer( { allowHalfOpen: true }, function(socket) { server.close(); } ); server.listen(port); server.on('listening', function() { console.log('started listening'); }); ``` ## Class: net.Socket This object is an abstraction of a TCP or a local socket. `net.Socket` inherits from [`Stream.Duplex`](IoT.js-API-Stream.md). They can be created by the user (used as a client with connect()) or by the IoT.js engine (passed to the user through the 'connection' event of a server). ### new net.Socket([options]) * `options` {Object} An optional object which specifies the socket information. * Returns {net.Socket}. Construct a new socket object. The `options` object specifies only the following information: `allowHalfOpen` {boolean}. **Example** ```js var net = require('net'); var socket = new net.Socket(); ``` ### socket.connect(options[, connectListener]) * `options` {Object} An object which specifies the connection information. * `connectListener` {Function} Listener for the `'connect'` event. * Returns {net.Socket}. Creates a new socket object and automatically connects with the supplied `options`. The `options` object specifies following information: * `port` {number} Port connect to (required). * `host` {string} Host connect to (optional, **Default:** `localhost`). * `family` {number} Version of IP stack. The `connectionListener` is automatically registered as a `'connect'` event listener which will be emitted when the connection is established. **Example** ```js var net = require('net'); var port = 22702; var socket = new net.Socket(); socket.connect({port: port, family: 4}, function() { socket.end('Hello IoT.js'); }); ``` ### socket.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 socket and automatically connects with the supplied `port` and `host`. `connectionListener` is automatically registered as a `'connect'` event listener which will be emitted when the connection is established. **Example** ```js var net = require('net'); var port = 80; var socket = new net.Socket(); socket.connect(port, '127.0.0.1', function() { socket.end('Hello IoT.js'); }); ``` ### socket.destroy() Ensures that no more I/O activity happens on the socket and destroys the socket as soon as possible. **Example** ```js var net = require('net'); var port = 80; var socket = new net.Socket(); socket.connect(port, '127.0.0.1', function() { socket.end('Hello IoT.js'); }); /* ... */ socket.destroy(); ``` ### socket.end([data][, callback]) * `data` {Buffer|string} * `callback` {Function} Half-closes the socket. The socket is no longer writable. If `data` is given it is equivalent to `socket.write(data)` followed by `socket.end()`. **Example** ```js var net = require('net'); var server = net.createServer(); var port = 4010; server.listen(port); server.on('connection', function(socket) { socket.on('data', function(data) { socket.end('Hello IoT.js'); }); }); ``` ### socket.pause() Pauses reading data. **Example** ```js var net = require('net'); var server = net.createServer(); var port = 4010; server.listen(port); server.on('connection', function(socket) { // as soon as connection established, pause the socket socket.pause(); }); ``` ### socket.resume() Resumes reading data after a call to `pause()`. **Example** ```js var net = require('net'); var timers = require('timers'); var server = net.createServer(); var port = 80; var socket = new net.Socket(); var msg = ""; /* ... */ server.listen(port); server.on('connection', function(socket) { socket.on('data', function(data) { msg += data; socket.end(); }); socket.on('close', function() { server.close(); }); // as soon as connection established, pause the socket socket.pause(); // resume after 2 secs timers.setTimeout(function() { socket.resume(); }, 2000); }); ``` ### socket.setKeepAlive([enable][, initialDelay]) * `enable` {boolean} **Default:** `false`. * `initialDelay {number} **Default:** `0`. Enables or disables keep-alive functionality. **Example** ```js var net = require('net'); var keepalive_sock = new net.Socket(); keepalive_sock.setKeepAlive(true, 1000); ``` ### socket.setTimeout(timeout[, callback]) * `timeout` {number} Timeout number. * `callback` {Function} Registered as a `'timeout'` event listener. Sets timeout for the socket. If the socket is inactive for `timeout` milliseconds, `'timeout'` event will emit. **Example** ```js var net = require('net'); var server = net.createServer(); var port = 40; var timeout = 2000; var msg = ''; server.listen(port); server.on('connection', function(socket) { socket.setTimeout(timeout, function() { socket.end(); }); }); ``` ### socket.write(data[, callback]) * `data` {Buffer|string} Data to write. * `callback` {Function} Executed function (when the data is finally written out). Sends `data` on the socket. The optional `callback` function will be called after the given data is flushed through the connection. **Example** ```js var net = require('net'); var timers = require('timers'); var writeat = 1000; var socket = new net.Socket(); /* ... */ socket.on('connect', function() { timers.setTimeout(function() { socket.write('Hello IoT.js'); }, writeat); }); ``` ### Event: 'connect' * `callback` {Function} Emitted after connection is established. **Example** ```js var net = require('net'); var port = 80; var count = 40; /* ... */ for (var i = 0; i < count; ++i) { (function(i) { var socket = new net.Socket(); socket.connect(port, "localhost"); socket.on('connect', function() { socket.end(i.toString()); }); /* ... */ })(i); } ``` ### Event: 'close' * `callback` {Function} Emitted when the socket has been closed. **Example** ```js var net = require('net'); var server = net.createServer(); var port = 80; server.listen(port); server.on('connection', function(socket) { /* ... */ socket.on('close', function() { server.close(); }); }); ``` ### Event: 'data' * `callback` {Function} The data is given an argument (data: Buffer|string). Emitted when data is received from the connection. **Example** ```js var net = require('net'); var msg = ""; var socket = new net.Socket(); /* ... */ socket.on('data', function(data) { msg += data; }); ``` ### Event: 'drain' * `callback` {Function} Emitted when the write buffer becomes empty. **Example** ```js var net = require('net'); var port = 22703; var limit = 200; var server = net.createServer(); server.listen({ port: port }); /* ... */ server.on('connection', function(socket) { var i = 0; var writing = function() { var ok; do { ok = socket.write("" + (i % 10)); if (++i == limit) { socket.end(); ok = false; } } while (ok); }; socket.on('drain', writing); writing(); }); ``` ### Event: 'end' * `callback` {Function} Emitted when FIN packet received. **Example** ```js var net = require('net'); var socket = new net.Socket(); /* ... */ socket.on('end', function() { socket.end(); }); ``` ### Event: 'error' * `callback` {Function} * `err` {Error} Emitted when an error occurs. **Example** ```js var assert = require('assert'); var net = require('net'); var bad_sock = new net.Socket(); bad_sock.on('error', function(err){ assert.equal(err instanceof Error, true); }); ``` ### Event: 'lookup' * `callback` {Function} * `err` {Error} * `address` {string} * `family` {string|null} Emitted after resolving hostname. **Example** ```js var socket = new net.Socket(); var msg = ""; var lookupHandled = false; socket.on('lookup', function(err, ip, family) { lookupHandled = true; }); ``` ### Event: 'timeout' * `callback` {Function}` Emitted when the connection remains idle for the specified timeout. **Example** ```js var net = require('net'); var timedout = false; // Try connect to host that is not exist (Reserved address) var socket = net.createConnection(11111, '192.0.2.1'); socket.setTimeout(1000); socket.on('timeout', function() { timedout = true; socket.destroy(); }); ``` iotjs-1.0+715/docs/api/IoT.js-API-PWM.md000066400000000000000000000176361371177304000172330ustar00rootroot00000000000000### Platform Support The following shows PWM module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(ARTIK530) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(ARTIK053) | | :---: | :---: | :---: | :---: | :---: | :---: | | pwm.open | X | O | O | O | O | | pwm.openSync | X | O | O | O | O | | pwmpin.setPeriod | X | O | O | O | O | | pwmpin.setPeriodSync | X | O | O | O | O | | pwmpin.setFrequency | X | O | O | O | O | | pwmpin.setFrequencySync | X | O | O | O | O | | pwmpin.setDutyCycle | X | O | O | O | O | | pwmpin.setDutyCycleSync | X | O | O | O | O | | pwmpin.setEnable | X | O | O | O | O | | pwmpin.setEnableSync | X | O | O | O | O | | pwmpin.close | X | O | O | O | O | | pwmpin.closeSync | X | O | O | O | O | ## Class: PWM ### pwm.open(configuration, callback) * `configuration` {Object} Configuration object which can have the following properties. * `pin` {number} The pin number to use with this PWM object (mandatory configuration). * `chip` {number} The PWM chip number (only on Linux). **Default:** `0`. * `period` {number} The period of the PWM signal, in seconds (positive number). * `dutyCycle` {number} The active time of the PWM signal, must be within the `0.0` and `1.0` range. * `callback` {Function} Callback function. * `err` {Error|null} The error object or `null` if there were no error. * `pwmpin` {Object} An instance of PWMPin. * Returns: {Object} An instance of PWMPin. Opens PWM pin with the specified configuration. To correctly open a PWM pin one must know the correct pin number: * On Linux, `pin` is a number which is `0` or `1`. * On Tizen, `pin` is a number which is `2`. (Only ARTIK530 board support PWM.) * On NuttX, you have to know pin name. The pin name is defined in target board module. For more module information, please see below list. * [STM32F4-discovery](../targets/nuttx/stm32f4dis/IoT.js-API-Stm32f4dis.md#pwm-pin) **Example** ```js var pwm = require('pwm'); var config = { pin: 0, period: 0.1, dutyCycle: 0.5 } var pwm0 = pwm.open(config, function(err) { if (err) { throw err; } }); ``` ### pwm.openSync(configuration) * `configuration` {Object} Configuration object which can have the following properties. * `pin` {number} The pin number to use with this PWM object (mandatory configuration). * `chip` {number} The PWM chip number (only on Linux). **Default:** `0`. * `period` {number} The period of the PWM signal, in seconds (positive number). * `dutyCycle` {number} The active time of the PWM signal, must be within the `0.0` and `1.0` range. * Returns: {Object} An instance of PWMPin. Opens PWM pin with the specified configuration. To correctly open a PWM pin one must know the correct pin number: * On Linux, `pin` is a number which is `0` or `1`. * On NuttX, you have to know pin name. The pin name is defined in target board module. For more module information, please see below list. * [STM32F4-discovery](../targets/nuttx/stm32f4dis/IoT.js-API-Stm32f4dis.md#pwm-pin) **Example** ```js var pwm = require('pwm'); var config = { pin: 0, period: 0.1, dutyCycle: 0.5 } var pwm0 = pwm.openSync(config); ``` ## Class: PWMPin ### pwmpin.setPeriod(period[, callback]) * `period` {number} The period of the PWM signal, in seconds (positive number). * `callback` {Function} * `err` {Error|null} The error object or `null` if there were no error. The `setPeriod` method allows the configuration of the period of the PWM signal in seconds. The `period` argument must specified and it should be a positive number. Configuration is done asynchronously and the `callback` method is invoked after the period is configured to the new value or if an error occured. **Example** ```js pwm0.setPeriod(1, function(err) { if (err) { throw err; } console.log('done'); }); // prints: do console.log('do'); // prints: done ``` ### pwmpin.setPeriodSync(period) * `period` {number} The period of the PWM signal, in seconds (positive number). The `setPeriodSync` method allows the configuration of the period of the PWM signal in seconds. The `period` argument must specified and it should be a positive number. Configuration is done synchronously and will block till the period is configured. **Example** ```js pwm0.setPeriodSync(1); // prints: done console.log('done'); ``` ### pwmpin.setFrequency(frequency[, callback]) * `frequency` {integer} In Hz (positive integer). * `callback` {Function} * `err` {Error|null} The error object or `null` if there were no error. The `setFrequency` method configures the frequency of the PWM signal. `frequency` is the measurement of how often the signal is repeated in a single period. Configuration is done asynchronously and the `callback` method is invoked after the frequency is configured to the new value or if an error occured. **Example** ```js pwm0.setFrequency(1, function(err) { if (err) { throw err; } console.log('done'); }); // prints: do console.log('do'); // prints: done ``` ### pwmpin.setFrequencySync(frequency) * `frequency` {integer} In Hz (positive integer). The `setFrequencySync` method configures the frequency of the PWM signal. `frequency` is the measurement of how often the signal is repeated in a single period. Configuration is done synchronously and will block till the frequency is configured. **Example** ```js pwm0.setFrequencySync(1); // prints: done console.log('done'); ``` ### pwmpin.setDutyCycle(dutyCycle[, callback]) * `dutyCycle` {number} Must be within the `0.0` and `1.0` range. * `callback` {Function} * `err` {Error|null} The error object or `null` if there were no error. The `setDutyCycle` method allows the configuration of the duty cycle of the PWM signal. The duty cycle is the ratio of the pulse width in one period. Configuration is done asynchronously and the `callback` method is invoked after the duty cycle is configured to the new value or if an error occured. **Example** ```js pwm0.setDutyCycle(1, function(err) { if (err) { throw err; } console.log('done'); }); // prints: do console.log('do'); // prints: done ``` ### pwmpin.setDutyCycleSync(dutyCycle) * `dutyCycle` {number} Must be within the `0.0` and `1.0` range. The `setDutyCycleSync` method allows the configuration of the duty cycle of the PWM signal. The duty cycle is the ratio of the pulse width in one period. Configuration is done synchronously and will block till the duty cycle is configured. **Example** ```js pwm0.setDutyCycleSync(1); // prints: done console.log('done'); ``` ### pwmpin.setEnable(enable[, callback]) * `enable` {boolean} * `callback` {Function} * `err` {Error|null} The error object or `null` if there were no error. The `setEnable` method can turn on/off the generation of the PWM signal. If the `enable` argument is `true` then the PWN signal generation is turned on. Otherwise the signal generation is turned off. After enabling/disabling the signal generation the `callback` is invoked. **Example** ```js pwm0.setEnable(true, function(err) { if (err) { throw err; } console.log('done'); }); // prints: do console.log('do'); // prints: done ``` ### pwmpin.setEnableSync(enable) * `enable` {boolean} The `setEnableSync` method can turn on/off the generation of the PWM signal. If the `enable` argument is `true` then the PWN signal generation is turned on. Otherwise the signal generation is turned off. **Example** ```js pwm0.setEnableSync(false); // prints: done console.log('done'); ``` ### pwmpin.close([callback]) * `callback` {Function} * `err` {Error|null} The error object or `null` if there were no error. The `close` method closes the PWM pin asynchronously. The `callback` method will be invoked after the PWM device is released. **Example** ```js pwm0.close(function(err) { if (err) { throw err; } console.log('done'); }); // prints: do console.log('do'); // prints: done ``` ### pwmpin.closeSync() The `closeSync` method closes the PWM pin synchronously. **Example** ```js pwm0.closeSync(); // prints: done console.log('done'); ``` iotjs-1.0+715/docs/api/IoT.js-API-Process.md000066400000000000000000000202101371177304000201640ustar00rootroot00000000000000### Platform Support The following shows process module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | process.nextTick | O | O | O | O | O | | process.exit | O | O | O | O | O | | process.cwd | O | O | O | O | O | | process.chdir | O | O | 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. * `IOTJS_WORKING_DIR_PATH` is the specified current working directory path to change the root of the module load. * `IOTJS_EXTRA_MODULE_PATH` contains the paths to be additionally referenced to load any module. * `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 `'artik05x'`, `'artik10'`, `'rpi2'`,`'stm32f4dis'`, or `'unknown'`. **Example** ```js console.log(process.iotjs.board); // on Raspberry 2 it prints: rpi2 ``` ### 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 explicitly 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, [...args]) * `callback` {Function} * `...args` {any} Additional arguments to pass when invoking the callback 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.'); ``` iotjs-1.0+715/docs/api/IoT.js-API-SPI.md000066400000000000000000000123671371177304000172170ustar00rootroot00000000000000### Platform Support The following shows spi module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | spi.open | X | O | O | O | O | | spi.openSync | X | O | O | O | O | | spibus.transfer | X | O | O | O | O | | spibus.transferSync | X | O | O | O | O | | spibus.close | X | O | O | O | O | | spibus.closeSync | X | O | O | O | O | ## Class: SPI SPI (Serial Peripheral Interface) is a communication protocol which defines a way to communicate between devices. * On Tizen, the bus number is defined in [this documentation](../targets/tizen/SystemIO-Pin-Information-Tizen.md#spi). * 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) ### 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. (Tizen, TizenRT and NuttX only) * `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}. * `spibus` {Object} An instance of SPIBus. * Returns: {Object} An instance of SPIBus. Opens an SPI device with the specified configuration. **Example** ```js var spi = require('spi'); var spi0 = spi.open({ device: '/dev/spidev0.0' }, function(err) { if (err) { throw err; } }); ``` ### spi.openSync(configuration) * `configuration` {Object} * `device` {string} The specified path for `spidev`. (only on Linux) * `bus` {number} The specified bus number. (Tizen, TizenRT and NuttX only) * `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`. * Returns: {Object} An instance of SPIBus. Opens an SPI device with the specified configuration. **Example** ```js var spi = require('spi'); var spi0 = spi.openSync({ device: '/dev/spidev0.0' }); ``` ## Class: SPIBus The SPIBus is commonly used for communication. ### spibus.transfer(txBuffer, [, callback]) * `txBuffer` {Array|Buffer}. * `callback` {Function}. * `err` {Error|null}. * `rxBuffer` {Array}. Writes and reads data from the SPI device asynchronously. The `txBuffer` and `rxBuffer` length is equal. **Example** ```js var tx = new Buffer('Hello IoTjs'); var rx = new Buffer(tx.length); spi0.transfer(tx, function(err, rx) { 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) * `txBuffer` {Array|Buffer}. * Returns: `rxBuffer` {Array}. Writes and reads data from the SPI device synchronously. The `txBuffer` and `rxBuffer` length is equal. **Example** ```js var tx = new Buffer('Hello IoTjs'); var rx = spi0.transferSync(tx); 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'); ``` iotjs-1.0+715/docs/api/IoT.js-API-Stream.md000066400000000000000000000332421371177304000200120ustar00rootroot00000000000000### Platform Support The following shows stream module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | readable.isPaused | O | O | O | O | O | | readable.pause | O | O | O | O | O | | readable.read | O | O | O | O | O | | readable.resume | O | O | O | O | O | | writable.end | O | O | O | O | O | | writable.write | O | O | O | O | O | # Stream A stream is an abstract interface for working with streaming data. Streams can be readable, writable, or both (duplex). All streams are instances of EventEmitter. ## Class: Stream ### new Stream() **This method is only for implementing a new stream type.** This function registers the common properties of all streams. **Example** ```js var Stream = require('stream').Stream; var stream = new Stream(); stream.read = function () { // A custom read function. } ``` ## Class: Stream.Readable Readable stream is an abstraction for a *data source* from which data will be read. At any time a readable stream operates in one of two modes: *flowing* and *paused*. All streams begin in paused mode. In paused mode the stream emits [`'readable'`](#event-readable) event every time a new data is available for read. This data can be read by calling the [`readable.read()`](#readablereadsize) function. A stream can be switched to paused mode by calling the [`readable.pause()`](#readablepause) function. In flowing mode the stream emits [`'data'`](#event-data) events every time when data is received. The data buffer is passed to the callback function. A stream can be switched to flowing mode by calling the [`readable.resume()`](#readableresume) function or by adding a [`'data'`](#event-data) event handler. Supported events: ### Event: 'close' Emitted when the underlying resource has been closed and no more events will be emitted. Not all [`Readable`](#class-streamreadable) streams will emit the `'close'` event. ### Event: 'data' * `chunk` {Buffer|string} Emitted when the stream passes the ownership of the data to a consumer. Only streams in flowing mode emit this event. A stream can be switched to flowing mode by calling the [`readable.resume()`](#readableresume) function or by adding a `'data'` event handler. **Example** ```js var Readable = require('stream').Readable; var readable = new Readable(); readable.on('data', function (chunk) { // prints: data received: message console.log('data received: ' + chunk); }) readable.push("message"); ``` ### Event: 'end' Emitted when there is no more data to be consumed from the stream. **Example** ```js var Readable = require('stream').Readable; var readable = new Readable(); readable.on('end', function () { // prints: no more data console.log('no more data'); }) readable.push(null); ``` ### Event: 'error' * `error` {Object} Emitted when an error is detected by the readable stream. This event may occure any time. ### Event: 'readable' Emitted when there is data available to be read from the stream. This event will also be emitted once the end of the stream data has been reached but before the ['end'](#event-end) event is emitted. **Example** ```js var Readable = require('stream').Readable; var readable = new Readable(); readable.on('readable', function () { // prints:. console.log('data received: ' + this.read()); }) readable.push('message'); ``` ### new Readable(options) * `options` {Object} * `defaultEncoding` {string} **Default:** `utf8` **This method is only for implementing a new [`Readable`](#class-streamreadable) stream type.** This function registers the common properties of [`Readable`](#class-streamreadable) streams. The `options` object allows passing configuration arguments. The `Readable` constructor only supports a few members of the `options` object but descendants may supports more of them. **Example** ```js var Readable = require('stream').Readable; var readable = new Readable({ defaultEncoding: 'utf8' }); ``` ### readable.isPaused() * Returns: {boolean} Returns `true` if the [`Readable`](#class-streamreadable) stream is in paused mode. Otherwise the stream is in flowing mode. By default the stream starts in paused mode. **Example** ```js var Readable = require('stream').Readable; var readable = new Readable(); // prints: true console.log(readable.isPaused()); ``` ### readable.pause() * Returns: {Readable} Stops emitting [`'data'`](#event-data) events if the stream is in flowing mode and sets paused mode. No effect otherwise. **Example** ```js var Readable = require('stream').Readable; var readable = new Readable(); readable.pause(); ``` ### readable.read([size]) * `size` {number} Specify how much data will be read. * Returns: {Buffer|null} The `readable.read()` method pulls some data out of the internal buffer and returns it. If no data is available `null` is returned instead. Note: currently all data must be read. **Example** ```js var Readable = require('stream').Readable; var readable = new Readable(); // prints: null console.log(readable.read()); readable.push('message'); // prints: message console.log(readable.read()); ``` ### readable.resume() * Returns: {Readable} Starts emitting [`'data'`](#events-data) events if the stream is in paused mode and sets flowing mode. No effect otherwise. **Example** ```js var Readable = require('stream').Readable; var readable = new Readable(); readable.resume(); ``` ### readable.push(chunk) * `chunk` {Buffer|string} **This method is only for implementing a new [`Readable`](#class-streamreadable) stream type.** Push a chunk of data to the underlying `Buffer` of this stream. The data can be read by using either [`readable.read()`](#readablereadsize) method or [`'data'`](#event-data) event of this stream. **Example** ```js var Readable = require('stream').Readable; var readable = new Readable(); readable.push('message'); // prints: message console.log(readable.read()); ``` ### readable.pipe(destination[, options]) * `destination` {Writable|Duplex} * `options` * `end` {bool} **Default: `true`** * returns: {Writable|Duplex} Attaches a Writable or Duplex stream to the Readable. Automatically switches the Readable stream into flowing mode and pushes all of its data into the attached Writable. **Example** ```js var stream = require('stream'); var Readable = stream.Readable; var Writable = stream.Writable; var source = new Readable(); var dest = new Writable(); dest._write = function(chunk, callback, onwrite) { console.log('dest received: ', chunk.toString()); }; dest._readyToWrite(); source.pipe(dest); source.push('hello'); // the dest._write function will print the data ``` It is also possible to attach multiple Writable streams to a single Readable stream. The `readable.pipe()` method returns a reference to the `destination` stream, making it possible to set up a chain of piped streams (only if `destination` is Duplex). **Example** ```js var stream = require('stream'); var Readable = stream.Readable; var Writable = stream.Writable; var source = new Readable(); var dest = new Duplex(); var dest2 = new Duplex(); dest._write = function(chunk, callback, onwrite) { console.log('dest received: ', chunk.toString()); }; dest._readyToWrite(); dest2._write = function(chunk, callback, onwrite) { console.log('dest2 received: ', chunk.toString()); }; dest2._readyToWrite(); source.pipe(dest).pipe(dest2); source.push('hello'); // dest and dest2 will receive and print the data ``` By default, the `end()` method of the `destination` stream is called when the Readable emits `end`. This behavior can be disabled by passing the `end` option as `false` to the `Readable.pipe()` method. Note: in case of a stream error, the attached streams will NOT be closed automatically. If a stream error occurs, each of the attached streams must be closed manually. ### readable.unpipe([destination]) * `destination` {Writable|Duplex} * returns: `this` Detaches a previously attached stream from the Readable. If the optional `destination` argument is not specified, all attached streams will be detached. If `destination` is specified but there is no pipe set up for it, then the method simply returns and does nothing. **Example** ```js var stream = require('stream'); var Readable = stream.Readable; var Writable = stream.Writable; var source = new Readable(); var dest = new Writable(); dest._write = function(chunk, callback, onwrite) { console.log('dest received: ', chunk.toString()); }; dest._readyToWrite(); source.pipe(dest); source.push('hello'); // the dest._write function will print the data source.unpipe(dest); // source.unpipe() has the same effect in this case source.push(world); // dest will not receive the data anymore ``` Note: if multiple streams are piped together in a chain, unpiping the first one from the readable will not unpipe the rest of them. **Example** ```js source.pipe(dest).pipe(dest2).pipe(dest3).pipe(dest4); // ... some code ... source.unpipe(dest); // dest will no longer be piped to source, but dest2 will still be // piped to dest, etc ``` # Class: Stream.Writable Writable stream is an abstraction for a *destination* to which data is written. Several functions of the Stream.Writable class are abstract interfaces and descendants can override them. The [`new Stream.Writable()`](#new-streamwritableoptions) constructor must be used for initializing a writable stream and [`writable._write()`](#writable_writechunk-callback-onwrite) method are required to be implemented. Supported events: ### Event: 'drain' If [`writable.write()`](#writablewritechunk-callback) returns `false` the stream emits a `drain` event when it is appropriate to resume writing data into the stream. **Example** ```js var Writable = require('stream').Writable; // Buffer is full after 1 byte of data. var writable = new Writable({ highWaterMark:1 }); writable._write = function(chunk, callback, onwrite) { onwrite(); } // Writes 1 byte data into the stream. writable.write("X"); writable.on('drain', function() { // prints: can continue writing console.log('can continue writing'); }); writable._readyToWrite(); ``` ### Event: 'error' * `err` {Error} Emitted if an error occures during writing the data. ### Event: 'finish' Emitted after [`writable.end()`](#writableendchunk-callback) has been called and all pending data has been flushed. **Example** ```js var Writable = require('stream').Writable; var writable = new Writable(); writable.on('finish', function() { // prints: end of writing console.log('end of writing'); }); writable.end(); ``` ### new Stream.Writable([options]) * `options` {Object} * `highWaterMark` {number} **This method is only for implementing a new [`Writable`](#class-streamwritable) stream type.** This function registers the common properties of [`Writable`](#class-streamwritable) streams. When the size of the internal buffer reaches `options.highWaterMark` the [`writable.write()`](#writablewritechunk-callback) method starts returning with `false` and the data should be drained before further data is written. **Example** ```js var Writable = require('stream').Writable; var writable = new Writable({ highWaterMark:256 }); ``` ### writable.end([chunk[, callback]]) * `chunk` {Buffer|string} Final data to write. * `callback` {Function} Calling this function signals that no more data will be written to the Writable. The optional `chunk` argument allows writing a final chunk of data. If `chunk` is `null` no data is written. The optional `callback` function is attached as a listener for the ['finish'](#event-finish) event. **Example** ```js var Writable = require('stream').Writable; var writable = new Writable(); writable.end(); ``` ### writable.write(chunk[, callback]) * `chunk` {Buffer|string} Data to write. * `callback` {Function} Called when this chunk of data is flushed. * Returns: {boolean} Converts `chunk` into a sequence of bytes and writes this data to the stream. An optional `callback` function is called when the data is flushed. The returned value is `true` if writing can be continued right after calling this method. Otherwise the returned value is `false` and no data should be written until the [`'drain'`](#event-drain) event is received. **Example** ```js var Writable = require('stream').Writable; var writable = new Writable(); writable.write("String"); ``` ### writable._readyToWrite() **This method is only for implementing a new [`Writable`](#class-streamwritable) stream type.** This method informs the [`Writable`](#class-streamwritable) stream that the implementation is ready for receiving data. **Example** ```js var Writable = require('stream').Writable; var writable = new Writable(); writable._readyToWrite(); ``` ### writable._write(chunk, callback, onwrite) * `chunk` {Buffer|string} The data to be written by the stream. * `callback` {Function} Callback to be called when the chunk of data is flushed. * `onwrite` {Function} Internal Callback to be called for when the chunk of data is flushed. **This method is only for implementing a new [`Writable`](#class-streamwritable) stream type.** This internal method is called by the [`Writable`](#class-streamwritable) stream and the implementation **must** override it. The data to be written is passed as the `chunk` argument. After the operation is completed, both `callback` and `onwrite` function should be called. **Example** ```js var Writable = require('stream').Writable; var writable = new Writable(); writable._write = function(chunk, callback, onwrite) { // prints: message console.log(chunk); onwrite(); if (callback) callback(); } writable._readyToWrite(); writable.write('message'); ``` # Class: Stream.Duplex Duplex streams are streams that implement both the Readable and Writable interfaces. iotjs-1.0+715/docs/api/IoT.js-API-TLS.md000066400000000000000000000164311371177304000172220ustar00rootroot00000000000000### Platform Support The following chart shows the availability of each TLS module API function on each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | Nuttx
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | tls.connect | O | O | O | O | O | O | | tls.createServer | O | O | O | O | O | O | | tls.createSecureContext | O | O | O | O | O | O | | tls.Server | O | O | O | O | O | O | | tls.TLSSocket | O | O | O | O | O | O | | tls.TLSSocket.write | O | O | O | O | O | O | | tls.TLSSocket.pause | O | O | O | O | O | O | | tls.TLSSocket.end | O | O | O | O | O | O | | tls.TLSSocket.resume | O | O | O | O | O | O | | tls.TLSSocket.pause | O | O | O | O | O | O | As even a couple of sockets/servers/requests require a considerable size of memory, on NuttX/STM32F4-Discovery and TizenRT/Artik053 the number of such sockets are limited. # TLS Transport Layer Security makes secure communication over sockets possible. ### tls.connect(options[,callback]) * `options` {Object} * `host` {string} Host the client should connect to, defaults to 'localhost'. * `port` {number} Port the client should connect to. * `socket` {stream.Duplex} Optional, typically an instance of `net.Socket`. If this options is specified, host and port are ignored. The user passing the options is responsible for it connecting to the server. `tls.connect` won't call `net.connect` on it. * `rejectUnauthorized` {boolean} Whether the server certificate should be verified against the list of supplied CAs. An `error` event is emitted if verifications fails; `err.code` contains the MbedTLS error code. Defaults to `false`. NOT READY * `servername` {string} Server name for the SNI (Server name Indication) TLS extension. NOT READY * `session` {Buffer} A `Buffer` containing a TLS session. NOT READY * `minDHSize` {number} The minimum size of the DH parameter in bits to accept a TLS connection. If a server offers a DH parameter with a size less than specified, the TLS connection is destroyed and an error is thrown. Defaults to `1024`. * `lookup` {Function} Custom lookup. Defaults to `dns.lookup()`. * `callback` {Function} The callback function will be added as a listener for the `secureConnect` event. Returns a `tls.TLSSocket` object. **Example** ```js var tls = require('tls'); var opts = { host: '127.0.0.1', port: 443, rejectUnauthorized: true } var socket = tls.connect(opts, function() { socket.write('Hello IoT.js'); socket.end(); }); ``` ### tls.connect(port[,host][,options][,callback]) * `port` {number} Port the client should connect to. * `host` {string} Host the client should connect to, defaults to 'localhost'. * `options` {Object} See `tls.connect()`. * `callback` {Function} See `tls.connect()`. Same as tls.connect() except that port and host can be provided as arguments instead of options. A port or host option, if specified, will take precedence over any port or host argument. **Example** ```js var tls = require('tls'); var socket = tls.connect(443, 'localhost', function() { socket.write('Hello IoT.js'); socket.end(); }); ``` ### tls.createServer([options][, secureConnectionListener]) * `options` {object} Accepts the same options as the `tls.Server()` and `tls.createSecureContext()`. * `secureConnectionListener` {Function} * `socket` {tls.TLSSocket} The connected TLSSocket. * Returns {tls.Server} Create a TLS Server. Behaves the same way as the `new tls.Server(options, secureConnectionListener)` call. **Example** ```js var fs = require('fs'); var tls = require('tls'); var options = { key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt') }; var server = tls.createServer(options, function(socket) { console.log('got connection'); ... }); server.listen(8081); ``` ### tls.createSecureContext([options]) * `options` {object} * `ca` {string | Buffer} Optional trusted CA certificates. No default is provided. * `cert` {string | Buffer} Cert chains in PEM format. * `key` {string | Buffer} Private keys in PEM format. * Returns {Object} The method returns a special object containing the tls context and credential information. ## Class: tls.Server A server object representing a TLS server. Based on the `net.Server`. All events, methods and properties are inherited from the `net.Server`. ### new tls.Server([options][, secureConnectionListener]) * `options` {object} Options for the TLS connection. * `secureContext` {object} An special object containing the tls credential information. This should be only created via a `tls.createSecureContext()` call if needed. If not provided a secureContext will be created automatically, using the `options` object. No default value is provided. * Additional options are from `tls.createSecureContext()`. * `secureConnectionListener` {Function} * `socket` {tls.TLSSocket} * Returns {tls.Server} Creates new `tls.Server` object. The `secureConnectionListener` method is automatically set as a listener for the `'secureConnection'` event. To correctly create a TLS Server the server certificates should be provided in the `options` object. **Example** ```js var fs = require('fs'); var tls = require('tls'); var options = { key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt') }; var server = new tls.Server(options, function(socket) { console.log('got connection'); ... }); server.listen(8081); ``` ## Class: tls.TLSSocket The `TLSSocket` is responsible for all TLS negotiations and data encryption on a `net.Socket`. Just like `net.Socket` it uses a `Stream.duplex` interface. ### new tls.TLSSocket(socket[,options]) * `socket` {net.Socket | stream.Duplex} * `options` {Object} * `isServer` {boolean} The TLSSocket must know if it represents the server or client side of the connection. Default: `false`. * `secureContext` {Object} The TLS context object. If none provided one will be created with the `tls.createSecureContext` method using the given `options` object. * Returns {tls.TLSSocket} Creates a new TLSSocket object for an existing TCP socket. ### tlsSocket.address() Returns an object containing the bound address, family name, and port of the socket.`{port: 443, family: 'IPv4', address: '127.0.0.1'}` ### tlsSocket.authorizationError Returns the reason why the peer's certificate has not been verified. ### tlsSocket.authorized Returns `true` if the peer certificate was signed by one of the CAs specified when creating the `tls.TLSSocket` instance, otherwise false. ### tlsSocket.encrypted Always returns `true`, can be used to distinguish TLS sockets from regular `net.Socket`s. ### tlsSocket.getProtocol() Returns a string containing the negotiated SSL/TLS protocol version of the connection. If the handshaking has not been complete, `unknown` will be returned. The value `null` will be returned for server sockets or disconnected client sockets. ### tlsSocket.localAddress Returns a string representing the local IP address. ### tlsSocket.localPort Returns a number representing the local port. ### tlsSocket.remoteAddress Returns a string representing the remote IP address. ### tlsSocket.remoteFamily Returns a string representing the remote IP family. ### tlsSocket.remotePort Returns a number representing the remote port. iotjs-1.0+715/docs/api/IoT.js-API-Timers.md000066400000000000000000000055701371177304000200250ustar00rootroot00000000000000### Platform Support The following shows timer module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | setTimeout | O | O | O | O | O | | clearTimeout | O | O | O | O | O | | setInterval | O | O | O | O | O | | clearInterval | O | O | O | O | O | # Timers 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. ### setTimeout(callback, delay[, args..]) * `callback` {Function} The function to call when the timer elapses. * `...args` {any} * `delay` {number} The number of milliseconds to wait before calling the `callback`. * `...args` {any} - Optional arguments to pass when the `callback` is called. * Returns: {Timeout} Schedules execution of a one-time `callback` after `delay` milliseconds. Returns a `Timeout` for use with `clearTimeout()`. If `callback` is not a function, a `TypeError` will be thrown. **Example** ```js var timeout = setTimeout(function() { // Do something which will be executed after one second. }, 1000); ``` ### clearTimeout(timeout) * `timeout` {Timeout} A Timeout object returned by `setTimeout()`. Cancels a `Timeout` object created by `setTimeout()`. **Example** ```js var timeout = setTimeout(function() { }, 1000); ... clearTimeout(timeout); ``` ### setInterval(callback, delay[, args..]) * `callback` {Function} The function to call when the timer elapses. * `...args` {any} * `delay` {number} The number of milliseconds to wait before calling the `callback`. * `...args` {any} - Optional arguments to pass when the `callback` is called. * Returns: {Timeout} Schedules repeated execution of `callback` every `delay` milliseconds. Returns a `Timeout` object for use with `clearInterval()`. If `callback` is not a function, a `TypeError` will be thrown. **Example** ```js var timeout = setInterval(function() { // Do something which will be executed repeatadly one time per second. }, 1000); ``` ### clearInterval(timeout) * `timeout` {Timeout} A Timeout object as returned by `setInterval()`. Cancels a `Timeout` object created by `setInterval()`. **Example** ```js var timeout = setInterval(function() { }, 1000); ... clearInterval(timeout); ``` ## Class: Timeout This object is created internally and is returned from `setTimeout()` and `setInterval()`. ### timeout.ref() When called, requests that the IoT.js event loop should not exit as long as the `Timeout` is active. ### timeout.unref() When called, the active `Timeout` object will not force the IoT.js event loop to remain active. If there are no other scheduled activities, the process may exit, the process may exit before the `Timeout` object's callback is invoked. iotjs-1.0+715/docs/api/IoT.js-API-UART.md000066400000000000000000000077221371177304000173360ustar00rootroot00000000000000### Platform Support The following shows uart module APIs available for each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | uart.open | O | O | O | O | O | | uart.openSync | O | O | O | O | O | | uartport.write | O | O | O | O | O | | uartport.writeSync | O | O | O | O | O | | uartport.close | O | O | O | O | O | | uartport.closeSync | O | O | O | O | O | ## Class: UART The UART (Universal Asynchronous Receiver/Transmitter) class supports asynchronous serial communication. * On Tizen, the port number is defined in [this documentation](../targets/tizen/SystemIO-Pin-Information-Tizen.md#uart). ### uart.open(configuration, callback) * `configuration` {Object} * `device` {string} Mandatory configuration. The specified device path.(Linux, Nuttx and TizenRT only) * `port` {number} Mandatory configuration. The specified port number. (Tizen only) * `baudRate` {number} Specifies how fast data is sent over a serial line. **Default:** `9600`. * `dataBits` {number} Number of data bits that are being transmitted. **Default:** `8`. * `callback` {Function}. * `err` {Error|null}. * Returns: {UARTPort}. Opens an UARTPort object with the specified configuration. The `baudRate` must be equal to one of these values: [0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400]. The `dataBits` must be equal to one of these values: [5, 6, 7, 8]. On NuttX, you also need to set the properties of the `configuration` in the NuttX configuration file. Using the NuttX menuconfig, it can be found at the `Device Drivers -> Serial Driver Support -> U[S]ART(N) Configuration` section. You can read more information about the usage of the UART on stm32f4-discovery board: [STM32F4-discovery](../targets/nuttx/stm32f4dis/IoT.js-API-Stm32f4dis.md#uart). **Example** ```js var uart = require('uart'); var configuration = { device: '/dev/ttyUSB0' baudRate: 115200, dataBits: 8, } var serial = uart.open(configuration, function(err) { // Do something. }); serial.closeSync(); ``` ### uart.openSync(configuration) * `configuration` {Object} * `device` {string} Mandatory configuration. The specified device path. (Linux, Nuttx and TizenRT only) * `port` {number} Mandatory configuration. The specified port number. (Tizen only) * `baudRate` {number} Specifies how fast data is sent over a serial line. **Default:** `9600`. * `dataBits` {number} Number of data bits that are being transmitted. **Default:** `8`. * Returns: {UARTPort}. Opens an UARTPort object with the specified configuration. **Example** ```js var uart = require('uart'); var configuration = { device: '/dev/ttyUSB0' baudRate: 115200, dataBits: 8, } var serial = uart.openSync(configuration); serial.closeSync(); ``` ## Class: UARTPort The UARTPort class is responsible for transmitting and receiving serial data. ### uartport.write(data, callback). * `data` {string}. * `callback` {Function}. * `err` {Error|null}. Writes the given `data` to the UART device asynchronously. **Example** ```js var serial = uart.openSync({device: '/dev/ttyUSB0'}); serial.write('Hello?', function(err) { if (err) { // Do something. } serial.closeSync(); }); ``` ### uartport.writeSync(data) * `data` {string}. Writes the given `data` to the UART device synchronously. **Example** ```js var serial = uart.openSync({device: '/dev/ttyUSB0'}); serial.writeSync('Hello?'); serial.closeSync(); ``` ### uartport.close([callback]) * `callback` {Function}. * `err` {Error|null)}. Closes the UART device asynchronously. ### uartport.closeSync() Closes the UART device synchronously. ### Event: 'data' * `callback` {Function} * `data` {Buffer} A data from the sender. **Example** ```js /* ... */ serial.on('data', function(data) { console.log('read result: ' + data.toString()); }); ``` iotjs-1.0+715/docs/api/IoT.js-API-WebSocket.md000066400000000000000000000214741371177304000204510ustar00rootroot00000000000000### Platform Support The following chart shows the availability of each WebSocket module API function on each platform. | | Linux
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | Nuttx
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | websocket.connect | O | O | O | X | O | | websocket.close | O | O | O | X | O | | websocket.ping | O | O | O | X | O | | websocket.send | O | O | O | X | O | # WebSocket WebSocket provides full-duplex communication over a TCP connection. It is designed to work over HTTP ports 80 and 443. ### Requirements WebSocket requires you to enable both the `TLS` and the `WebSocket` module. This can be done by compiling IoT.js with `--cmake-param=-DENABLE_MODULE_WEBSOCKET=ON`. Currently WebSocket only works if TLS is enabled as well. ## Class: Websocket.Server Create a new Websocket server instance. ### Websocket.Server(options[, callback]) Create a new server instance. One of `port` or `server` must be provided or an error is thrown. An HTTP server is automatically created, started, and used if `port` is set. If `secure` is set TLS server is automatically created, started and used. The `tls` module is required or an error is thrown. To use an external HTTP/S server instead, specify only `server`. In this case the HTTP/S server must be started manually. - `options` {Object} - `port` {Number} - `host` {String} Optional. Defaults to `localhost`. - `server` {Object} Optional. - `path` {String} Optional. Defaults to `/`. - `secure` {Boolean} Optional. - `key` {String} Optional. (Required on `secure` server) - `cert` {String} Optional. (Required on `secure` server) - `callback` {Function} Optional. The function which will be executed when the client successfully connected to the server. Emits a `connection` event when the connection is established. **Example** ```js var websocket = require('websocket'); var options = { port: 9999 } var server = new websocket.Server(options, Listener); function Listener(ws) { console.log('Client connected: handshake done!'); ws.on('message', function (msg) { console.log('Message received: %s', msg.toString()); ws.send(msg.toString(), {mask: true, binary: false}); //echo server.close(); }); ws.on('ping', function (msg) { console.log('Ping received: %s', msg.toString()); }); ws.on('close', function (msg) { console.log('Client close :\n' 'Reason: ' + msg.reason + ' Code: ' + msg.code); }); ws.on('error', function (msg) { console.log('Error: %s', msg.toString()); }); server.broadcast('Message to all clients', {mask: false, binary: false}); }; server.on('error', function (msg) { console.log('Error: %s', msg.toString()); }); server.on('close', function (msg) { console.log('Server close: \nReason: ' + msg.reason + ' Code: ' + msg.code); }); ``` **Example using http server** ```js var websocket = require('websocket'); var http = require('http'); var httpserver = http.createServer().listen(9999); options = { server: httpserver }; var wss3 = new websocket.Server(options, Listener); function Listener(ws) { console.log('Client connected: handshake done!'); }; ``` ### server.address() Returns an object with `port`, `family`, and `address` properties specifying the bound address, the family name, and port of the server. **Example** ```js var websocket = require('websocket'); var options = { port: 9999 } var server = new websocket.Server(options, function(ws) { }); console.log(server.address()); ``` ### server.close([reason], [code]) You can specify a close message and a close code as well. More info on them can be read here: [https://tools.ietf.org/html/rfc6455#section-7.4.1](https://tools.ietf.org/html/rfc6455#section-7.4.1 "The WebSocket Protocol Status Codes") - `reason` {String} Optional. Defaults to `Connection successfully closed`. - `code` {Number} Optional. Defaults to `1000`. Close the Websocket server, terminate all clients and emit the `close` event. **Example** ```js var websocket = require('websocket'); var options = { port: 9999 } var server = new websocket.Server(options, Listener); function Listener(ws) { console.log('Client connected: handshake done!'); server.close('Connection successfully closed', 1000); }; ``` ### server.broadcast(message [, options]) You can specify a message that will be sent to every clients. The `mask` will specify whether the data frame should be masked or not. The `binary` will specify that if the data frame mode should be text or binary, default to text. More info on them can be read here: [https://tools.ietf.org/html/rfc6455#section-5.6](https://tools.ietf.org/html/rfc6455#section-5.6 "The WebSocket Protocol Data Frames") - `message` {String} - `options` {Object} Optional. - `mask` {Boolean} Optional. Defaults to `true`. - `binary` {Boolean} Optional. Defaults to `false`. Send message to all clients. **Example** ```js var websocket = require('websocket'); var options = { port: 9999 } var server = new websocket.Server(options, Listener); function Listener(ws) { console.log('Client connected: handshake done!'); }; server.broadcast('Message to receive all client', {mask: true, binary: false}); ``` ### Event: 'connection' - `socket` {Websocket} Emitted when the handshake is complete. ### Event: 'close' - `message` {Object} - `reason` {String} - `code` {Number} Emitted when the server close. ### Event: 'error' - `error` {Error} Emmitted when an error occurs on the server. ## Class: Websocket The `Websocket` client can simultaneously receive and send data. Both `net` and `TLS` sockets are supported, however the latter is recommended, since `websocket` itself doesn't provide a secure enough context to communicate sensitive data. ### websocket.connect([host], [port], [path], [callback]) Connects to a `websocket` server, host names can be prefixed with `ws://` or `wss://`. - `host` {string} Optional. Defaults to `localhost`. - `port` {number} Optional. Defaults to `80` if the `host` begins with `ws://` or `443` with `wss://`. - `path` {Buffer | string} Optional. Defaults to `/`. If given, the client connects to that `endpoint`. - `callback` {function} Optional. The function which will be executed when the client successfully connected to the server. Emits an `open` event when the connection is established. **Example** ```js var ws = require('websocket'); var my_websocket = new ws.Websocket(); my_websocket.connect('wss://127.0.0.1', 443, '/my_endpoint', function() { my_websocket.close('Successful connection', 1000); }); ``` ### websocket.close([message], [code], [callback]) Closes the `websocket` connection with the server. You can specify a close `message` and a close `code` as well. More info on them can be read here: https://tools.ietf.org/html/rfc6455#section-7.4.1 - `message` {Buffer | string} Optional. This `message` is sent to the server as a close message, mostly for explaining the status `code`. - `code` {number} Optional. The `code` indicates the reason why the `websocket` connection was closed. Defaults to 1000. - `callback` {function} Optional. The function will be executed when the `websocket` connection is closed. Emits a `close` event when the connection is closed. ### websocket.ping([message], [mask], [callback]) Sends a `ping` to the server. If there is no response in the next 30 seconds, the connection is closed. - `message` {Buffer | string} Optional. The `message` is used to identify the `ping` frame. - `mask` {boolean} Optional. Defaults to `false`. Sets to mask the `message` or not. - `callback` {function} Optional. The function to be executed when the server sends a response to the `ping`. **Example** ```js my_websocket.ping('Ping frame 1', true, function(msg) { console.log('Pong frame successfully received for frame ' + msg); }); ``` ### websocket.send([message], [options], [callback]) Sends data to the server. It can be either `binary` or `utf8` data. - `message` {Buffer | string} The `message` to be sent to the server. - `options` {Object} - `mask` {boolean} Optional. Defaults to `false`. If set, the `message` is masked. - `binary` {boolean} Optional. Defaults to `false`. If set, the `message` is expected to be binary data. - `callback` {function} Optional. The function to be executed when the `frame` is successfully sent. **Example** ```js my_websocket.send('My first WebSocket message!', {mask: true, binary: false}, function() { console.log('The data was successfully written to the socket!'); }); ``` ## Events ### `close` Having closed the `websocket` connection, with the server, a `close` is emitted. ### `error` If an `error` occurs, the `error` event is emitted, with the corresponding error message. ### `message` The `message` event is emitted when the client receives data from the server. ### `open` Emitted when the client established a `websocket` connection with the server. iotjs-1.0+715/docs/api/IoT.js-API-reference.md000066400000000000000000000013731371177304000205150ustar00rootroot00000000000000# IoT.js modules ## Basic API * [Assert](IoT.js-API-Assert.md) * [Buffer](IoT.js-API-Buffer.md) * [DNS](IoT.js-API-DNS.md) * [Events](IoT.js-API-Events.md) * [File System](IoT.js-API-File-System.md) * [HTTP](IoT.js-API-HTTP.md) * [Module](IoT.js-API-Module.md) * [Net](IoT.js-API-Net.md) * [Process](IoT.js-API-Process.md) * [Timers](IoT.js-API-Timers.md) ## Extended API * [(ADC)](IoT.js-API-ADC.md) * [(BLE)](IoT.js-API-BLE.md) * [(GPIO)](IoT.js-API-GPIO.md) * [HTTPS](IoT.js-API-HTTPS.md) * [(I2C)](IoT.js-API-I2C.md) * [(PWM)](IoT.js-API-PWM.md) * [(SPI)](IoT.js-API-SPI.md) * [TLS](IoT.js-API-TLS.md) * [(UART)](IoT.js-API-UART.md) * [UDP/Datagram](IoT.js-API-DGRAM.md) ## Abstract interfaces * [Stream](IoT.js-API-Stream.md) *() not supported by node.js iotjs-1.0+715/docs/build/000077500000000000000000000000001371177304000150445ustar00rootroot00000000000000iotjs-1.0+715/docs/build/Build-Script.md000066400000000000000000000166721371177304000177030ustar00rootroot00000000000000## 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//debug/bin/iotjs". You can also build release binary with; ``` ./tools/build.py --buildtype=release ``` ### Arguments of IoT.js The following arguments are related to the IoT.js framework. --- #### `--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 ``` --- #### `--buildlib` With given this option, build.py will generate IoT.js output as a library. ``` ./tools/build.py ---buildlib ``` --- #### `--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="..." ``` --- #### `--clean` With given this option, build.py will clear all the build directory before start new build. ``` ./tools/build.py --clean ``` --- #### `--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 does 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. --- #### `-e, --experimental` Enable to build experimental features ``` ./tools/build.py --experimental ``` --- #### `--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-lib` Specify external library that will be linked with IoT.js. If you have multiple such libraries, supply it with multiple use of this option; ``` ./tools/build.py --external-lib="libxxx" ``` --- #### `--external-modules` Specify the path of modules.json files which should be processed (format: path1,path2,...). See also: ["How to write a new module"](../devs/Writing-New-Module.md) ``` ./tools/build.py --external-modules=/home/iotjs/my-modules-directory ``` --- #### `--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="..." ``` --- #### `--no-check-valgrind` Disable test execution with valgrind after build. ``` ./tools/build.py --no-check-valgrind ``` --- #### `--no-init-submodule` With given this option, submoduls will not initialized before start build. ``` ./tools/build.py --no-init-submodule ``` --- #### `--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="..." ``` --- #### `--profile` With given this option, build.py will use the specified profile for the build. See also: ["How to write a new module"](../devs/Writing-New-Module.md#profile) ``` ./tools/build.py --profile=./profiles/minimal.profile ``` --- #### `--run-test` * `full` | `quiet` Execute tests after build, optional argument specifies the level of output for the testrunner. ``` ./tools/build.py --run-test=full ``` --- #### `--sysroot` The location of the development tree root directory (sysroot). Must be compatible with used toolchain. ``` ./tools/build.py --sysroot=/home/iotjs/sysroot-directory ``` --- #### `--target-arch` * `arm` | `x86` | `i686` | `x86_64` | `x64` | `mips` | `noarch` Specify target architecture. ``` ./tools/build.py --target-arch=arm ``` --- #### `--target-board` * `artik10` | `artik05x` | `rpi2` | `rpi3` | `stm32f4dis` | empty Specify target board. ``` ./tools/build.py --target-os=nuttx --target-arch=arm --target-board=stm32f4dis ``` --- #### `--target-os` * `linux` | `darwin` | `osx` | `nuttx` | `tizen` | `tizenrt` | `openwrt` Specify target OS. ``` ./tools/build.py --target-os=nuttx --target-arch=arm ``` ### Arguments of JerryScript The following arguments are related to the JavaScript engine under the framework. For example they can change the enabled features of the ECMA-262 standard. --- #### `--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-debugger` Enable JerryScript debugger. See also ["Use JerryScript Debugger"](../devs/Use-JerryScript-Debugger.md). ``` ./tools/build.py --jerry-debugger ``` --- #### `--jerry-heaplimit` Specify object heap limit for JerryScript engine. ``` ./tools/build.py --jerry-heaplimit=80 ``` --- #### `--jerry-heap-section` Specify the name of the JerryScript heap section. ``` ./tools/build.py --jerry-heap-section=".ARM.__at_0x20000" ``` --- #### `--jerry-lto` With given this option, JerryScript will be built with LTO. ``` ./tools/build.py --jerry-lto ``` --- #### `--jerry-memstat` Enable memstat of JerryScript engine. ``` ./tools/build.py --jerry-memstat ``` --- #### `--jerry-profile` * `es5.1` | `es2015-subset | absolute path to a custom profile file` Specify the profile for JerryScript (default: es5.1). In JerryScript all of the features are enabled by default, so an empty profile file turns on all of the available ECMA features. See also the related [README.md](https://github.com/jerryscript-project/jerryscript/blob/master/jerry-core/profiles/README.md). E.g.: **/home/iotjs/my-jerry-profile.profile** ``` # Turn off every ES2015 feature EXCEPT the arrow functions CONFIG_DISABLE_ES2015_BUILTIN CONFIG_DISABLE_ES2015_PROMISE_BUILTIN CONFIG_DISABLE_ES2015_TEMPLATE_STRINGS CONFIG_DISABLE_ES2015_TYPEDARRAY_BUILTIN ``` ``` ./tools/build.py --jerry-profile=/home/iotjs/my-jerry-profile.profile ``` --- #### `--js-backtrace` Enable/disable backtrace information of JavaScript code (default: ON in debug and OFF in release build). ``` ./tools/build.py --js-backtrace ``` iotjs-1.0+715/docs/build/Build-for-ARTIK053-TizenRT.md000066400000000000000000000073431371177304000216550ustar00rootroot00000000000000### About This directory contains files to run IoT.js on [TizenRT](https://github.com/Samsung/TizenRT). ### How to build #### 1. Set up the build environment for Artik053 board ##### Install toolchain Get the build in binaries and libraries, [gcc-arm-none-eabi-4_9-2015q3-20150921-linux.tar](https://launchpad.net/gcc-arm-embedded/4.9/4.9-2015-q3-update). Untar the gcc-arm-none-eabi-4_9-2015q3-20150921-linux.tar and export the path like ``` tar xvf gcc-arm-none-eabi-4_9-2015q3-20150921-linux.tar export PATH=:$PATH ``` ##### Install genromfs to use romfs ```bash sudo apt-get install genromfs ``` ##### Install kconfig-frontends to use menuconfig Refer to [Kconfig-frontends Installation](https://github.com/Samsung/TizenRT#appendix) ##### Get IoT.js and TizenRT sources Clone IoT.js and TizenRT into iotjs-tizenrt directory ```bash mkdir iotjs-tizenrt cd iotjs-tizenrt git clone https://github.com/jerryscript-project/iotjs.git git clone https://github.com/Samsung/TizenRT.git ``` The following directory structure is created after these commands ```bash iotjs-tizenrt + iotjs + TizenRT ``` #### 2. Configure IoT.js This step is optional. You can edit the build config of IoT.js in `iotjs/build.config`. In order to enable modules you want, you can configure your own profile file, or you can add them as an option to the build command. For more details, please find the `ENABLE_MODULE_[NAME]` section in [How to write a new module](../devs/Writing-New-Module.md#enable_module_name). ``` ENABLE_MODULE_ADC ENABLE_MODULE_GPIO ``` ``` $ ./tools/build.py --external-modules=./my-module --cmake-param=-DENABLE_MODULE_MYMODULE=ON ``` #### 3. Configure TizenRT ```bash cd TizenRT/os/tools ./configure.sh artik053/iotjs cd .. ``` #### 4. Copy your app in ROMFS ```bash cp ../tools/fs/contents/ # make ROMFS image ../tools/fs/mkromfsimg.sh # The contents folder is later flashing into the target's /rom folder ``` NOTE: The romfs image file must not exceed 400kb. #### 5. Build IoT.js for TizenRT ```bash make IOTJS_ROOT_DIR=../../iotjs ``` If `IOTJS_ROOT_DIR` isn't given as the argument, IoT.JS codes, which are located in `external/iotjs` of TizenRT, will be used for the build. > :grey_exclamation: Trouble Shooting: Building IoT.js fails: You may encounter `arm-none-eabi-gcc: Command not found` error message while building IoT.js on a 64-bit system. This may be because the above toolchain you set uses 32-bit libs. For this matter, install the below toolchain as alternative. > ``` > $ sudo apt-get install -y libc6-i386 > ``` #### 6. Flashing ```bash make download ALL ``` > :grey_exclamation: Trouble Shooting: Flashing the binary via USB fails: Refer to [add-usb-device-rules](https://github.com/Samsung/TizenRT/blob/master/build/configs/artik053/README.md#add-usb-device-rules). Your `VendorID:ProductID` pair can be found in `lsusb` output as the below instance. > >``` >$ lsusb >Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub >Bus 003 Device 005: ID 0403:6010 Future Technology Devices International, Ltd >FT2232C Dual USB-UART/FIFO IC >``` #### 7. Run IoT.js You should use `minicom` to login to the device: ```bash $ sudo minicom -s ``` The following changes are necessaries in the `Serial port setup` menu: ``` Serial Device : /dev/ # e.g. /dev/ttyUSB0 Hardware Flow Control : No ``` After `Exit`, press an enter and the prompt should be available: ```bash TASH>> ``` The following commands help to establish Internet connection on the device: ```bash TASH>> wifi startsta TASH>> wifi join TASH>> ifconfig wl1 dhcp ``` Finally, the `iotjs` built-in command can be executed: ```bash TASH>> iotjs Usage: iotjs [options] {FILE | FILE.js} [arguments] TASH>> ``` iotjs-1.0+715/docs/build/Build-for-OpenWrt.md000066400000000000000000000060761371177304000206160ustar00rootroot00000000000000# IoT.js for OpenWrt build guide > :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. The document presents the steps required to compile the IoT.js for OpenWrt. For target device, the TP-Link WR1043ND v1.x router is used. Please be advised, that if you have a different one, minor modifications to this document could be required. IMPORTANT! As the TP-Link WR1043ND is a mips based device and mips is a big-endian architecture. A JerryScipt snapshot which was built on an little-endian system will not work correctly. Thus the IoT.js must be built with disabled snaphost mode. ## OpenWrt notes Since January 2018 the OpenWrt and LEDE project have merged into one and thus the old OpenWrt parts are now usable only from an archived repository: https://github.com/openwrt/archive ## OpenWrt toolchain setup To build the IoT.js for OpenWrt, a toolchain is required for the target router/device. The toolchain setup in this document was tested on an Ubuntu 16.04.3 LTS Linux. Steps required for toolchain creation: ### 0. Install OpenWrt build requirements ```sh $ sudo apt-get install git-core build-essential libssl-dev libncurses5-dev unzip gawk zlib1g-dev subversion mercurial ``` ### 1. Clone OpenWrt (Chaos Calmer version) ```sh $ git clone https://github.com/openwrt/archive openwrt -b chaos_calmer $ cd openwrt ``` ### 2. Run Menuconfig and configure the OpenWrt ```sh $ make menuconfig ``` Options which should be set: * Set "Target System" to "Atheros AR7xxx/AR9xxx". * Set "Target Profile" to "TP-LINK TL-WR1043N/ND". Save the configuration (as .config) and exit from the menuconfig. ### 3. Configure the environment variables ```sh $ export BUILDROOT=$(pwd) # where the openwrt root dir is $ export STAGING_DIR=${BUILDROOT}/staging_dir/ # required by the compiler $ export PATH=$PATH:${STAGING_DIR}/host/bin:${STAGING_DIR}/toolchain-mips_34kc_gcc-4.8-linaro_uClibc-0.9.33.2/bin/ ``` The name `toolchain-mips_34kc_gcc-4.8-linaro_uClibc-0.9.33.2` is created based on the menuconfig. This changes depending on the target device! ### 4. Build the OpenWrt ```sh $ make ``` ### 5. Check if the compiler was built ```sh $ mips-openwrt-linux-gcc --version # running this should print out the version information ``` At this point we have the required compiler for OpenWrt. ## Build IoT.js for OpenWrt ### 0. Check environment Please check if the `STAGING_DIR` is configured correctly and that the toolchain binary is on the `PATH`. ### 1. Run the build with the OpenWrt toolchain file ```sh $ ./tools/build.py --experimental --target-os openwrt --target-arch mips --no-snapshot --buildtype=release ``` It is advised to use release build as it is smaller than the debug build and can fit on the target router device. ### 2. Copy the binary After a successful build, the `build/mips-openwrt/release/bin/iotjs` binary file can be copied to the target device. On how to copy a binary file to an OpenWrt target device, please see the OpenWrt manual(s). iotjs-1.0+715/docs/build/Build-for-RPi2-Linux.md000066400000000000000000000106041371177304000210610ustar00rootroot00000000000000 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. This setting guide is based on the image below. |Raspbian Image | |----------| | [2017-11-29-raspbian](http://downloads.raspberrypi.org/raspbian/images/raspbian-2017-12-01/) | #### 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 "5 Interfacing Options" * Select "P5 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. From the command line type: ```bash sudo raspi-config ``` This will launch raspi-config utility. * Select "5 Interfacing Options" * Select "P6 Serial" The screen will ask you to enable Serial interface. * Select "Yes" * Select "Ok" * Select "Finish" to return to the command line. Reboot your Raspberry Pi. 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. #### Enable the SPI interface To use SPI module, the SPI interface must be enabled. From the command line type: ```bash sudo raspi-config ``` This will launch raspi-config utility. * Select "5 Interfacing Options" * Select "P4 SPI" The screen will ask you to enable SPI interface. * Select "Yes" * Select "Ok" * Select "Finish" to return to the command line. Reboot your Raspberry Pi. ### 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 ``` iotjs-1.0+715/docs/build/Build-for-RPi3-Tizen.md000066400000000000000000000063411371177304000210570ustar00rootroot00000000000000 ### 1. Tizen on RPi3 GBS build #### Prerequisites * Install SDB tool (https://developer.tizen.org/development/tizen-studio/download) It is required to send file to target, which is in Tizen Studio. * Modify sources.list of Ubuntu It is a buil system to create Tizen RPM package. To install gbs in your system, it's required to add the Tizen tools repository to the source list ``` $ sudo vim /etc/apt/sources.list ``` In Ubuntu 16.04, append the following line to the source list: ``` bash deb [trusted=yes] http://download.tizen.org/tools/latest-release/Ubuntu_16.04/ / ``` In Ubuntu 14.04, append the follwing line to the source list: ``` bash deb http://download.tizen.org/tools/latest-release/Ubuntu_14.04/ / ``` * Install GBS ``` bash sudo apt-get update sudo apt-get install gbs ``` * Prepare a GBS configuration file. You can use sample gbs configuration in config/tizen/sample.gbs.conf. See https://source.tizen.org/documentation/reference/git-build-system/configuration-file for details. #### Building * You can modify IoT.js build option on the spec file. (config/tizen/packaging/iotjs.spec) * Run gbsbuild.sh at first. Compile: ``` bash ./config/tizen/gbsbuild.sh ``` The following options are provided. ``` --debug: Build output is 'debug'. If this option is not specified, it is 'release'. --clean: Make a clean gbs build by deleting the old build root. ``` ### 2. Bring up RPi3 with Tizen Please see the following guide to bring up your RPI3 target with Tizen. You can refer "Raspberry Pi 3" section of command-line-flash part. https://developer.tizen.org/development/iot-preview/getting-started/flashing-tizen-images#command-line-flash #### Setting up serial port Please refer the tizen wiki https://wiki.tizen.org/Raspberry_Pi#Debugging #### Setting up IP You can set up IP using WiFi or Ethernet * Setup IP on RPi3 target using WiFi: https://developer.tizen.org/development/iot-preview/getting-started/flashing-tizen-images#wifi-setup * Setup IP on RPi3 target using ethernet ``` bash User id/passwd : root / tizen (target)$ ifconfig eth0 down (target)$ ifconfig eth0 192.168.1.11 netmask 255.255.255.0 up (target)$ route add default gw 192.168.1.1 ``` If you want to use your fixed ip when you reboot, add ip settings in /etc/profile. Please make sure to run before modifying /etc/profile. ``` (target) $ mount -o remount,rw / ``` ``` bash (ubuntu)$ sdb pull /etc/profile (ubuntu)$ vi profile Adding the following configurations ifconfig eth0 down ifconfig eth0 192.168.1.11 netmask 255.255.255.0 up route add default gw 192.168.1.1 (ubuntu)$ sdb push profile /etc/ ``` #### SDB connection Now you can connect RPi3 on Ubuntu PC ``` bash (ubuntu)$ sdb connect 192.168.1.11 ``` #### Install Transfer iotjs binary and test file to the device: ``` bash (ubuntu)$ sdb push ~/GBS-ROOT/local/repos/tizen_unified_m1/armv7l/RPMS/iotjs-1.0.0-0.armv7l.rpm /tmp (ubuntu)$ sdb push ./test/run_pass/test_console.js /home/owner/iotjs/ (ubuntu)$ sdb root on (ubuntu)$ sdb shell (target)$ cd /tmp (only in headless Tizen 4.0 target)$ mount -o remount,rw / (target)$ rpm -ivh --force iotjs-1.0.0-0.armv7l.rpm ``` #### Run the test: ``` bash (ubuntu)$ sdb shell (target)$ iotjs test_console.js ``` iotjs-1.0+715/docs/build/Build-for-STM32F4-NuttX.md000066400000000000000000000315741371177304000213030ustar00rootroot00000000000000 ### 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.25 | | app | nuttx-7.25 | 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/jerryscript-project/iotjs.git $ git clone https://bitbucket.org/nuttx/nuttx.git --branch nuttx-7.25 $ git clone https://bitbucket.org/nuttx/apps.git --branch nuttx-7.25 $ 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 Ctrl-A + Z + U for short in minicom screen. (For linux user) * Press [Meta](http://osxdaily.com/2013/02/01/use-option-as-meta-key-in-mac-os-x-terminal/) + Z 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. ## EXTRA STM32 SUPPORT While STM32F4-Discovery is the reference target, IoT.js can be built for other based STM32 boards: * [Nucleo-F767zi](https://www.st.com/en/evaluation-tools/nucleo-f767zi.html) The procedure is similar to STM32F4, so only specific info will be explained in following chapters: ## NUCLEO-F767ZI ### 1. Prepare for prerequisite See general instructions for STM32F4 in related chapter. ### 2. Set up the build environment for STM32F7-Nucleo board #### Supported Nuttx version for NUCLEO-F767ZI Since development is still in progress, master branch of NuttX will be used until a version is released with relevant STM32F7 support. #### Clone repository for NUCLEO-F767ZI Clone IoT.js and NuttX into iotjs-nuttx directory: ```bash $ mkdir iotjs-nuttx $ cd iotjs-nuttx $ git clone https://github.com/jerryscript-project/iotjs.git $ git clone https://bitbucket.org/nuttx/nuttx.git --branch master $ git clone https://bitbucket.org/nuttx/apps.git --branch master ``` ### 3. Build NuttX (For the first time) for NUCLEO-F767ZI See general instructions for STM32F4 in related chapter. #### Add IoT.js as a builtin application for NuttX for NUCLEO-F767ZI See general instructions for STM32F4 in related chapter. ##### Configure NuttX for NUCLEO-F767ZI See general instructions for STM32F4 in related chapter. but instead of configuring for discovery in STM32F4: ```bash $ ./configure.sh stm32f4discovery/usbnsh ``` Nucleo-144 board configuration will be needed with STM32F7 MCU (with Network Controller support): ```bash $ ./configure.sh nucleo-144/f767-netnsh ``` 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/stm32f7nucleo/config.default .config ``` ### 4. Build IoT.js for NuttX for NUCLEO-F767ZI These options are needed. ```bash --target-arch=arm --target-os=nuttx --nuttx-home=/path/to/nuttx --target-board=stm32f7nucleo --jerry-heaplimit=[..] ``` For example, ```bash $ ./tools/build.py \ --target-arch=arm --target-os=nuttx --nuttx-home=../nuttx \ --target-board=stm32f7nucleo --jerry-heaplimit=78 ``` Library files will be generated like below when build is successful, at least expect to find: ```bash $ ls build/arm-nuttx/*/lib libhttpparser.a libiotjs.a libjerrycore.a libtuv.a ``` ### 5. Build NuttX for NUCLEO-F767ZI See general instructions for STM32F4 in related chapter. ### 6. Flashing for NUCLEO-F767ZI See general instructions for STM32F4 in related chapter. ### 7. Run IoT.js for NUCLEO-F767ZI See general instructions for STM32F4 in related chapter. iotjs-1.0+715/docs/build/Build-for-Windows.md000066400000000000000000000043121371177304000206410ustar00rootroot00000000000000# IoT.js for Windows build guide > :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. The document presents the steps required to compile the IoT.js for Windows. Tested on Windows 10 and with Visual Studio 2017 Community Edition. ## Build IoT.js for Windows ### 0. Check environment Check if the following tools are installed: * GIT * Visual Studio 2017 with C++ support * Python 3 * CMake Additionally clone the IoT.js repository into a convenient directory. In the document the `C:\dev\iotjs` path will be used as an example. ### 1. Run the build script To create the required Visual Studio solution file(s) the build scripts needs to be executed. Please start a Command Prompt and navigate to the source directory where the IoT.js is cloned. In the IoT.js directory issue the following command: ```sh C:\dev\iotjs> .\tools\build.py --experimental ``` Currently for Windows the `--experimental` option is a must. Additionally if other options are required it can be specified after this option. This command will create the solution files in the build directory. Specifically in the `build\i686-windows\debug` directory in case of debug build. In case of release build the solution files will be in the `build\i686-windows\release\` directory. Please note that currently only the `i686` target is supported. ### 2. Open the IoT.js solution file In the `build\i686-windows\debug` directory the `IOTJS.sln` file should be opened with Visual Studion 2017. ### 3. Build After the IoT.js solution file is opened the Visual Studio can now start the build. Press CTRL+SHIFT+B to build the whole solution. The resulting iotjs.exe will be placed in the build's `bin\Debug` or `bin\Release` directory depending on the configuration chosen in the Visual Studio. ### Extra On Windows the test runner can also be executed. To do this the following steps are required: 1. Have a built iotjs.exe 2. Start a command prompt 3. Navigate to the IoT.js source directory 4. Execute the test runner. Ex.: ```sh C:\dev\iotjs> tools\testrunner.py build\i686-windows\debug\bin\Debug\iotjs.exe ``` iotjs-1.0+715/docs/build/Build-for-x86-Linux.md000066400000000000000000000154221371177304000207350ustar00rootroot00000000000000### 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/jerryscript-project/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/jerryscript-project/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) profile=path-to-profile (default: profiles/default.profile) 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-lib 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-parallel-build no-snapshot nuttx-home= (no default value) run-test (default is False) ``` 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. * nuttx-home: it's NuttX platform specific, to tell where the NuttX configuration and header files are. * run-test: run all tests in test folder after build. 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 specify the `ENABLE_MODULE_[NAME]=ON` CMake parameter, where `[NAME]` is the uppercase name of the module. ``` ./tools/build.py --cmake-param=-DENABLE_MODULE_DGRAM=ON ``` The second way is by using profile descriptors, where a profile file contains the list of enabled modules. E.g.: **my-profile** ``` ENABLE_MODULE_IOTJS_CORE_MODULES ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_DGRAM ``` ``` ./tools/build.py --profile=./my-profile ``` #### 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 --mem-stats ./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 ``` iotjs-1.0+715/docs/contributing/000077500000000000000000000000001371177304000164545ustar00rootroot00000000000000iotjs-1.0+715/docs/contributing/Assigned-People.md000066400000000000000000000003551371177304000217600ustar00rootroot00000000000000#### Maintainers * akosthekiss (integration) * LaszloLango (integration) * zherczeg (Steering Committee) * yichoi (Steering Committee, Project main contact) #### Committers * chokobole * glistening * hs0225 * daeyeon * bzsolt * galpeteriotjs-1.0+715/docs/contributing/Community-Guidelines.md000066400000000000000000000034141371177304000230520ustar00rootroot00000000000000All 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.
### Community Consensus, Lazy Consensus and Silent 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.

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_**)

Silent Consent means that those who do not offer a reasoned alternative in course of the discussion implicitly agree with the proposal.
### 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. iotjs-1.0+715/docs/contributing/Governance.md000066400000000000000000000133251371177304000210710ustar00rootroot00000000000000* [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.iotjs-1.0+715/docs/contributing/Patch-Submission-Process.md000066400000000000000000000071051371177304000236050ustar00rootroot00000000000000The 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/jerryscript-project/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. iotjs-1.0+715/docs/devs/000077500000000000000000000000001371177304000147065ustar00rootroot00000000000000iotjs-1.0+715/docs/devs/API-Document-Guidelines.md000066400000000000000000000163711371177304000215130ustar00rootroot00000000000000## 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
(Ubuntu) | Tizen
(Raspberry Pi) | Raspbian
(Raspberry Pi) | NuttX
(STM32F4-Discovery) | TizenRT
(Artik053) | | :---: | :---: | :---: | :---: | :---: | :---: | | {class_name}.{functionName1} | O | O | O | O | O | | {class_name}.{functionName2} | O | O | O | O | O | | {class_name}.{functionName3} | O | O | 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. iotjs-1.0+715/docs/devs/Advanced-Development.md000066400000000000000000000006501371177304000212160ustar00rootroot00000000000000 - [Inside IoT.js](Inside-IoT.js.md) - [Experimental Features](Experimental-Features.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) iotjs-1.0+715/docs/devs/Coding-Style-Guidelines.md000066400000000000000000000135711371177304000216260ustar00rootroot00000000000000* [Coding Style Guideline for C](#coding-style-guideline-for-c) * 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 Check Tool](#coding-style-check-tool) # 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++. ## Header Files ### #define guard Use #define guard in all header files. `_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 and destructor, 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_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 variable 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/) # Coding Style Check Tool When this guideline is ambiguous, just follow the result of running `./tools/check_tidy.py`. This tool helps you check your code style. You have to install `clang` and `eslint` to use this tool. And [`node.js`](https://nodejs.org/en/download/) should be installed before installing `eslint`. ```bash $ sudo apt-get update $ sudo apt-get install clang-format-3.9 $ cd iotjs $ npm install ``` Here are `./tools/check_tidy.py` options: ``` --autoedit: Automatically edit the detected clang format and eslint errors. No diffs will be displayed. ``` iotjs-1.0+715/docs/devs/Developer-Tutorial.md000066400000000000000000000162471371177304000207700ustar00rootroot00000000000000### 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`. See also: * [How to write a new module](Writing-New-Module.md) iotjs-1.0+715/docs/devs/Development-Process.md000066400000000000000000000120161371177304000211260ustar00rootroot00000000000000* [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/jerryscript-project/iotjs/issues) in GitHub, and if necessary, [create a new issue](https://github.com/jerryscript-project/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/jerryscript-project/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/jerryscript-project/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/). iotjs-1.0+715/docs/devs/Experimental-Features.md000066400000000000000000000050261371177304000214440ustar00rootroot00000000000000# 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/jerryscript-project/iotjs/blob/master/tools/build.py), with `--experimental` or `-e` option. ```bash tools/build.py --experimental tools/build.py -e --cmake-param=-DENABLE_MODULE_EXPERIMENTAL-MODULE=ON 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/jerryscript-project/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. iotjs-1.0+715/docs/devs/Extended-API-Guidelines.md000066400000000000000000000042601371177304000214670ustar00rootroot00000000000000Basically, our basic APIs are based on node.js. They will follow same form with node.js because of compatibility.
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.
For example, `readSync()`, `writeSync()`, and so on. ## Creating a module object 1. The module object should be generated using `open()` API for consistent usability. 2. `open()` API should have configurable as first argument and callback function as second argument.
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);}); gpio10.writeSync(1); ``` ## 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 has similar role should have same event name. ## Error generation 1. `error` can be generated in both JS/native side. 2. The `error` should be created in the place where it occurs. 3. In the asynchronous function, the first parameter of callback indicates an error. If it is null, the function works without error. For example, error can be generated like below: In native side, ```c iotjs_jargs_t jargs = iotjs_jargs_create(2); if (!result) { iotjs_jargs_append_error(&jargs, "GPIO Error"); } ``` 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. If it is possible, use the functions provided by `libtuv` (File open, read, write, etc.) 2. Callback function in API argument should be always optional. iotjs-1.0+715/docs/devs/Inside-IoT.js.md000066400000000000000000000306111371177304000175500ustar00rootroot00000000000000Inside IoT.js ============= * [Design](#design) * [Javascript Binding](#javascript-binding) * [jerry_value_t](#jerry_value_t) * [Native handler](#native-handler) * [Embedding API](#embedding-api) * [libuv Binding](#libuv-binding) * [iotjs_handlewrap_t](#iotjs_handlewrap_t) * [iotjs_reqwrap_t](#iotjs_reqwrap_t) * [IoT.js Core](#iotjscoe) * [Life cycle of IoT.js](#life-cycle-of-iot.js) * [Builtin modules](#builtin-modules) * [Event loop](#event-loop) # Design IoT.js is built on top of [JerryScript](http://jerryscript.net/) and [libuv](http://libuv.org). JerryScript is a lightweight Javascript engine intended to run on small devices for IoT and libuv is a library for supporting asynchronous I/O. There is a layer that binds JerryScript and libuv to IoT.js. We will deals with the layer in [Javascript Binding](#javascript-binding) and [libuv Binding](#javascript-binding) section on this document respectively. IoT.js core layer locates above these binding layer. This core layer plays a central role in this project providing upper layer with fundamental functionality of running main event loop, interacting with Javascript engine, managing I/O resources via libuv, managing life cycle of objects, providing builtin modules, and so forth. [IoT.js Core](#iotjs-core) section deals with the layer in detail. IoT.js provides APIs for user applications to help creating IoT friendly services. You can see the list of API from [IoT.js API Reference](../api/IoT.js-API-reference.md). # Javascript Binding Many modern Javascript Engines come with [embedding API](#embedding-api) to provide functionality for compiling and executing Javascript program, accessing Javascript object and its value, handling errors, managing lifecyles of objects and so on. You can think of Javascript binding layer as an interface between upper layer (IoT.js core) and underlying Javascript engine. Although IoT.js only supports JerryScript for now, there will be a chance that we extend supporting Javascript engine (such as [Duktape](http://duktape.org/) or [V8](https://code.google.com/p/v8/)) in the future. For this reason, we want to keep the layer independent from a specific Javascript engine. You can see interface of the layer in [iotjs_binding.h](../../src/iotjs_binding.h). ## jerry_value_t `jerry_value_t` struct stands for a real Javascript object. Upper layers will access Javascript object via this struct. This struct provides following functionalities: * Creating a Javascript object using `iotjs_jval_create_*()` constructor. * Creating a Javascript object by a value. * Creating a Javascript function object where its body is implemented in C. * Creating a Javascript Error object. * Creating reference for a Javascript object increasing reference count. * Increasing reference count. * Decreasing reference count. * Checking object type. * Retrieving value. * Calling a Javascript function. * Evaluating a Javascript script. * Set and Get corresponding native data to the Javascript object. ## Native handler Some operations - such as file I/O, networking, device control, multitasking, and etc - can not be performed by pure Javascript. IoT.js uses a mechanism called "native handler" to enable such operations performed from Javascript. You can regard native handler as Javascript function object with its body implemented in C. You might think it is somewhat similar to [FFI](https://en.wikipedia.org/wiki/Foreign_function_interface). In a wide sense, it's true for native handler is for calling C function from Javascript. But in a narrow sense, it's not true. Usually main purpose of [FFI](https://en.wikipedia.org/wiki/Foreign_function_interface) is to call a routine written in one language from a program written in another. After a routine was invoked, it is common that the routine just do what it is supposed to do without knowing the surrounding context except arguments. Whereas native handler does know that it is being called from Javascript (actually it is a Javascript function although not written in Javascript) and does access surrounding Javascript execution context using [embedding API](#embedding-api). ## Embedding API Many Javascript engines these days provide embedding API. IoT.js uses the API to create [builtin module](#builtin-modules) and [native handler](#native-handler). See following link if you want further information about the API: * [JerryScript API](http://jerryscript.net/api-reference) * [Duktape API](http://duktape.org/api.html) * [V8 embedder's guide](https://developers.google.com/v8/embed) * [SpiderMonkey API](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_reference) # libuv Binding IoT.js is using [libuv](http://libuv.org/) to perform various asynchronous I/O and threading. Because IoT.js adopts asynchronous programming model, libuv plays very important role in this project. Actually the [main loop](#event-loop) of IoT.js is libuv event loop waiting I/O event, picks the event, and dispatches it to corresponding event handler function. You can read [libuv design document](http://docs.libuv.org/en/v1.x/design.html) to get detailed information about asynchronous programming model based on libuv. ## iotjs_handlewrap_t `iotjs_handlewrap_t` is to bind a Javascript object and a libuv handle (e.g. file descriptor) together. `iotjs_handlewrap_t` inherits `iotjs_jobjectwrap_t` since it is linked with a Javascript object. Unlike `iotjs_jobjectwrap_t`, `iotjs_handlewrap_t` increases RC for the Javascript object when an instance of it is created to prevent GC while the handle is alive. The reference counter will be decreased after the handle is closed, allowing GC. ## iotjs_reqwrap_t `iotjs_reqwrap_t` is for wrapping libuv request data and Javascript callback function. And make sure that the Javascript callback function is alive during the I/O operation. Let's look at how asynchronous I/O are treated in IoT.js: 1. Javascript module calls builtin function to perform I/O applying arguments including callback. 2. Builtin creates `iotjs_reqwrap_t` to wrap `uv_req_s` and Javascript callback function. 3. Builtin calls libuv to perform the I/O. 4. After I/O finished, libuv calls builtin after handler. 5. Builtin after handler takes `iotjs_reqwrap_t` containing I/O result and Javascript callback function. 6. Builtin after handler calls Javascript callback. 7. Builtin after handler release `iotjs_reqwrap_t` by calling `iotjs_*reqwrap_dispatch()` `iotjs_reqwrap_t` does not inherits `iotjs_handlewrap_t` for wrapping the callback function object. Note that `HandleWrap` does not increase reference count of wrapping object. It does not guarantee guarantee liveness of the object even if the wrapper is alive. On the other hand, `iotjs_reqwrap_t` increases the reference count for the callback function and decreases when it is being freed to guarantee the liveness of callback function during the request is ongoing. After request is finished and `iotjs_reqwrap_t` released by calling `iotjs_*reqwrap_dispatch()`, the callback function could be collected by GC when it need to be. # IoT.js Core ## Life cycle of IoT.js _Note:_ _We are currently focusing on implementing IoT.js upon JerryScript engine._ _Implementation of initializing process depends on JerryScript API._ _That could be changed when we adopt other Javascript engines._ _Anyway, in this chapter we will explain initialization process based on current implementation._ The process of IoT.js can be summarized as follow: 1. Initialize JerryScript engine. 2. Execute empty script * Create initial Javascript context. 3. Initialize builtin modules. * Create builin modules including ['process'](../api/IoT.js-API-Process.md). 4. Evaluate ['iotjs.js'](../../src/js/iotjs.js). * Generate entry function. 5. Run the entry function passing 'process'. 1. Initialize 'process' module. 2. Load user application script. 3. Run user application. 6. Run [event loop](#event-loop) until there are no more events to be handled. 7. Clean up. ## Builtin modules "Builtin" is Javascript objects implemented in C using [embedding API](#embedding-api), in Javascript or both. The list of builtin objects can be found in ['modules.json'](../../src/modules.json). Native parts of builtin modules are implemented as [native handler](#native-handler), so they are able to access underlying system using libuv, C library, and system call. The [basic modules and extended modules](../api/IoT.js-API-reference.md) provided by IoT.js are called 'Builtin module' because it will be included in the IoT.js binary. There is a [tool](../../tools/js2c.py) that transfer Javascript script source file into C file and this C file will be compiled into the IoT.js binary. Some native modules are bound to global object while others are on demand. On demand modules will be created at the moment when it is first required and will not released until the program terminates. ## Event loop _Note:_ _It would be helpful to read [libuv design overview](http://docs.libuv.org/en/v1.x/design.html) to understand asynchronous I/O programming model if you are not familiar with it._ _Note:_ _In this section we will see simple file open example and relevant code segment. You can find the source files at ['iotjs.c'](../../src/iotjs.c), [`iotjs_module_fs.c`](../../src/module/iotjs_module_fs.c) and ['fs.js'](../../src/js/fs.js)_ IoT.js follows asynchronous I/O programming model proposed by libuv to perform non-blocking, single-threaded, asynchronous I/O. You can find main loop of the program at the file ['iotjs.c'](../../src/iotjs.c) in the source tree. It looks like this: ```c // Run event loop. 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)); } } while (more); ``` While running a IoT.js application, it could make requests for I/O operations using [IoT.js API](../api/IoT.js-API-reference.md). For example, You can write a code for opening 'hello.txt' file and printing file descriptor out like this: ```js fs.open('hello.txt', 'r', function(err, fd) { console.log('fd:' + fd); }); conosle.log('requested'); ``` To handle the request, IoT.js will wrapping the request and callback function using `iotjs_reqwrap_t`. ```c iotjs_fsreqwrap_t* req_wrap = iotjs_fsreqwrap_create(jcallback); ``` libuv will take charge of actual I/O processing taking the request. ```c uv_fs_t* fs_req = iotjs_fsreqwrap_req(req_wrap); int err = uv_fs_open(iotjs_environment_loop(env), fs_req, path, flags, mode, AfterAsync); ``` Since all I/O are treated as non-blocking, calling for async I/O API returns immediately right after request was sent to libuv. And then next line of javascript program will be executed immediately without waiting the I/O. Thus in the above example 'requested' will be printed out right after file open request was made. If there were I/O requests, `uv_run()` in the main loop waits by polling the requests until at least one of the request processing were finished. When a result for a request was produced, internal part of libuv calls corresponding handler function (let it be after function) back. Usually, the after function retrieves I/O result and `iotjs_reqwrap_t` object from request data. And calling the javascript callback function with the result. ```c iotjs_fsreqwrap_t* req_wrap = (iotjs_fsreqwrap_t*)(req->data); // get request wrapper const jerry_value_t* cb = iotjs_fsreqwrap_jcallback(req_wrap); // javascript callback function iotjs_jargs_t jarg = iotjs_jargs_create(2); iotjs_jargs_append_null(&jarg); // in case of success. iotjs_jargs_append_number(req->result); // result - file descriptor for open syscall // callback iotjs_jhelper_make_callback(cb, iotjs_jval_get_null(), &jarg); // cleanup iotjs_jargs_destroy(&jarg); iotjs_fsreqwrap_dispatched(req_wrap); ``` For above file open example, calling javascript callback function would result execution of the handler. ```js function(err, fd) { console.log('fd:' + fd); } ``` One iteration of event loop is finished and `uv_run()` finally returns after all results were handled. Next, it calls next tick handler. ```c more |= iotjs_process_next_tick(); ``` And for next step, main event loop checks if there were no more request to be treated. ```c if (more == false) { more = uv_loop_alive(iotjs_environment_loop(env)); } ``` If there are another iteration of the loop executed. Otherwise, main event loop ends. iotjs-1.0+715/docs/devs/IoT.js-Developer's-Certificate-of-Origin-1.0.md000066400000000000000000000046131371177304000250620ustar00rootroot00000000000000The 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: " % content) ``` Please refer [Git Hooks](http://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) for more information.iotjs-1.0+715/docs/devs/IoT.js-Module-Generator.md000066400000000000000000000454471371177304000215230ustar00rootroot00000000000000# C/C++ API to IoT.js module generator The module generator is an automatic code generating tool, which gives help for developers to avoid writing lots of code. It generates a binding layer between a C/C++ API and the IoT.js framework and creates a native module which can be easily imported and used in JavaScript. **NOTE:** The tool can't handle perfect when there are complex user-defined types, pointers to structures, multiple indirections etc. in the native library. The input of the generator is a directory, which contains the C/C++ header files and the static library of the API. 1. [Dependencies](#dependencies) 2. [Features](#features) - [Classes](#classes) - [Functions](#functions) - [Variables](#variables) - [Enums](#enums) - [Macros](#macros) - [Namespaces](#namespaces) 3. [Supported types](#supported-types) - [Examples](#examples) 4. [Usage](#usage) - [Optional arguments](#optional-arguments) 5. [Quick example](#quick-example) ## Dependencies: The tool uses libclang to analyze the given library and get the necessary informations. ### Clang library: #### Linux: ```bash apt install libclang1-6.0 ``` **NOTE:** The python binding searches for `libclang.so` as deafult. After installing `libclang1-6.0` you should add a symlink to `path/to/libclang-6.0.so` like below: ```bash cd /usr/lib/x86_64-linux-gnu/ sudo ln -s libclang-6.0.so libclang.so ``` #### Windows: [Download link](http://releases.llvm.org/6.0.0/LLVM-6.0.0-win32.exe) **NOTE:** The tool has been tested with 32 bit binary. You should add LLVM to the system PATH, so python binding can find it. ### Python binding for Clang: ```bash pip install clang ``` or optionally for Linux: ```bash apt install python-clang-6.0 ``` ## Features: The C/C++ library is represented as an object in the JavaScript environment. This object is the result of the `require` function call with the right module name parameter. The generated module name is the name of the input folder with `'_module'` suffix. If the input folder is `my_api` then you can load the module with the code below: ```javascript var lib = require('my_api_module'); ``` #### Classes: If there is a class in the C++ library, the module object has a property with the name of the class, which is a constructor. You can create an object in JavaScript, if you call the constructor with the right parameters. The returned JavaScript variable has some properties, which are represent the members and methods of the class. C++ header: ```cpp class MyClass { int x; public: MyClass(): x(0) {} MyClass(int x): x(x) {} void foo(void); // print x }; ``` JS file: ```javascript var cpp_lib = require('module_name'); var obj1 = new cpp_lib.MyClass(); var obj2 = new cpp_lib.MyClass(42); obj1.foo(); // print 0 obj2.foo(); // print 42 ``` #### Functions: Every function from the C/C++ library are represented as properties of the library object. **C :** If there is a declaration, like `void foo(int);` in the C library, then the object has a property with the name `foo`. ```javascript var c_lib = require('module_name'); c_lib.foo(42); // call the C function ``` **C++ :** The different between C and C++ functions, that you can call C++ functions with the same name, but with different parameter lists. If there is a declaration, like `void foo(int = 0);` in the C++ library, you can use it as below. It works in the case of constructors and methods too. ```javascript var cpp_lib = require('module_name'); cpp_lib.foo(); // call the C++ function with the default parameter cpp_lib.foo(42); ``` **NOTE**: There are cases when you can't decide on the API side what is the real type of a JavaScript value. For example there are two overloads of a C++ function: `void f(int);` `void f(double);` In the binding layer you can check that the parameter is a number or not, but you don't know it is an integer or a floating point number, so it isn't clear which overload you should call. The generator's solution for the problem is using suffixes. If you generate the binding layer for the example code above you will get a message like that: ``` WARN: The following overload of f has been renamed to f_$0 : void f ( int ) WARN: The following overload of f has been renamed to f_$1 : void f ( double ) ``` The rigth usage of the **f** function in that case is the following: ```javascript var cpp_lib = require('module_name'); cpp_lib.f_$0(1); // Use f_$0 with integer parameter cpp_lib.f_$1(1.5); // Use f_$1 with floating point parameter ``` #### Variables: The global variables of the C/C++ library are also represented as properties. If there is a declaration, like `int a;` in the C library, then the object has a property with the name `a`, and you can get and set its value, but if there is a definition, like `const int b = 42;` you can only read the value from the property and you can not modify it. C/C++ header: ```c int i; ``` JS file: ```javascript var lib = require('module_name'); lib.i = 1; // set the value of 'i' console.log(lib.i); // print 1 ``` #### Enums: Enums work like constants above. You can read the value of the enumerator from a property, but you can not modify it. C/C++ header: ```c enum abc {A, B, C}; ``` JS file: ```javascript var lib = require('module_name'); console.log(lib.A); // print 0 console.log(lib.B); // print 1 console.log(lib.C); // print 2 ``` #### Macros: Macros also work like constants. You can read the value of the macro from a property, but you can not modify it. There are three supported macro types. * If the macro defines a character literal, like `#define C 'c'`. * If the macro defines a string literal, like `#define STR "str"`. * If the macro defines a numeric literal, or contains some kind of operation, but the result is a number, like `#defines ZERO 0` or `#define TWO 1 + 1`. It also works, if the macro contains other macro identifiers. C/C++ header: ```c #define ONE 1 #define TWO 2 #define THREE ONE + TWO ``` JS file: ```javascript var lib = require('module_name'); console.log(lib.ONE); // print 1 console.log(lib.TWO); // print 2 console.log(lib.THREE); // print 3 ``` #### Namespaces: In JavaScript a namespace represented as an object, which is set to another object as property. Concretely to the object, which represent the scope where the namespace is. C++ header: ```c namespace my_ns { void foo(void); namespace nested { void foo(void); } } ``` JS file: ```javascript var cpp_lib = require('module_name'); cpp_lib.my_ns.foo(); // my_ns::foo with (lib.my_ns.nested) { foo(); // my_ns::nested::foo } ``` **NOTE**: If there is a `using` command for a namespace in the native header, you also have to call functions etc. through the namespace object. You can use `with` in JavaScript to reduce the code. ## Supported types: The table below shows which JavaScript type represent the particular C/C++ type. ### Fundamental types: | C/C++ type | JS type | | - | - | | void | undefined | | char | one length String | | integers (short/int/long etc.) | Number | | enum | Number | | float / double | Number | | _Bool / bool | Boolean | ### Record types: If you would like to create a record type variable you have to call a constructor through the library object. | C/C++ type | JS type | | - | - | | struct / union / class | Object | ### Pointer types: If there is a char* or a pointer to a number (short/int/float etc.) in a native function's parameter list and you call this function from JavaScript with a String or TypedArray the binding layer alloc memory for the native pointers. If after the native call the pointers won't be used you should modify the source code of the binding layer and free them. | C/C++ type | JS type | | - | - | | char* | String / Null | | signed char* | Int8Array | | unsigned char* | Uint8Array | | short* | Int16Array | | unsigned short* | Uint16Array | | int* / long* / long long* | Int32Array | | unsigned int* / unsigned long* / unsigned long long* | Uint32Array | | float* | Float32Array | | double* / long double* | Float64Array | | function pointer (only as function parameter) | Function / Null | | record pointer (only as function parameter) | Object / Null | **NOTE**: Other types are not supported, which means that you need to implement how you would like to use these parts of the C/C++ API. #### Examples: ##### `void` ```c void f(void); ``` ```javascript var a = lib.f(); // 'a' == undefined ``` ##### `char` ```c char c; char f(char); ``` ```javascript lib.c = 'c'; var a = lib.f('b'); ``` ##### `integers` ```c int i; int f(int); ``` ```javascript lib.i = 42; var a = lib.f(5); ``` ##### `enum` ```c typedef enum {A, B, C} my_enum; my_enum e; my_enum f(my_enum); ``` ```javascript lib.e = lib.B; var a = lib.f(lib.A); ``` ##### `float/double` ```c float f; double d; float f(float); double g(double); ``` ```javascript lib.f = 1.5; lib.d = 2.5; var f = lib.f(1.5); var d = lib.g(lib.d); ``` ##### `bool` ```c _Bool b; _Bool f(_Bool); ``` ```javascript lib.b = true; var a = lib.f(false); ``` ##### `char*/char[]` If there is global pointer to a char, its value can be `null` or a `String`. ```c char * c_ptr; char c_arr[6]; char* f(char*); char* g(char[5]); ``` ```javascript lib.c_ptr = 'some string'; // lib.c_arr = 'maximum string length is 5'; NOT WORK lib.c_arr = 'works'; var f = lib.f('other string'); // returned value can be null or String var g = lib.g('1234'); ``` ##### `int*/int[]` If there is global pointer to a number, its value can be `null` or a `TypedArray`. If there is an array of numbers, it will be a `TypedArray` in the JS environment, and you can set the values by indexing. ```c int * i_ptr; int i_arr[5]; int* f(int*); int* g(int[5]); ``` ```javascript var typed_array = new Int32Array(new ArrayBuffer(8), 0, 2); typed_array[0] = 10; typed_array[1] = 20; lib.i_ptr = typed_array; lib.i_ptr = null; // lib.i_arr = typed_array; NOT WORK lib.i_arr[0] = 1; lib.i_arr[1] = 2; lib.i_arr[2] = 3; var f = lib.f(null); // returned value can be null or TypedArray var g = lib.g(typed_array); ``` ##### `function` Function pointers supported as parameters. There can be cases when it does not work correctly, if the function will be called asynchronous. ```c typedef int (callback)(void); int f(callback c) { return c(); } ``` ```javascript var a = lib.f(function () { return 42; }); ``` Let's see a dummy example, when function pointers work incorrectly. ```c typedef void (cb)(void); cb cb_arr[2]; void foo(cb c) { static int i = 0; cb_arr[i++] = c; } void bar(void) { cb_arr[0](); } ``` ```javascript lib.foo(function() { console.log('first callback'); }); lib.foo(function() { console.log('second callback'); }); // the second foo call overwrite the first callback function // it will print 'second callback', which is not the expected lib.bar(); ``` ##### `struct / union / class` ```cpp typedef struct { int i; char c; } S; typedef union { int i; char c; } U; class C { int i = 42; public: int get_i() {return i;} }; S s; U u; C c; S f(S); U g(U); C h(C); void ptr(S*); ``` ```javascript var s = new lib.S(); var u = new lib.U(); var c = new lib.C(); s.i = 42; s.c = 's'; lib.s = s; lib.s.i = 0; // var o = { // i: 42, // c: 'o' // } // // lib.f(o); NOT WORK 'o' is not a valid S type object var other_s = lib.f(s); var other_u = lib.g(u); var other_c = lib.h(c); lib.ptr(s); console.log(lib.c.get_i()); ``` ## Usage: You can generate a module using the following command: ```bash # assuming you are in iotjs folder $ tools/iotjs-generate-module.py [OPTIONS] ``` The `` should contain the header files and the static library of the C/C++ API. `` is the language of the API, which can be `c` or `c++`. These are required arguments for the script. The script generates the source files to the `iotjs/tools/module_generator/output/_module/` folder. The module name will be `_module`. If you would like to modify how the module should work, you have to make some changes in the generated `.c` or `.cpp` file. #### Optional arguments: The script has some optional arguments, which are the following: ##### `--out-dir` The output folder of the generated module. Default is `tools/module_generator/output` ```bash $ tools/iotjs-generate-module.py --out-dir ``` ##### `--off` * `functions` | `variables` | `enums` | `macros` Turn off the processing of the given part of the API, which means that the script will not generate any code for this part, so you can not use this in the JS environment. ```bash $ tools/iotjs-generate-module.py --off=enums --off=macros ``` ##### `--define` Define a macro for the clang preprocessor. ```bash $ tools/iotjs-generate-module.py --define FOO --define BAR=42 ``` ##### `--defines` A file, which contains macro definitions for the clang preprocessor. `macro_defines.txt`: ```txt FOO BAR=42 ``` ```bash $ tools/iotjs-generate-module.py --defines macro_defines.txt ``` ##### `--include` Add include path to search for other files. ```bash $ tools/iotjs-generate-module.py --include path/to/the/include/folder/ ``` ##### `--includes` A file, which contains include paths. `includes.txt`: ```txt path/to/include/folder other/path/to/other/folder ``` ```bash $ tools/iotjs-generate-module.py --includes includes.txt ``` ## Quick example: #### Directory structure: * iotjs/ * my_api/ * foo/ * foo.h * bar.h * libexample.a #### Header files: foo.h: ```c #define N 10 int foo(int x); //return x+x ``` bar.h: ```c typedef enum {A, B, C} flags; void bar(); // print "Hello!" ``` #### Build: ```bash # assuming you are in iotjs folder $ tools/iotjs-generate-module.py ../my_api/ c tools/build.py --external-module=tools/module_generator/output/my_api_module --cmake-param=-DENABLE_MODULE_MY_API_MODULE=ON ``` #### Usage: api.js: ```javascript // the name of the module is same as the directory name with '_module' suffix var c_lib = require('my_api_module'); var x = c_lib.foo(2); console.log(x); // print 4 c_lib.bar(); // print 'Hello!' console.log(c_lib.N); // print 10 console.log(c_lib.B); // print 1 ``` #### Generated binding layer: my_api_js_binding.c: ```c #include #include #include "jerryscript.h" #include "my_api_js_binding.h" // external function for API functions or for getters / setters jerry_value_t bar_handler (const jerry_value_t function_obj, const jerry_value_t this_val, const jerry_value_t args_p[], const jerry_length_t args_cnt) { // check the count of the external function's arguments if (args_cnt != 0) { char const *msg = "Wrong argument count for bar(), expected 0."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); } // native function call bar (); jerry_value_t ret_val = jerry_create_undefined (); return ret_val; } // external function for API functions or for getters / setters jerry_value_t foo_handler (const jerry_value_t function_obj, const jerry_value_t this_val, const jerry_value_t args_p[], const jerry_length_t args_cnt) { // check the count of the external function's arguments if (args_cnt != 1) { char const *msg = "Wrong argument count for foo(), expected 1."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); } // check the type of a jerry_value_t variable if (!jerry_value_is_number (args_p[0])) { char const *msg = "Wrong argument type for foo(), expected number."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); } // create an integer / floating point number from a jerry_value_t int arg_0 = (int)jerry_get_number_value (args_p[0]); // native function call int result = foo (arg_0); jerry_value_t ret_val = jerry_create_number (result); return ret_val; } // init function for the module jerry_value_t Init_my_api() { jerry_value_t object = jerry_create_object(); // set an external function as a property to the module object jerry_value_t bar_name = jerry_create_string ((const jerry_char_t*)"bar"); jerry_value_t bar_func = jerry_create_external_function (bar_handler); jerry_value_t bar_ret = jerry_set_property (object, bar_name, bar_func); jerry_release_value (bar_name); jerry_release_value (bar_func); jerry_release_value (bar_ret); // set an external function as a property to the module object jerry_value_t foo_name = jerry_create_string ((const jerry_char_t*)"foo"); jerry_value_t foo_func = jerry_create_external_function (foo_handler); jerry_value_t foo_ret = jerry_set_property (object, foo_name, foo_func); jerry_release_value (foo_name); jerry_release_value (foo_func); jerry_release_value (foo_ret); // set an enum constant as a property to the module object jerry_property_descriptor_t A_prop_desc; jerry_init_property_descriptor_fields (&A_prop_desc); A_prop_desc.is_value_defined = true; A_prop_desc.value = jerry_create_number (A); jerry_value_t A_name = jerry_create_string ((const jerry_char_t *)"A"); jerry_value_t A_ret = jerry_define_own_property (object, A_name, &A_prop_desc); jerry_release_value (A_ret); jerry_release_value (A_name); jerry_free_property_descriptor_fields (&A_prop_desc); // set an enum constant as a property to the module object jerry_property_descriptor_t B_prop_desc; jerry_init_property_descriptor_fields (&B_prop_desc); B_prop_desc.is_value_defined = true; B_prop_desc.value = jerry_create_number (B); jerry_value_t B_name = jerry_create_string ((const jerry_char_t *)"B"); jerry_value_t B_ret = jerry_define_own_property (object, B_name, &B_prop_desc); jerry_release_value (B_ret); jerry_release_value (B_name); jerry_free_property_descriptor_fields (&B_prop_desc); // set an enum constant as a property to the module object jerry_property_descriptor_t C_prop_desc; jerry_init_property_descriptor_fields (&C_prop_desc); C_prop_desc.is_value_defined = true; C_prop_desc.value = jerry_create_number (C); jerry_value_t C_name = jerry_create_string ((const jerry_char_t *)"C"); jerry_value_t C_ret = jerry_define_own_property (object, C_name, &C_prop_desc); jerry_release_value (C_ret); jerry_release_value (C_name); jerry_free_property_descriptor_fields (&C_prop_desc); jerry_value_t N_js = jerry_create_number (N); // set a global constant or a macro as a property to the module object jerry_property_descriptor_t N_prop_desc; jerry_init_property_descriptor_fields (&N_prop_desc); N_prop_desc.is_value_defined = true; N_prop_desc.value = N_js; jerry_value_t N_prop_name = jerry_create_string ((const jerry_char_t *)"N"); jerry_value_t N_return_value = jerry_define_own_property (object, N_prop_name, &N_prop_desc); jerry_release_value (N_return_value); jerry_release_value (N_prop_name); jerry_free_property_descriptor_fields (&N_prop_desc); return object; } ``` iotjs-1.0+715/docs/devs/IoT.js-Package-(outdated).md000066400000000000000000000077261371177304000216330ustar00rootroot00000000000000**The content on this page does not work. Currently, there is no plan to run ipm server. This document will leave for discussion in the future.** IoT.js follows the practice of node.js npm to provide module development community with separate IoT.js own registry. * To see what it actually is, please visit [www.npmjs.com](https://www.npmjs.com/), and also [docs.npmjs.com](https://docs.npmjs.com/). * To avoid confusion with the original server, we'll call it "ipm", for IoT.js Package Manager. * Current status of "ipm" is started and it's for developers so has no separate web page. We need to develop them. * "npm" program is used for publish and download modules. We may fork when customization is needed. ### Installing "npm" ``` sudo apt-get install npm ``` ### Setting registry As ipm uses different server, you need to change registry information ``` npm config set registry="http://ipm.iotjs.net:5984/registry/_design/app/_rewrite" ``` ### Adding your account You may have to register your account if you plan to publish some packages, for example, ``` npm set init.author.name "Your Name" npm set init.author.email "you@example.com" npm set init.author.url "http://yourblog.com" npm adduser ``` Please set to your real name and email address. url is optional. ### Publish a package cd to your package folder you wish to publish and init ``` npm init ``` It'll ask information for your package, for an example; ``` Press ^C at any time to quit. name: (t) echotest version: (1.0.0) 0.0.1 description: simple echo server entry point: (index.js) test command: git repository: keywords: license: (ISC) About to write to /(your working folder)/package.json: { "name": "echotest", "version": "0.0.1", "description": "simple echo server", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "(your name) (your blog page)", "license": "ISC" } Is this ok? (yes) yes ``` and all things are good to go, publish. ``` npm publish ./ ``` Please visit [npmjs.org](https://docs.npmjs.com/getting-started/publishing-npm-packages) for detailed explanations. ### About the license of each packages IoT.js is released under Apache 2.0 license, [this page](../License.md). We assume you also agree on this license when publishing to ipm registry. ### Downloading packages "npm" provides local and global packages and you may be working on some powerful machines. In IoT devices this may be somewhat different. It may not have enough memory, power, network or even no console to give commands. So it can have several scenarios depending on the device you may be working on. This may be some of them; 1) Download to your machine with Linux, Mac or Windows. * Install packages to your powerful machine * Send it to the IoT device through copy to memory card * or send through serial line, BT, USB with old time kermit or z-modem 2) If it has a WiFi the download directly from the registry * But to make this work, we need to develop a small shell program with iotjs. * This can be done with built-in module downloader, we need to develop this. * Issue [#75](https://github.com/jerryscript-project/iotjs/issues/75) to track 3) If your IoT is very small and even has no writable file system * Package modules should be built-in to IoT.js at compile time. * We should also develop this. 4) any more ideas? As for case 1), ``` (cd to some working directory) npm install (copy node_modules folder to your device) ``` As mentioned above, npm has local and global packages. But for IoT.js lets stick on the local only. For some cases running on ROTS there may not be any globals place. ### Package license You may use ipm packages freely under Apache 2.0 license, read [this page](../License.md) ### Searching for packages Searching is possible with search command. See [docs.npmjs.com/cli/search](https://docs.npmjs.com/cli/search). ``` npm search ``` If you omit the keyword, it'll list all packages registered. iotjs-1.0+715/docs/devs/Logging-IoT.js-execution.md000066400000000000000000000021711371177304000217240ustar00rootroot00000000000000### Logging Support IoT.js supports logging on Debug version. It can output message strings to the stderr console by default or any file you give. To add a message line, use one of three macros in the source, defined in iotjs_module_debug.h ``` DLOG() DDLOG() DDDLOG() ``` DLOG is level 1 which means it's an error so that should be displayed. DDLOG is for warning messages and is level 2. DDDLOG is information you need while IoT.js is running, which is level 3. Default is 1. ### Setting logging level In linux, use `IOTJS_DEBUG_LEVEL` environment variable to change the level, for example, if you want to see error and warning messages; ``` export IOTJS_DEBUG_LEVEL=2 ``` Numbers can be 0, 1, 2 or 3. If you give 0, it will be silence, no message. ### Logging to a file To save to a file, use also the environment variable, for example; ``` export IOTJS_DEBUG_LOGFILE="/home/iotjsdev/iotjslog.txt" ``` You must have file creation rights to that directory. File will be overwritten on every start, so don't run the program before looking inside or backing it up. To disable logging to a file, ``` unset IOTJS_DEBUG_LOGFILE ``` will do. iotjs-1.0+715/docs/devs/Memory-savings-with-libtuv.md000066400000000000000000000200201371177304000224160ustar00rootroot00000000000000Memory usage with libtuv on iotjs is described here and compared to libuv. * Compared with release version in i686. * iotjs version: hash f8e8391d8c30a76c2f82644e454056c11a2bad1a #### runtime memory usage compare with libuv running iotjs 1) how to build 1-1) with libuv ``` ./tools/build.py --buildtype=release --nochecktest ``` 1-2) with libtuv ``` ./tools/build.py --buildtype=release --nochecktest --tuv ``` 2) memory usage measurement with valgrind running `test httpserver` ``` valgrind ./build/i686-linux/release/iotjs/iotjs ./test/run_pass/test_httpserver.js ``` 2-1) with libuv ``` ==5740== Memcheck, a memory error detector ==5740== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. ==5740== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info ==5740== Command: ./build/i686-linux/release/iotjs/iotjs ./test/run_pass/test_httpserver.js ==5740== ==5740== ==5740== HEAP SUMMARY: ==5740== in use at exit: 0 bytes in 0 blocks ==5740== total heap usage: 959 allocs, 959 frees, 482,669 bytes allocated ==5740== ==5740== All heap blocks were freed -- no leaks are possible ==5740== ==5740== For counts of detected and suppressed errors, rerun with: -v ==5740== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) ``` 2-2) with libtuv ``` ==7584== Memcheck, a memory error detector ==7584== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. ==7584== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info ==7584== Command: ./build/i686-linux/release/iotjs/iotjs ./test/run_pass/test_httpserver.js ==7584== ==7584== ==7584== HEAP SUMMARY: ==7584== in use at exit: 0 bytes in 0 blocks ==7584== total heap usage: 955 allocs, 955 frees, 481,645 bytes allocated ==7584== ==7584== All heap blocks were freed -- no leaks are possible ==7584== ==7584== For counts of detected and suppressed errors, rerun with: -v ==7584== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) ``` 482,669 vs 481,645 = 1,024 bytes saved #### binary size 1) build ``` ./tools/build.py --buildtype=release --nochecktest --target-arch=arm --target-os=linux ./tools/build.py --buildtype=release --nochecktest --target-arch=arm --target-os=linux --tuv ``` 2) binary size in i686-linux * libuv : 213,130 / iotjs: 2,512,292, stripped: 782,152 * libtuv: 103,158 / iotjs: 2,460,357, stripped: 732,776 * itself: 109,972 smaller, iotjs: 51,935(striped 49,376) saved 3) binary size in arm-linux * libuv : 176,614 / iotjs: 2,543,525, stripped: 536,460 * libtuv: 83,458 / iotjs: 2,506,455, stripped: 507,548 * itself: 93,156 smaller, iotjs: 37,070(stripped: 28,912) saved #### libuv vs libtuv itself 1) use `tuvtester` as an application to compare. 2) codes changes to make both libuv.a and libtuv.a interchangeable. 2-1) as libtuv uses c++ compiler, wrap all codes with ``` extern "C" { ... } ``` 2-2) for libuv, give `libuv.a` by changing `tuvtest.cmake` file. use file from iotjs build. ``` target_link_libraries(${TUVTESTNAME} LINK_PUBLIC #${TARGETLIBNAME} "/(absolute path to libuv)/libuv.a" ${TUV_LINK_LIBS}) ``` 2-3) some functions that does not exist in libuv. add this bottom of in runner_main.cpp ``` #if 1 #define uv__handle_deinit(h) \ do { \ QUEUE_REMOVE(&(h)->handle_queue); \ QUEUE_INIT(&(h)->handle_queue); \ } \ while (0) void uv_deinit(uv_loop_t* loop, uv_handle_t* handle) { QUEUE* q; uv_handle_t* h; QUEUE_FOREACH(q, &loop->handles_queue) { h = QUEUE_DATA(q, uv_handle_t, handle_queue); if (h == handle) { uv__handle_deinit(handle); break; } } } #endif ``` 2-4) remove test codes that does not run with libuv, tested codes are like this in runner_list.h ``` #define TEST_LIST_ALL(TE) \ TE(idle_basic, 5000) \ TE(timer_init, 5000) \ \ TE(condvar_2, 5000) \ TE(condvar_3, 5000) \ TE(cwd, 5000) \ \ TE(fs_file_noent, 5000) \ TE(fs_file_sync, 5000) \ TE(fs_file_async, 5000) \ TE(fs_file_write_null_buffer, 5000) \ TE(fs_stat_missing_path, 5000) \ TE(fs_open_dir, 5000) \ TE(fs_file_open_append, 5000) \ TE(fs_read_file_eof, 5000) \ \ TE(threadpool_queue_work_simple, 5000) \ // shutdown_eof should be last of tcp test, it'll stop "echo_sevrer" #if defined(__linux__) #define TEST_LIST_EXT(TE) \ #else #define TEST_LIST_EXT(TE) \ #endif #define HELPER_LIST_ALL(TE) \ ``` 3) measure run with valgrind ``` valgrind ./build/i686-linux/release/bin/tuvtester ``` 3-1) with libuv ``` ==24952== Memcheck, a memory error detector ==24952== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. ==24952== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info ==24952== Command: ./build/i686-linux/release/bin/tuvtester ==24952== Run Helpers... [idle_basic ]...OK [timer_init ]...OK [condvar_2 ]...OK [condvar_3 ]...OK [cwd ]...OK [fs_file_noent ]...OK [fs_file_sync ]...OK [fs_file_async ]...OK [fs_file_write_null_buffer ]...OK [fs_stat_missing_path ]...OK [fs_open_dir ]...OK [fs_file_open_append ]...OK [fs_read_file_eof ]...OK [threadpool_queue_work_simple ]...OK Waiting Helpers to end... ==24952== ==24952== HEAP SUMMARY: ==24952== in use at exit: 0 bytes in 0 blocks ==24952== total heap usage: 44 allocs, 44 frees, 1,727 bytes allocated ==24952== ==24952== All heap blocks were freed -- no leaks are possible ==24952== ==24952== For counts of detected and suppressed errors, rerun with: -v ==24952== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) ``` 3-2) with libtuv ``` ==26621== Memcheck, a memory error detector ==26621== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. ==26621== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info ==26621== Command: ./build/i686-linux/release/bin/tuvtester ==26621== Run Helpers... [idle_basic ]...OK [timer_init ]...OK [condvar_2 ]...OK [condvar_3 ]...OK [cwd ]...OK [fs_file_noent ]...OK [fs_file_sync ]...OK [fs_file_async ]...OK [fs_file_write_null_buffer ]...OK [fs_stat_missing_path ]...OK [fs_open_dir ]...OK [fs_file_open_append ]...OK [fs_read_file_eof ]...OK [threadpool_queue_work_simple ]...OK Waiting Helpers to end... ==26621== ==26621== HEAP SUMMARY: ==26621== in use at exit: 0 bytes in 0 blocks ==26621== total heap usage: 40 allocs, 40 frees, 991 bytes allocated ==26621== ==26621== All heap blocks were freed -- no leaks are possible ==26621== ==26621== For counts of detected and suppressed errors, rerun with: -v ``` 3-3) result * libuv: 1,727 bytes * libtuv: 991 bytesiotjs-1.0+715/docs/devs/Native-Module-vs-JS-Module.md000066400000000000000000000051271371177304000220710ustar00rootroot00000000000000# 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. iotjs-1.0+715/docs/devs/Optimization-Tips.md000066400000000000000000000056141371177304000206410ustar00rootroot00000000000000## 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; ``` ## Modify the default jerry-heap size By default, JerryScript uses 16 bit long (8 byte aligned) pointers, that is why the maximum addressable area (on the JerryScript heap) is 512 KB. Of course, these compressed pointers can be extended to 32 bit to cover the entire address space of a 32 bit system. You can modify the default JerryScript heap size by using the `--jerry-heaplimit` argument when building IoT.js. If that value is bigger than `512`, the JerryScript submodule is compiled with 32 bit pointer support. iotjs-1.0+715/docs/devs/Test-Guidelines.md000066400000000000000000000046461371177304000202470ustar00rootroot00000000000000### 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_[_` 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/jerryscript-project/iotjs/blob/master/test/testsets.json), and set attributes (timeout, skip, ...) on the test case if it needs. #### Test set descriptor * [`test/testsets.json`](https://github.com/jerryscript-project/iotjs/blob/master/test/testsets.json) ``` { "directory": [ { "name": "filename", "skip": ["all"], "reason": "reason of skipping", "timeout": seconds, "expected-failure": true, "required-modules": ["my_module"], "required-features": ["es-262-feature"] }, ... ], ... } ``` - _directory_: group of tests - _name_: filename = testname - _skip_: platform where the test must be skipped. ["all", "darwin", "linux", "nuttx", "tizen", "tizenrt"] **(optional)** - _reason_: it belongs to skip property, reason of skipping. **(optional)** - _timeout_: timeout in seconds **(optional)** - _expected-failure_: identifies the "must fail" testcases. Still catches segfaults, IOTJS_ASSERT and JERRY_ASSERT. Default: false [true, false] **(optional)** ### How to Test When you build ``iotjs`` binary successfully, you can run test runner with this binary. ```bash tools/testrunner.py /path/to/iotjs ``` #### Set test options Some basic options are provided. Existing test options are listed as follows; ``` -h, --help show this help message and exit --quiet show or hide the output of the tests --skip-modules list module list to skip test of specific modules --testsets TESTSETS JSON file to extend or override the default testsets --timeout TIMEOUT default timeout for the tests in seconds --valgrind check tests with Valgrind --coverage measure JavaScript coverage ``` iotjs-1.0+715/docs/devs/Use-JerryScript-Debugger.md000066400000000000000000000053671371177304000217770ustar00rootroot00000000000000## Jerry-debugger Detailed description about the debugger is available [here](https://github.com/jerryscript-project/jerryscript/blob/master/docs/07.DEBUGGER.md). ### Enable debugger support in IoT.js To enable the debugger support under IoT.js, the `--jerry-debugger` option should be passed to the `tools/build.py`. The server part of the debugger is intergrated into the binary of IoT.js. ### Usage To start the debugger-server: ` --start-debug-server test.js` It is important to note that optional parameters (such as `--debugger-wait-source` or `--debugger-port `) should be specified after `--start-debug-server` in order to work properly. #### Sending source to the debugger remotely The `--debugger-wait-source` makes the client wait until the source files are sent by the debugger-client. The file argument is ignored in this case, therefore doesn't need to be specified. IoT.js is also capable of resetting the context, thus, there's no need to restart the environment if the remote source is changed. **Important note**: Remote sources must be sent in correct order! IoT.js compiles them in the order they are received, so file(s) used with `require` should be sent first, and the file(s) using them after. #### Select Channel and Protocol There are two available extension-provided channels, websocket and rawpacket, and two protocols, tcp and serial. Each initializes the debugger and blocks until a client connects. If you want to specify the debugger channel (default: websocket) or protocol (default: tcp) over the communication you can do with the `--debug-channel [websocket|rawpacket]` and `--debug-protocol [tcp|serial]` options: ` --start-debug-server --debugger-channel rawpacket --debug-protocol tcp test.js` #### Setting the debugger port If you want to specify the port number of the debugger-server with tcp connection (default: 5001), you can do so with the `--debugger-port ` option: ` --start-debug-server --debugger-port 8080 test.js` #### Configure the serial port If you want to configure parameters for serial port (default: /dev/ttyS0,115200,8,N,1), you can do with `--debug-serial-config CONFIG` option: ` --start-debug-server --debug-channel rawpacket --debug-protocol serial --debug-serial-config "/dev/ttyUSB0,115200,8,N,1" test.js` #### Available Clients * [JerryScript console debugger client](https://github.com/jerryscript-project/jerryscript/blob/master/jerry-debugger/jerry-client-ws.py) * [Iot.js Code](https://github.com/jerryscript-project/iotjscode) * [Jerryscript debugger Chrome webtool](https://github.com/jerryscript-project/jerryscript-debugger-ts) **Note**: When snapshot support is enabled, you won't be able to examine js-modules that are loaded from snapshots. iotjs-1.0+715/docs/devs/Writing-New-Module.md000066400000000000000000000473551371177304000206430ustar00rootroot00000000000000# How to write a new module This document provides a guide on how to write a module for IoT.js. Contents * Writing JavaScript Module * Writing Native Module * Platform dependent native parts * Native handler * Arguments and Return * Wrapping native object with JS object * Callback * Writing "Mixed" Module * Using native module in JavaScript module * Advanced usage * Module specific CMake file * Writing Dynamically loadable modules (N-API) * Module structure generator See also: * [Inside IoT.js](Inside-IoT.js.md) * [Native Module vs. JS module](Native-Module-vs-JS-Module.md) * [Optimization Tips](Optimization-Tips.md) * [Developer Tutorial](Developer-Tutorial.md) ## Writing JavaScript Module 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 anywhere on your filesystem. * Use `./tools/build.py --external-modules=my-module` when building * Enable your module in a profile or as an additional CMake parameter **Important:** the name of the module must be in lowercase. It is not allowed to use uppercase characters. Your new module will look like below: my-module/js/mymodule.js: ```javascript module.exports = { foo: function() { console.log("OK"); }, bar: 123 } ``` my-module/modules.json: ```json { "modules": { "mymodule": { "js_file": "js/mymodule.js", "require": ["buffer", "console"] } } } ``` user.js: ```javascript var mymodule = require('mymodule'); mymodule.foo(); // prints "OK" console.log(mymodule.bar); // prints "123" ``` and execute: ```sh $ ./tools/build.py --external-modules=./my-module --cmake-param=-DENABLE_MODULE_MYMODULE=ON $ ${PATH_TO}/iotjs user.js OK 123 ``` **Note**: `--cmake-param=-DENABLE_MODULE_MYMODULE=ON` option must be used in case of an external module, because the default profile enables only the basic and core modules. ### ENABLE_MODULE_[NAME] An uppercase `ENABLE_MODULE_[NAME]` CMake variable will be generated for every module, where `NAME` is the name of the module in the `modules.json`. To enable or disable a module by setting the corresponding `ENABLE_MODULE_[NAME]` to ON or OFF. It will override the defult settings of the profile. ### Profile The purpose of the "profile" is to describe the default settings of enabled modules for the build. A profile file is a list of `ENABLE_MODULE_[NAME]` macros. Those module whos `ENABLE_MODULE_[NAME]` macro is not listed will be disabled by defult. my-module/mymodule.profile: ``` ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_IOTJS_CORE_MODULES ENABLE_MODULE_MYMODULE ``` Execute: ```bash ./tools/build.py --external-modules=./my-module --profile=my-module/mymodule.profile ``` ## Writing Native Module 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 of you can call JerryScript API functions directly. * For native modules you must define an `init` function that provides the JS object that represents your module. * You can define multiple native files. * Directory of your module will be added to the include path. * Use `./tools/build.py --external-modules=my-module` when building. * Enable your module in a profile or as an additional CMake parameter. Your new module will look like below: my-module/my_module.c: ```javascript #include "iotjs_def.h" jerry_value_t InitMyNativeModule() { jerry_value_t mymodule = jerry_create_object(); iotjs_jval_set_property_string_raw(mymodule, "message", "Hello world!"); return mymodule; } ``` my-module/modules.json: ```json { "modules": { "mymodule": { "native_files": ["my_module.c"], "init": "InitMyNativeModule" } } } ``` user.js: ```javascript var mymodule = require('mymodule'); console.log(mymodule.message); // prints "Hello world!" ``` and execute: ```sh $ ./tools/build.py --external-modules=./my-module --cmake-param=-DENABLE_MODULE_MYMODULE=ON $ ${PATH_TO}/iotjs user.js Hello world! ``` ### Platform dependent native parts You can define the platform dependent low level parts in the `modules.json`. Structure of the directory of the custom module: ``` my_module |-- linux |-- my_module_platform_impl.c |-- nuttx |-- my_module_platform_impl.c |-- tizenrt |-- my_module_platform_impl.c |-- other |-- my_module_platform_impl.c |-- modules.json |-- my_module.h |-- my_module.c ``` modules.json: ```json { "modules": { "mymodule": { "platforms": { "linux": { "native_files": ["linux/my_module_platform_impl.c"] }, "nuttx": { "native_files": ["nuttx/my_module_platform_impl.c"] }, "tizenrt": { "native_files": ["tizenrt/my_module_platform_impl.c"] }, "undefined": { "native_files": ["other/my_module_platform_impl.c"] } }, "native_files": ["my_module.c"], "init": "InitMyModule" } } } ``` **Note**: Undefined platform means a general implementation. If the module does not support your platform then it will use the `undefined` platform implementation. ### Library dependency It is possible that the external module depends/requires an already compiled third-party shared object or static library. Such libraries can be specified in the `modules.json` file so they will be linked when the IoT.js module is used. To specify third-party libraries the `external_libs` key should be used in the module specification. For example in the `modules.json`: ```json { "modules": { "mymodule": { "platforms": { "linux": { "native_files": ["linux/my_module_platform_impl.c"], "external_libs": ["curl"] } }, "native_files": ["my_module.c"], "external_libs": ["lib_shared_on_all_platforms_if_it_truly_exists"], "init": "InitMyNativeModule" } } } ``` The `external_libs` key can be specified on the module level or for each platform also. ### 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 JS_FUNCTION(Stdout) { DJS_CHECK_ARGS(1, string); iotjs_string_t msg = JS_GET_ARG(0, string); fprintf(stdout, "%s", iotjs_string_data(&msg)); iotjs_string_destroy(&msg); return jerry_create_undefined(); } ``` Using `JS_GET_ARG(index, type)` macro inside `JS_FUNCTION()` will read JS-side argument. Since JavaScript values can have dynamic types, you must check if argument has valid type with `DJS_CHECK_ARGS(number_of_arguments, type1, type2, type3, ...)` macro, which throws JavaScript TypeError when given condition is not satisfied. `JS_FUNCTION()` must return with an `jerry_value_t` into JS-side. #### 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 { jerry_value_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 jerry_value_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 jerry_value_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. ## Writing "Mixed" Modules Modules could be a combination of JS and native code. In that case the Javascript file must export the objects of the module. In such cases the native part will be hidden. For simple explanation, `console` module will be used as an example. ``` src |-- js |-- console.js |-- modules |-- iotjs_module_console.c |-- modules.json ``` modules.json ```json { "modules": { ... "console": { "native_files": ["modules/iotjs_module_console.c"], "init": "InitConsole", "js_file": "js/console.js", "require": ["util"] }, ... } } ``` ### 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 Console.prototype.log = native.stdout(util.format.apply(this, arguments) + '\n'); ``` Where `native` is the JS object returned by the native `InitConsole` function in `iotjs_module_console.c`. **Note**: `native` is undefined if there is no native part of the module. ### Using bridge module to communicate between C and JavaScript module Bridge module provides two interfaces for sending synchronous and asynchronous message from Javascript to the native module. The Native module simply rersponds back to the requst using a simple inteface that can create return message. Of course you can use the IoT.js and JerryScript APIs to respond directly to the request of JavaScript module, but sometimes using a simpliffied method is more efficient in providing simple functionality in a short time. For example, JavaScript module can request resource path synchronously, and native module can simply return a resource path by just calling a function. in the bridge_sample.js of bridge_sample module ```javascript bridge_sample.prototype.getResPath = function(){ return this.bridge.sendSync("getResPath", ""); }; ``` in the iotjs_bridge_sample.c of bridge_sample module ```c if (strncmp(command, "getResPath", strlen("getResPath")) == 0) { iotjs_bridge_set_return(return_message, "res/"); return 0; } ``` For the complete sample code, please see the bridge_sample in samples/bridge_sample folder. ## Advanced usage ### Module specific CMake file For each module, it is possible to define one extra cmake file. This can be done by specifying the `cmakefile` key file for a module in the related `modules.json` file. For example: ```json { "modules": { "demomod": { ... "cmakefile": "module.cmake" } } } ``` This `module.cmake` is a module-specific CMake file which will be searchd for in the module's base directory. In this file it is possible to specify additonal dependecies, build targets, and other things. However, there are a few important rules which must be followed in the CMake file: * The `MODULE_DIR` and `MODULE_BINARY_DIR` will be set by the IoT.js build system. Do NOT overwrite them in the CMake file! * The `MODULE_NAME` CMake variable must be set. Example: `set(MODULE_NAME "demomod")` * The `add_subdirectory` call must specify the output binary dir. Please use this template: `add_subdirectory(${MODULE_DIR}/lib/ ${MODULE_BASE_BINARY_DIR}/${MODULE_NAME})` where `lib/` is a subdirectory of the module directory. * If there is an extra library which should be used during linking, the following template should be used: `list(APPEND MODULE_LIBS demo)` where `demo` is the extra module which must be linked. Any number of modules can be appended to the `MODULE_LIBS` list variable. * The source files which are specified in the `modules.json` file must NOT be specified in the CMake file. An example module CMake file: ``` set(MODULE_NAME "mymodule") add_subdirectory(${MODULE_DIR}/myLib/ ${MODULE_BASE_BINARY_DIR}/${MODULE_NAME}) list(APPEND MODULE_LIBS myLib) ``` To ease creation of modules which contains extra CMake files there is a module generator as described below. ## Writing Dynamically loadable modules (N-API) IoT.js support N-API for building and loading native addons. To create such modules the source files must be compiled into a shared object and must have a special entry point defined. See also: * [N-API in IoT.js](../api/IoT.js-API-N-API.md) * [N-API module registration](https://nodejs.org/docs/latest-v10.x/api/n-api.html#n_api_module_registration) macro. N-API modules are registered in a manner similar to other modules except that instead of using the `NODE_MODULE` macro the following is used: ```C NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) ``` The next difference is the signature for the `Init` method. For a N-API module it is as follows: ```C napi_value Init(napi_env env, napi_value exports); ``` The return value from `Init` is treated as the `exports` object for the module. The `Init` method is passed an empty object via the `exports` parameter as a convenience. If `Init` returns NULL, the parameter passed as `exports` is exported by the module. N-API modules cannot modify the `module` object but can specify anything as the `exports` property of the module. To add the method `hello` as a function so that it can be called as a method provided by the addon: ```C napi_value Init(napi_env env, napi_value exports) { napi_status status; napi_property_descriptor desc = {"hello", NULL, Method, NULL, NULL, NULL, napi_default, NULL}; status = napi_define_properties(env, exports, 1, &desc); if (status != napi_ok) return NULL; return exports; } ``` To set a function to be returned by the `require()` for the addon: ```C napi_value Init(napi_env env, napi_value exports) { napi_value method; napi_status status; status = napi_create_function(env, "exports", NAPI_AUTO_LENGTH, Method, NULL, &method); if (status != napi_ok) return NULL; return method; } ``` To define a class so that new instances can be created (often used with [Object Wrap][]): ```C // NOTE: partial example, not all referenced code is included napi_value Init(napi_env env, napi_value exports) { napi_status status; napi_property_descriptor properties[] = { { "value", NULL, NULL, GetValue, SetValue, NULL, napi_default, NULL }, DECLARE_NAPI_METHOD("plusOne", PlusOne), DECLARE_NAPI_METHOD("multiply", Multiply), }; napi_value cons; status = napi_define_class(env, "MyObject", New, NULL, 3, properties, &cons); if (status != napi_ok) return NULL; status = napi_create_reference(env, cons, 1, &constructor); if (status != napi_ok) return NULL; status = napi_set_named_property(env, exports, "MyObject", cons); if (status != napi_ok) return NULL; return exports; } ``` If the module will be loaded multiple times during the lifetime of the Node.js process, use the `NAPI_MODULE_INIT` macro to initialize the module: ```C NAPI_MODULE_INIT() { napi_value answer; napi_status result; status = napi_create_int64(env, 42, &answer); if (status != napi_ok) return NULL; status = napi_set_named_property(env, exports, "answer", answer); if (status != napi_ok) return NULL; return exports; } ``` This macro includes `NAPI_MODULE`, and declares an `Init` function with a special name and with visibility beyond the addon. This will allow IoT.js to initialize the module even if it is loaded multiple times. ## Module structure generator As previously shown, there are a few files required to create a module. These files can be createad manually or by the `tools/iotjs-create-module.py` script. The module generator can generate two types of modules: * basic built-in module which is compiled into the IoT.js binary. * shared module which can be dynamically loaded via the `require` call. To generate a module with the IoT.js module generator the module template should be specified and the name of the new module. **Important note:** The module name must be in lowercase. The `template` paramter for the module creator is optional, if it is not specified basic modules are created. The generated module(s) have simple examples in it which can be used to bootstrap ones own module(s). On how to use them please see the previous parts of this document. ### Basic module generation Example basic module generation: ``` $ python ./iotjs/tools/iotjs-create-module.py --template basic demomod Creating module in ./demomod loading template file: ./iotjs/tools/module_template/module.cmake loading template file: ./iotjs/tools/module_template/modules.json loading template file: ./iotjs/tools/module_template/js/module.js loading template file: ./iotjs/tools/module_template/src/module.c Module created in: /mnt/work/demomod ``` By default the following structure will be created by the tool: ``` demomod/ |-- js |-- module.js |-- module.cmake |-- modules.json |-- src |-- module.c ``` ### Shared (N-API) module generation Example shared module generation: ``` $ python ./iotjs/tools/iotjs-create-module.py --template shared demomod Creating module in ./demomod loading template file: ./iotjs/tools/module_templates/shared_module_template/CMakeLists.txt loading template file: ./iotjs/tools/module_templates/shared_module_template/README.md loading template file: ./iotjs/tools/module_templates/shared_module_template/js/test.js loading template file: ./iotjs/tools/module_templates/shared_module_template/src/module_entry.c Module created in: /mnt/work/demomod ``` The generated `demomod` will have a `CMakeLists.txt` file which contains path variables to the IoT.js headers and JerryScript headers. These path variables are absolute paths and required to the module compilation. Please adapt the paths if required. Additionnally the `README.md` file contains basic instructions on how to build and test the new module. iotjs-1.0+715/docs/targets/000077500000000000000000000000001371177304000154165ustar00rootroot00000000000000iotjs-1.0+715/docs/targets/nuttx/000077500000000000000000000000001371177304000166005ustar00rootroot00000000000000iotjs-1.0+715/docs/targets/nuttx/stm32f4dis/000077500000000000000000000000001371177304000205025ustar00rootroot00000000000000iotjs-1.0+715/docs/targets/nuttx/stm32f4dis/IoT.js-API-Stm32f4dis.md000066400000000000000000000114761371177304000244120ustar00rootroot00000000000000## 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 |iotjs-1.0+715/docs/targets/tizen/000077500000000000000000000000001371177304000165475ustar00rootroot00000000000000iotjs-1.0+715/docs/targets/tizen/SystemIO-Pin-Information-Tizen.md000066400000000000000000000025551371177304000247120ustar00rootroot00000000000000When you use System I/O module that is `GPIO`, `PWM`, `SPI`, `I2C`, and `UART`, you should know specified pin, bus or port number. ### GPIO #### ARTIK530 | GPIO Name | Pin Number | GPIO Name | Pin Number | | :---: | :---: | :---: | :---: | | GPIO0 | 128 | GPIO1 | 129 | | GPIO2 | 130 | GPIO3 | 46 | | GPIO4 | 14 | GPIO5 | 41 | | GPIO6 | 25 | GPIO7 | 0 | | GPIO8 | 26 | GPIO9 | 27 | #### Raspberry Pi3 | GPIO Name | Pin Number | GPIO Name | Pin Number | | :---: | :---: | :---: | :---: | | GPIO4 | 4 | GPIO5 | 5 | | GPIO6 | 6 | GPIO12 | 12 | | GPIO13 | 13 | GPIO16 | 16 | | GPIO17 | 17 | GPIO18 | 18 | | GPIO19 | 19 | GPIO20 | 20 | | GPIO21 | 21 | GPIO20 | 20 | | GPIO23 | 23 | GPIO24 | 24 | | GPIO25 | 25 | GPIO26 | 26 | | GPIO27 | 27 | - | - | ### PWM #### ARTIK530 | PWM Name | Pin Number | | :---: | :---: | | PWM0 | 2 | ### SPI #### ARTIK530 | SPI Name | Bus Number | Chip Select | | :---: | :---: | :---: | | SPI | 2 | 0 | #### Raspberry Pi3 | SPI Name | Bus Number | Chip Select | | :---: | :---: | :---: | | SPI0(CS0) | 0 | 0 | | SPI0(CS1) | 0 | 1 | ### I2C #### ARTIK530 | I2C Name | Bus Number | | :---: | :---: | | I2C | 1 | #### Raspberry Pi3 | I2C Name | Bus Number | | :---: | :---: | | I2C | 1 | #### UART #### ARTIK530 | UART Name | Port Number | | :---: | :---: | | UART0 | 4 | #### Raspberry Pi3 | UART Name | Port Number | | :---: | :---: | | UART0 | 0 |iotjs-1.0+715/docs/targets/tizenrt/000077500000000000000000000000001371177304000171155ustar00rootroot00000000000000iotjs-1.0+715/docs/targets/tizenrt/artik05x/000077500000000000000000000000001371177304000205645ustar00rootroot00000000000000iotjs-1.0+715/docs/targets/tizenrt/artik05x/IoT.js-API-artik053.md000066400000000000000000000010601371177304000241600ustar00rootroot00000000000000## Artik053 module ## `Pin` To use system IO, such as PWM, you must know pin name. ### `PWM Pin Number` For example, ``` javascript var pwm = new require('pwm')(); var config = { pin: 0, period: 0.001, dutyCycle: 0.5 } var pwm0 = pwm.open(config, function() { if (err) { throw err; } }); ``` The following is a list of PWM pin numbers. | PWM Pin number | GPIO Name | | :---: | :---: | | 0 | XPWMTOUT_0 | | 1 | XPWMTOUT_1 | | 2 | XPWMTOUT_2 | | 3 | XPWMTOUT_3 | | 4 | XPWMTOUT_4 | | 5 | XPWMTOUT_5 | | 6 | XPWMTOUT_6 | iotjs-1.0+715/include/000077500000000000000000000000001371177304000144405ustar00rootroot00000000000000iotjs-1.0+715/include/iotjs.h000066400000000000000000000020301371177304000157340ustar00rootroot00000000000000/* 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_IOTJS_H #define IOTJS_IOTJS_H #ifdef __cplusplus #define IOTJS_EXTERN_C extern "C" #else /* !__cplusplus */ #define IOTJS_EXTERN_C extern #endif /* !__cplusplus */ IOTJS_EXTERN_C int iotjs_entry(int argc, char** argv); IOTJS_EXTERN_C void iotjs_conf_console_out(int (*fp)(int level, const char* fmt, ...)); #endif /* IOTJS_IOTJS_H */ iotjs-1.0+715/include/node_api.h000066400000000000000000001050201371177304000163650ustar00rootroot00000000000000// Pulled from nodejs/node#8742cbfef0d31d7fad49ced7d11e6827b932b101 v10.8.0 using tools/pull-napi.sh #ifndef SRC_NODE_API_H_ #define SRC_NODE_API_H_ #include #include #include "node_api_types.h" struct uv_loop_s; // Forward declaration. #ifndef NAPI_VERSION #ifdef NAPI_EXPERIMENTAL // Use INT_MAX, this should only be consumed by the pre-processor anyway. #define NAPI_VERSION 2147483647 #else // The baseline version for N-API #define NAPI_VERSION 3 #endif #endif #ifdef _WIN32 #ifdef BUILDING_NODE_EXTENSION #ifdef EXTERNAL_NAPI // Building external N-API, or native module against external N-API #define NAPI_EXTERN /* nothing */ #else // Building native module against node with built-in N-API #define NAPI_EXTERN __declspec(dllimport) #endif #else // Building node with built-in N-API #define NAPI_EXTERN __declspec(dllexport) #endif #else #define NAPI_EXTERN /* nothing */ #endif #ifdef _WIN32 # define NAPI_MODULE_EXPORT __declspec(dllexport) #else # define NAPI_MODULE_EXPORT __attribute__((visibility("default"))) #endif #ifdef __GNUC__ #define NAPI_NO_RETURN __attribute__((noreturn)) #else #define NAPI_NO_RETURN #endif typedef napi_value (*napi_addon_register_func)(napi_env env, napi_value exports); typedef struct { int nm_version; unsigned int nm_flags; const char* nm_filename; napi_addon_register_func nm_register_func; const char* nm_modname; void* nm_priv; void* reserved[4]; } napi_module; #define NAPI_MODULE_VERSION 1 #if defined(_MSC_VER) #pragma section(".CRT$XCU", read) #define NAPI_C_CTOR(fn) \ static void __cdecl fn(void); \ __declspec(dllexport, allocate(".CRT$XCU")) void(__cdecl * fn##_)(void) = \ fn; \ static void __cdecl fn(void) #else #define NAPI_C_CTOR(fn) \ static void fn(void) __attribute__((constructor)); \ static void fn(void) #endif #ifdef __cplusplus #define EXTERN_C_START extern "C" { #define EXTERN_C_END } #else #define EXTERN_C_START #define EXTERN_C_END #endif #define NAPI_MODULE_X(modname, regfunc, priv, flags) \ EXTERN_C_START \ static napi_module _module = \ { \ NAPI_MODULE_VERSION, \ flags, \ __FILE__, \ regfunc, \ #modname, \ priv, \ {0}, \ }; \ NAPI_C_CTOR(_register_ ## modname) { \ napi_module_register(&_module); \ } \ EXTERN_C_END #define NAPI_MODULE(modname, regfunc) \ NAPI_MODULE_X(modname, regfunc, NULL, 0) // NOLINT (readability/null_usage) #define NAPI_MODULE_INITIALIZER_BASE napi_register_module_v #define NAPI_MODULE_INITIALIZER_X(base, version) \ NAPI_MODULE_INITIALIZER_X_HELPER(base, version) #define NAPI_MODULE_INITIALIZER_X_HELPER(base, version) base##version #define NAPI_MODULE_INITIALIZER \ NAPI_MODULE_INITIALIZER_X(NAPI_MODULE_INITIALIZER_BASE, \ NAPI_MODULE_VERSION) #define NAPI_MODULE_INIT() \ EXTERN_C_START \ NAPI_MODULE_EXPORT napi_value \ NAPI_MODULE_INITIALIZER(napi_env env, napi_value exports); \ EXTERN_C_END \ NAPI_MODULE(NODE_GYP_MODULE_NAME, NAPI_MODULE_INITIALIZER) \ napi_value NAPI_MODULE_INITIALIZER(napi_env env, \ napi_value exports) #define NAPI_AUTO_LENGTH SIZE_MAX EXTERN_C_START NAPI_EXTERN void napi_module_register(napi_module* mod); NAPI_EXTERN napi_status napi_get_last_error_info(napi_env env, const napi_extended_error_info** result); NAPI_EXTERN NAPI_NO_RETURN void napi_fatal_error(const char* location, size_t location_len, const char* message, size_t message_len); // Getters for defined singletons NAPI_EXTERN napi_status napi_get_undefined(napi_env env, napi_value* result); NAPI_EXTERN napi_status napi_get_null(napi_env env, napi_value* result); NAPI_EXTERN napi_status napi_get_global(napi_env env, napi_value* result); NAPI_EXTERN napi_status napi_get_boolean(napi_env env, bool value, napi_value* result); // Methods to create Primitive types/Objects NAPI_EXTERN napi_status napi_create_object(napi_env env, napi_value* result); NAPI_EXTERN napi_status napi_create_array(napi_env env, napi_value* result); NAPI_EXTERN napi_status napi_create_array_with_length(napi_env env, size_t length, napi_value* result); NAPI_EXTERN napi_status napi_create_double(napi_env env, double value, napi_value* result); NAPI_EXTERN napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result); NAPI_EXTERN napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result); NAPI_EXTERN napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result); NAPI_EXTERN napi_status napi_create_string_latin1(napi_env env, const char* str, size_t length, napi_value* result); NAPI_EXTERN napi_status napi_create_string_utf8(napi_env env, const char* str, size_t length, napi_value* result); NAPI_EXTERN napi_status napi_create_string_utf16(napi_env env, const char16_t* str, size_t length, napi_value* result); NAPI_EXTERN napi_status napi_create_symbol(napi_env env, napi_value description, napi_value* result); NAPI_EXTERN napi_status napi_create_function(napi_env env, const char* utf8name, size_t length, napi_callback cb, void* data, napi_value* result); NAPI_EXTERN napi_status napi_create_error(napi_env env, napi_value code, napi_value msg, napi_value* result); NAPI_EXTERN napi_status napi_create_type_error(napi_env env, napi_value code, napi_value msg, napi_value* result); NAPI_EXTERN napi_status napi_create_range_error(napi_env env, napi_value code, napi_value msg, napi_value* result); // Methods to get the native napi_value from Primitive type NAPI_EXTERN napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result); NAPI_EXTERN napi_status napi_get_value_double(napi_env env, napi_value value, double* result); NAPI_EXTERN napi_status napi_get_value_int32(napi_env env, napi_value value, int32_t* result); NAPI_EXTERN napi_status napi_get_value_uint32(napi_env env, napi_value value, uint32_t* result); NAPI_EXTERN napi_status napi_get_value_int64(napi_env env, napi_value value, int64_t* result); NAPI_EXTERN napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result); // Copies LATIN-1 encoded bytes from a string into a buffer. NAPI_EXTERN napi_status napi_get_value_string_latin1(napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result); // Copies UTF-8 encoded bytes from a string into a buffer. NAPI_EXTERN napi_status napi_get_value_string_utf8(napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result); // Copies UTF-16 encoded bytes from a string into a buffer. NAPI_EXTERN napi_status napi_get_value_string_utf16(napi_env env, napi_value value, char16_t* buf, size_t bufsize, size_t* result); // Methods to coerce values // These APIs may execute user scripts NAPI_EXTERN napi_status napi_coerce_to_bool(napi_env env, napi_value value, napi_value* result); NAPI_EXTERN napi_status napi_coerce_to_number(napi_env env, napi_value value, napi_value* result); NAPI_EXTERN napi_status napi_coerce_to_object(napi_env env, napi_value value, napi_value* result); NAPI_EXTERN napi_status napi_coerce_to_string(napi_env env, napi_value value, napi_value* result); // Methods to work with Objects NAPI_EXTERN napi_status napi_get_prototype(napi_env env, napi_value object, napi_value* result); NAPI_EXTERN napi_status napi_get_property_names(napi_env env, napi_value object, napi_value* result); NAPI_EXTERN napi_status napi_set_property(napi_env env, napi_value object, napi_value key, napi_value value); NAPI_EXTERN napi_status napi_has_property(napi_env env, napi_value object, napi_value key, bool* result); NAPI_EXTERN napi_status napi_get_property(napi_env env, napi_value object, napi_value key, napi_value* result); NAPI_EXTERN napi_status napi_delete_property(napi_env env, napi_value object, napi_value key, bool* result); NAPI_EXTERN napi_status napi_has_own_property(napi_env env, napi_value object, napi_value key, bool* result); NAPI_EXTERN napi_status napi_set_named_property(napi_env env, napi_value object, const char* utf8name, napi_value value); NAPI_EXTERN napi_status napi_has_named_property(napi_env env, napi_value object, const char* utf8name, bool* result); NAPI_EXTERN napi_status napi_get_named_property(napi_env env, napi_value object, const char* utf8name, napi_value* result); NAPI_EXTERN napi_status napi_set_element(napi_env env, napi_value object, uint32_t index, napi_value value); NAPI_EXTERN napi_status napi_has_element(napi_env env, napi_value object, uint32_t index, bool* result); NAPI_EXTERN napi_status napi_get_element(napi_env env, napi_value object, uint32_t index, napi_value* result); NAPI_EXTERN napi_status napi_delete_element(napi_env env, napi_value object, uint32_t index, bool* result); NAPI_EXTERN napi_status napi_define_properties(napi_env env, napi_value object, size_t property_count, const napi_property_descriptor* properties); // Methods to work with Arrays NAPI_EXTERN napi_status napi_is_array(napi_env env, napi_value value, bool* result); NAPI_EXTERN napi_status napi_get_array_length(napi_env env, napi_value value, uint32_t* result); // Methods to compare values NAPI_EXTERN napi_status napi_strict_equals(napi_env env, napi_value lhs, napi_value rhs, bool* result); // Methods to work with Functions NAPI_EXTERN napi_status napi_call_function(napi_env env, napi_value recv, napi_value func, size_t argc, const napi_value* argv, napi_value* result); NAPI_EXTERN napi_status napi_new_instance(napi_env env, napi_value constructor, size_t argc, const napi_value* argv, napi_value* result); NAPI_EXTERN napi_status napi_instanceof(napi_env env, napi_value object, napi_value constructor, bool* result); // Methods to work with napi_callbacks // Gets all callback info in a single call. (Ugly, but faster.) NAPI_EXTERN napi_status napi_get_cb_info( napi_env env, // [in] NAPI environment handle napi_callback_info cbinfo, // [in] Opaque callback-info handle size_t* argc, // [in-out] Specifies the size of the provided argv array // and receives the actual count of args. napi_value* argv, // [out] Array of values napi_value* this_arg, // [out] Receives the JS 'this' arg for the call void** data); // [out] Receives the data pointer for the callback. NAPI_EXTERN napi_status napi_get_new_target(napi_env env, napi_callback_info cbinfo, napi_value* result); NAPI_EXTERN napi_status napi_define_class(napi_env env, const char* utf8name, size_t length, napi_callback constructor, void* data, size_t property_count, const napi_property_descriptor* properties, napi_value* result); // Methods to work with external data objects NAPI_EXTERN napi_status napi_wrap(napi_env env, napi_value js_object, void* native_object, napi_finalize finalize_cb, void* finalize_hint, napi_ref* result); NAPI_EXTERN napi_status napi_unwrap(napi_env env, napi_value js_object, void** result); NAPI_EXTERN napi_status napi_remove_wrap(napi_env env, napi_value js_object, void** result); NAPI_EXTERN napi_status napi_create_external(napi_env env, void* data, napi_finalize finalize_cb, void* finalize_hint, napi_value* result); NAPI_EXTERN napi_status napi_get_value_external(napi_env env, napi_value value, void** result); // Methods to control object lifespan // Set initial_refcount to 0 for a weak reference, >0 for a strong reference. NAPI_EXTERN napi_status napi_create_reference(napi_env env, napi_value value, uint32_t initial_refcount, napi_ref* result); // Deletes a reference. The referenced value is released, and may // be GC'd unless there are other references to it. NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref); // Increments the reference count, optionally returning the resulting count. // After this call the reference will be a strong reference because its // refcount is >0, and the referenced object is effectively "pinned". // Calling this when the refcount is 0 and the object is unavailable // results in an error. NAPI_EXTERN napi_status napi_reference_ref(napi_env env, napi_ref ref, uint32_t* result); // Decrements the reference count, optionally returning the resulting count. // If the result is 0 the reference is now weak and the object may be GC'd // at any time if there are no other references. Calling this when the // refcount is already 0 results in an error. NAPI_EXTERN napi_status napi_reference_unref(napi_env env, napi_ref ref, uint32_t* result); // Attempts to get a referenced value. If the reference is weak, // the value might no longer be available, in that case the call // is still successful but the result is NULL. NAPI_EXTERN napi_status napi_get_reference_value(napi_env env, napi_ref ref, napi_value* result); NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result); NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope); NAPI_EXTERN napi_status napi_open_escapable_handle_scope(napi_env env, napi_escapable_handle_scope* result); NAPI_EXTERN napi_status napi_close_escapable_handle_scope(napi_env env, napi_escapable_handle_scope scope); NAPI_EXTERN napi_status napi_escape_handle(napi_env env, napi_escapable_handle_scope scope, napi_value escapee, napi_value* result); // Methods to support error handling NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error); NAPI_EXTERN napi_status napi_throw_error(napi_env env, const char* code, const char* msg); NAPI_EXTERN napi_status napi_throw_type_error(napi_env env, const char* code, const char* msg); NAPI_EXTERN napi_status napi_throw_range_error(napi_env env, const char* code, const char* msg); NAPI_EXTERN napi_status napi_is_error(napi_env env, napi_value value, bool* result); // Methods to support catching exceptions NAPI_EXTERN napi_status napi_is_exception_pending(napi_env env, bool* result); NAPI_EXTERN napi_status napi_get_and_clear_last_exception(napi_env env, napi_value* result); // Methods to provide node::Buffer functionality with napi types NAPI_EXTERN napi_status napi_create_buffer(napi_env env, size_t length, void** data, napi_value* result); NAPI_EXTERN napi_status napi_create_external_buffer(napi_env env, size_t length, void* data, napi_finalize finalize_cb, void* finalize_hint, napi_value* result); NAPI_EXTERN napi_status napi_create_buffer_copy(napi_env env, size_t length, const void* data, void** result_data, napi_value* result); NAPI_EXTERN napi_status napi_is_buffer(napi_env env, napi_value value, bool* result); NAPI_EXTERN napi_status napi_get_buffer_info(napi_env env, napi_value value, void** data, size_t* length); // Methods to work with array buffers and typed arrays NAPI_EXTERN napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result); NAPI_EXTERN napi_status napi_create_arraybuffer(napi_env env, size_t byte_length, void** data, napi_value* result); NAPI_EXTERN napi_status napi_create_external_arraybuffer(napi_env env, void* external_data, size_t byte_length, napi_finalize finalize_cb, void* finalize_hint, napi_value* result); NAPI_EXTERN napi_status napi_get_arraybuffer_info(napi_env env, napi_value arraybuffer, void** data, size_t* byte_length); NAPI_EXTERN napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result); NAPI_EXTERN napi_status napi_create_typedarray(napi_env env, napi_typedarray_type type, size_t length, napi_value arraybuffer, size_t byte_offset, napi_value* result); NAPI_EXTERN napi_status napi_get_typedarray_info(napi_env env, napi_value typedarray, napi_typedarray_type* type, size_t* length, void** data, napi_value* arraybuffer, size_t* byte_offset); NAPI_EXTERN napi_status napi_create_dataview(napi_env env, size_t length, napi_value arraybuffer, size_t byte_offset, napi_value* result); NAPI_EXTERN napi_status napi_is_dataview(napi_env env, napi_value value, bool* result); NAPI_EXTERN napi_status napi_get_dataview_info(napi_env env, napi_value dataview, size_t* bytelength, void** data, napi_value* arraybuffer, size_t* byte_offset); // Methods to manage simple async operations NAPI_EXTERN napi_status napi_create_async_work(napi_env env, napi_value async_resource, napi_value async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete, void* data, napi_async_work* result); NAPI_EXTERN napi_status napi_delete_async_work(napi_env env, napi_async_work work); NAPI_EXTERN napi_status napi_queue_async_work(napi_env env, napi_async_work work); NAPI_EXTERN napi_status napi_cancel_async_work(napi_env env, napi_async_work work); // Methods for custom handling of async operations NAPI_EXTERN napi_status napi_async_init(napi_env env, napi_value async_resource, napi_value async_resource_name, napi_async_context* result); NAPI_EXTERN napi_status napi_async_destroy(napi_env env, napi_async_context async_context); NAPI_EXTERN napi_status napi_make_callback(napi_env env, napi_async_context async_context, napi_value recv, napi_value func, size_t argc, const napi_value* argv, napi_value* result); // version management NAPI_EXTERN napi_status napi_get_version(napi_env env, uint32_t* result); NAPI_EXTERN napi_status napi_get_node_version(napi_env env, const napi_node_version** version); // Promises NAPI_EXTERN napi_status napi_create_promise(napi_env env, napi_deferred* deferred, napi_value* promise); NAPI_EXTERN napi_status napi_resolve_deferred(napi_env env, napi_deferred deferred, napi_value resolution); NAPI_EXTERN napi_status napi_reject_deferred(napi_env env, napi_deferred deferred, napi_value rejection); NAPI_EXTERN napi_status napi_is_promise(napi_env env, napi_value promise, bool* is_promise); // Memory management NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env, int64_t change_in_bytes, int64_t* adjusted_value); // Runnig a script NAPI_EXTERN napi_status napi_run_script(napi_env env, napi_value script, napi_value* result); #if NAPI_VERSION >= 2 // Return the current libuv event loop for a given environment NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env, struct uv_loop_s** loop); #endif // NAPI_VERSION >= 2 #if NAPI_VERSION >= 3 NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env, napi_value resource_object, napi_async_context context, napi_callback_scope* result); NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env, napi_callback_scope scope); NAPI_EXTERN napi_status napi_fatal_exception(napi_env env, napi_value err); NAPI_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env, void (*fun)(void* arg), void* arg); NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env, void (*fun)(void* arg), void* arg); #endif // NAPI_VERSION >= 3 #ifdef NAPI_EXPERIMENTAL // Calling into JS from other threads NAPI_EXTERN napi_status napi_create_threadsafe_function(napi_env env, napi_value func, napi_value async_resource, napi_value async_resource_name, size_t max_queue_size, size_t initial_thread_count, void* thread_finalize_data, napi_finalize thread_finalize_cb, void* context, napi_threadsafe_function_call_js call_js_cb, napi_threadsafe_function* result); NAPI_EXTERN napi_status napi_get_threadsafe_function_context(napi_threadsafe_function func, void** result); NAPI_EXTERN napi_status napi_call_threadsafe_function(napi_threadsafe_function func, void* data, napi_threadsafe_function_call_mode is_blocking); NAPI_EXTERN napi_status napi_acquire_threadsafe_function(napi_threadsafe_function func); NAPI_EXTERN napi_status napi_release_threadsafe_function(napi_threadsafe_function func, napi_threadsafe_function_release_mode mode); NAPI_EXTERN napi_status napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func); NAPI_EXTERN napi_status napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func); NAPI_EXTERN napi_status napi_create_bigint_int64(napi_env env, int64_t value, napi_value* result); NAPI_EXTERN napi_status napi_create_bigint_uint64(napi_env env, uint64_t value, napi_value* result); NAPI_EXTERN napi_status napi_create_bigint_words(napi_env env, int sign_bit, size_t word_count, const uint64_t* words, napi_value* result); NAPI_EXTERN napi_status napi_get_value_bigint_int64(napi_env env, napi_value value, int64_t* result, bool* lossless); NAPI_EXTERN napi_status napi_get_value_bigint_uint64(napi_env env, napi_value value, uint64_t* result, bool* lossless); NAPI_EXTERN napi_status napi_get_value_bigint_words(napi_env env, napi_value value, int* sign_bit, size_t* word_count, uint64_t* words); #endif // NAPI_EXPERIMENTAL EXTERN_C_END #endif // SRC_NODE_API_H_ iotjs-1.0+715/include/node_api_types.h000066400000000000000000000077311371177304000176230ustar00rootroot00000000000000// Pulled from nodejs/node#8742cbfef0d31d7fad49ced7d11e6827b932b101 v10.8.0 using tools/pull-napi.sh #ifndef SRC_NODE_API_TYPES_H_ #define SRC_NODE_API_TYPES_H_ #include #include #if !defined __cplusplus || (defined(_MSC_VER) && _MSC_VER < 1900) typedef uint16_t char16_t; #endif // JSVM API types are all opaque pointers for ABI stability // typedef undefined structs instead of void* for compile time type safety typedef struct napi_env__* napi_env; typedef struct napi_value__* napi_value; typedef struct napi_ref__* napi_ref; typedef struct napi_handle_scope__* napi_handle_scope; typedef struct napi_escapable_handle_scope__* napi_escapable_handle_scope; typedef struct napi_callback_scope__* napi_callback_scope; typedef struct napi_callback_info__* napi_callback_info; typedef struct napi_async_context__* napi_async_context; typedef struct napi_async_work__* napi_async_work; typedef struct napi_deferred__* napi_deferred; #ifdef NAPI_EXPERIMENTAL typedef struct napi_threadsafe_function__* napi_threadsafe_function; #endif // NAPI_EXPERIMENTAL typedef enum { napi_default = 0, napi_writable = 1 << 0, napi_enumerable = 1 << 1, napi_configurable = 1 << 2, // Used with napi_define_class to distinguish static properties // from instance properties. Ignored by napi_define_properties. napi_static = 1 << 10, } napi_property_attributes; typedef enum { // ES6 types (corresponds to typeof) napi_undefined, napi_null, napi_boolean, napi_number, napi_string, napi_symbol, napi_object, napi_function, napi_external, napi_bigint, } napi_valuetype; typedef enum { napi_int8_array, napi_uint8_array, napi_uint8_clamped_array, napi_int16_array, napi_uint16_array, napi_int32_array, napi_uint32_array, napi_float32_array, napi_float64_array, napi_bigint64_array, napi_biguint64_array, } napi_typedarray_type; typedef enum { napi_ok, napi_invalid_arg, napi_object_expected, napi_string_expected, napi_name_expected, napi_function_expected, napi_number_expected, napi_boolean_expected, napi_array_expected, napi_generic_failure, napi_pending_exception, napi_cancelled, napi_escape_called_twice, napi_handle_scope_mismatch, napi_callback_scope_mismatch, napi_queue_full, napi_closing, napi_bigint_expected, } napi_status; #ifdef NAPI_EXPERIMENTAL typedef enum { napi_tsfn_release, napi_tsfn_abort } napi_threadsafe_function_release_mode; typedef enum { napi_tsfn_nonblocking, napi_tsfn_blocking } napi_threadsafe_function_call_mode; #endif // NAPI_EXPERIMENTAL typedef napi_value (*napi_callback)(napi_env env, napi_callback_info info); typedef void (*napi_finalize)(napi_env env, void* finalize_data, void* finalize_hint); typedef void (*napi_async_execute_callback)(napi_env env, void* data); typedef void (*napi_async_complete_callback)(napi_env env, napi_status status, void* data); #ifdef NAPI_EXPERIMENTAL typedef void (*napi_threadsafe_function_call_js)(napi_env env, napi_value js_callback, void* context, void* data); #endif // NAPI_EXPERIMENTAL typedef struct { // One of utf8name or name should be NULL. const char* utf8name; napi_value name; napi_callback method; napi_callback getter; napi_callback setter; napi_value value; napi_property_attributes attributes; void* data; } napi_property_descriptor; typedef struct { const char* error_message; void* engine_reserved; uint32_t engine_error_code; napi_status error_code; } napi_extended_error_info; typedef struct { uint32_t major; uint32_t minor; uint32_t patch; const char* release; } napi_node_version; #endif // SRC_NODE_API_TYPES_H_ iotjs-1.0+715/package.json000066400000000000000000000006071371177304000153060ustar00rootroot00000000000000{ "name": "IoT.js", "description": "Platform for Internet of Things with JavaScript", "scripts": { "lint": "eslint src -f codeframe || true", "lint-autofix": "eslint src -f codeframe --fix || true" }, "author": "Samsung Electronics Co., Ltd.", "license": "Apache-2.0", "devDependencies": { "eslint": "^4.7.2" }, "dependencies": { "node-gyp": "^3.8.0" } } iotjs-1.0+715/profiles/000077500000000000000000000000001371177304000146405ustar00rootroot00000000000000iotjs-1.0+715/profiles/default.profile000066400000000000000000000001031371177304000176400ustar00rootroot00000000000000ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_IOTJS_CORE_MODULES iotjs-1.0+715/profiles/minimal.profile000066400000000000000000000000411371177304000176430ustar00rootroot00000000000000ENABLE_MODULE_IOTJS_CORE_MODULES iotjs-1.0+715/sonar-project.properties000066400000000000000000000001751371177304000177240ustar00rootroot00000000000000sonar.projectKey=pando-project_iotjs sonar.projectName=IoT.js sonar.sources=src sonar.cfamily.build-wrapper-output=bw-output iotjs-1.0+715/src/000077500000000000000000000000001371177304000136045ustar00rootroot00000000000000iotjs-1.0+715/src/internal/000077500000000000000000000000001371177304000154205ustar00rootroot00000000000000iotjs-1.0+715/src/internal/node_api_internal.h000066400000000000000000000144771371177304000212600ustar00rootroot00000000000000/* Copyright 2019-present Samsung Electronics Co., Ltd. and other contributors * Copyright 2018-present Rokid 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_NODE_API_H #define IOTJS_NODE_API_H #include "iotjs_def.h" #include "jerryscript-ext/handle-scope.h" #include "jerryscript.h" #include "internal/node_api_internal_types.h" #include "node_api.h" #define GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4 #define AS_JERRY_VALUE(nvalue) (jerry_value_t)(uintptr_t) nvalue #define AS_NAPI_VALUE(jval) (napi_value)(uintptr_t) jval /** * MARK: - N-API Returns machenism: * If any non-napi-ok status code is returned in N-API functions, there * should be an error code and error message temporarily stored in napi-env * and can be fetched by `napi_get_last_error_info` until next napi function * called. */ #define NAPI_RETURN_WITH_MSG(status, message) \ do { \ iotjs_napi_set_error_info(iotjs_get_current_napi_env(), status, message, \ 0, NULL); \ return status; \ } while (0) #define NAPI_RETURN(status) \ do { \ iotjs_napi_set_error_info(iotjs_get_current_napi_env(), status, NULL, 0, \ NULL); \ return status; \ } while (0) /** MARK: - END N-API Returns */ /** MARK: - N-API Asserts */ /** * A weak assertion, which don't crash the program on failed assertion * rather returning a napi error code back to caller. */ #define NAPI_WEAK_ASSERT(error_t, assertion) \ do { \ if (!(assertion)) \ NAPI_RETURN_WITH_MSG(error_t, "Assertion (" #assertion ") failed"); \ } while (0) #define NAPI_WEAK_ASSERT_WITH_MSG(error_t, assertion, message) \ do { \ if (!(assertion)) \ NAPI_RETURN_WITH_MSG(error_t, message); \ } while (0) /** * A convenience weak assertion on jerry value type. */ #define NAPI_TRY_TYPE(type, jval) \ NAPI_WEAK_ASSERT_WITH_MSG(napi_##type##_expected, \ jerry_value_is_##type(jval), \ #type " was expected") /** * A convenience weak assertion on N-API Env matching. */ #define NAPI_TRY_ENV(env) \ do { \ if (napi_try_env_helper(env)) { \ NAPI_RETURN_WITH_MSG(napi_invalid_arg, "N-API env not match."); \ } \ } while (0) /** * A convenience weak assertion expecting there is no pending exception * unhandled. */ #define NAPI_TRY_NO_PENDING_EXCEPTION(env) \ NAPI_WEAK_ASSERT(napi_pending_exception, \ !iotjs_napi_is_exception_pending(env)) /** MARK: - N-API Asserts */ /** * In most N-API functions, there is an in-out pointer parameter to retrieve * return values, yet this pointer could be NULL anyway - it has to be ensured * no value were unexpectedly written to NULL pointer. */ #define NAPI_ASSIGN(result, value) \ if ((result) != NULL) \ *(result) = (value); /** * A convenience macro to call N-API functions internally and handle it's * non-napi-ok status code. */ #define NAPI_INTERNAL_CALL(call) \ do { \ napi_status status = (call); \ if (status != napi_ok) { \ NAPI_RETURN(status); \ } \ } while (0) /** * A convenience macro to create jerry-values and add it to current top * handle scope. */ #define JERRYX_CREATE(var, create) \ jerry_value_t var = (create); \ jerryx_create_handle(var); /** MARK: - node_api_module.c */ int napi_module_init_pending(jerry_value_t* exports); /** MARK: - END node_api_module.c */ /** MARK: - node_api_env.c */ napi_env iotjs_get_current_napi_env(void); bool napi_try_env_helper(napi_env env); void iotjs_napi_set_current_callback(napi_env env, iotjs_callback_info_t* callback_info); iotjs_callback_info_t* iotjs_napi_get_current_callback(napi_env env); void iotjs_napi_set_error_info(napi_env env, napi_status error_code, const char* error_message, uint32_t engine_error_code, void* engine_reserved); void iotjs_napi_clear_error_info(napi_env env); bool iotjs_napi_is_exception_pending(napi_env env); jerry_value_t iotjs_napi_env_get_and_clear_exception(napi_env env); jerry_value_t iotjs_napi_env_get_and_clear_fatal_exception(napi_env env); /** MARK: - END node_api_env.c */ /** MARK: - node_api_lifetime.c */ napi_status jerryx_status_to_napi_status(jerryx_handle_scope_status status); iotjs_object_info_t* iotjs_get_object_native_info(jerry_value_t jval, size_t native_info_size); iotjs_object_info_t* iotjs_try_get_object_native_info(jerry_value_t jval, size_t native_info_size); void iotjs_setup_napi(void); void iotjs_cleanup_napi(void); /** MARK: - END node_api_lifetime.c */ napi_status napi_assign_bool(bool value, bool* result); napi_status napi_assign_nvalue(jerry_value_t jvalue, napi_value* nvalue); #endif // IOTJS_NODE_API_H iotjs-1.0+715/src/internal/node_api_internal_types.h000066400000000000000000000060371371177304000224750ustar00rootroot00000000000000 /* Copyright 2018-present Rokid 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_NODE_API_TYPES_H #define IOTJS_NODE_API_TYPES_H #include "jerryscript.h" #include #include "node_api.h" typedef void (*iotjs_cleanup_hook_fn)(void* arg); typedef struct iotjs_async_context_s iotjs_async_context_t; typedef struct iotjs_async_work_s iotjs_async_work_t; typedef struct iotjs_buffer_external_info_s iotjs_buffer_external_info_t; typedef struct iotjs_callback_info_s iotjs_callback_info_t; typedef struct iotjs_cleanup_hook_s iotjs_cleanup_hook_t; typedef struct iotjs_function_info_s iotjs_function_info_t; typedef struct iotjs_napi_env_s iotjs_napi_env_t; typedef struct iotjs_object_info_s iotjs_object_info_t; typedef struct iotjs_reference_s iotjs_reference_t; typedef enum { napi_module_load_ok = 0, napi_module_no_pending, napi_module_no_nm_register_func, } napi_module_load_status; struct iotjs_cleanup_hook_s { iotjs_cleanup_hook_fn fn; void* arg; iotjs_cleanup_hook_t* next; }; struct iotjs_buffer_external_info_s { napi_env env; void* external_data; void* finalize_hint; napi_finalize finalize_cb; }; struct iotjs_reference_s { jerry_value_t jval; uint32_t refcount; iotjs_reference_t* prev; iotjs_reference_t* next; }; #define IOTJS_OBJECT_INFO_FIELDS \ napi_env env; \ void* native_object; \ napi_finalize finalize_cb; \ void* finalize_hint; \ iotjs_reference_t* ref_start; \ iotjs_reference_t* ref_end; struct iotjs_object_info_s { IOTJS_OBJECT_INFO_FIELDS }; struct iotjs_function_info_s { IOTJS_OBJECT_INFO_FIELDS napi_callback cb; void* data; }; struct iotjs_callback_info_s { size_t argc; jerry_value_t* argv; jerry_value_t jval_this; jerry_value_t jval_func; jerryx_handle_scope handle_scope; iotjs_function_info_t* function_info; }; struct iotjs_napi_env_s { napi_value pending_exception; napi_value pending_fatal_exception; napi_extended_error_info extended_error_info; /** Common function context */ iotjs_callback_info_t* current_callback_info; uv_thread_t main_thread; iotjs_cleanup_hook_t* cleanup_hook; }; struct iotjs_async_work_s { uv_work_t work_req; napi_env env; napi_value async_resource; napi_value async_resource_name; napi_async_execute_callback execute; napi_async_complete_callback complete; void* data; }; struct iotjs_async_context_s { napi_env env; napi_value async_resource; napi_value async_resource_name; }; #endif // IOTJS_NODE_API_TYPES_H iotjs-1.0+715/src/iotjs.c000066400000000000000000000223551371177304000151070ustar00rootroot00000000000000/* 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_js.h" #include "iotjs_string_ext.h" #include "jerryscript-ext/debugger.h" #if ENABLE_MODULE_NAPI #include "internal/node_api_internal.h" #endif #if !defined(__NUTTX__) && !defined(__TIZENRT__) #include "jerryscript-port-default.h" #endif #include "jerryscript-port.h" #include "jerryscript.h" #include "iotjs_uv_handle.h" #include #include #include static bool jerry_initialize(iotjs_environment_t* env) { // Set jerry run flags. jerry_init_flag_t jerry_flags = JERRY_INIT_EMPTY; if (iotjs_environment_config(env)->memstat) { jerry_flags |= JERRY_INIT_MEM_STATS; #if !defined(__NUTTX__) && !defined(__TIZENRT__) jerry_port_default_set_log_level(JERRY_LOG_LEVEL_DEBUG); #endif } if (iotjs_environment_config(env)->show_opcode) { jerry_flags |= JERRY_INIT_SHOW_OPCODES; #if !defined(__NUTTX__) && !defined(__TIZENRT__) jerry_port_default_set_log_level(JERRY_LOG_LEVEL_DEBUG); #endif } // Initialize jerry. jerry_init(jerry_flags); #ifdef JERRY_DEBUGGER if (iotjs_environment_config(env)->debugger != NULL) { bool protocol_created = false; char* debug_protocol = iotjs_environment_config(env)->debugger->protocol; char* debug_channel = iotjs_environment_config(env)->debugger->channel; if (!strcmp(debug_protocol, "tcp")) { uint16_t port = iotjs_environment_config(env)->debugger->port; protocol_created = jerryx_debugger_tcp_create(port); } else { IOTJS_ASSERT(!strcmp(debug_protocol, "serial")); char* config = iotjs_environment_config(env)->debugger->serial_config; protocol_created = jerryx_debugger_serial_create(config); } if (!strcmp(debug_channel, "rawpacket")) { jerryx_debugger_after_connect(protocol_created && jerryx_debugger_rp_create()); } else { IOTJS_ASSERT(!strcmp(debug_channel, "websocket")); jerryx_debugger_after_connect(protocol_created && jerryx_debugger_ws_create()); } if (!jerry_debugger_is_connected()) { DLOG("jerry debugger connection failed"); return false; } jerry_debugger_continue(); } #endif // Set magic strings. iotjs_register_jerry_magic_string(); // Register VM execution stop callback. jerry_set_vm_exec_stop_callback(vm_exec_stop_callback, &env->state, 2); // Do parse and run to generate initial javascript environment. jerry_value_t parsed_code = jerry_parse(NULL, 0, (jerry_char_t*)"", 0, JERRY_PARSE_NO_OPTS); if (jerry_value_is_error(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_is_error(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; } bool iotjs_initialize(iotjs_environment_t* env) { // Initialize JerryScript if (!jerry_initialize(env)) { DLOG("iotjs_jerry_init failed"); return false; } // Set event loop. if (!uv_default_loop()) { DLOG("iotjs uvloop init failed"); return false; } iotjs_environment_set_loop(env, uv_default_loop()); // Bind environment to global object. const jerry_value_t global = jerry_get_global_object(); jerry_set_object_native_pointer(global, env, NULL); // Initialize builtin process module. const jerry_value_t process = iotjs_module_get("process"); iotjs_jval_set_property_jval(global, "process", process); // Release the global object jerry_release_value(global); return true; } #ifdef JERRY_DEBUGGER void iotjs_restart(iotjs_environment_t* env, jerry_value_t jmain) { jerry_value_t abort_value = jerry_get_value_from_error(jmain, false); if (jerry_value_is_string(abort_value)) { /* TODO: When there is an api function to check for reset, this needs an update. */ static const char restart_str[] = "r353t"; jerry_size_t str_size = jerry_get_string_size(abort_value); if (str_size == sizeof(restart_str) - 1) { jerry_char_t str_buf[5]; jerry_string_to_char_buffer(abort_value, str_buf, str_size); if (memcmp(restart_str, (char*)(str_buf), str_size) == 0) { iotjs_environment_config(env)->debugger->context_reset = true; } } } jerry_release_value(abort_value); } #endif void iotjs_run(iotjs_environment_t* env) { // Evaluating 'iotjs.js' returns a function. #ifndef ENABLE_SNAPSHOT jerry_value_t jmain = iotjs_jhelper_eval("iotjs.js", strlen("iotjs.js"), iotjs_s, iotjs_l, false); #else jerry_value_t jmain = jerry_exec_snapshot((const uint32_t*)iotjs_js_modules_s, iotjs_js_modules_l, module_iotjs_idx, JERRY_SNAPSHOT_EXEC_ALLOW_STATIC); #endif if (jerry_value_is_error(jmain)) { jerry_value_t errval = jerry_get_value_from_error(jmain, false); #ifdef JERRY_DEBUGGER if (jerry_value_is_abort(jmain) && jerry_value_is_string(errval)) { static const char restart_str[] = "r353t"; jerry_size_t str_size = jerry_get_string_size(errval); if (str_size == sizeof(restart_str) - 1) { jerry_char_t str_buf[5]; jerry_string_to_char_buffer(errval, str_buf, str_size); if (memcmp(restart_str, (char*)(str_buf), str_size) == 0) { iotjs_environment_config(env)->debugger->context_reset = true; } } } #endif bool throw_exception = !iotjs_environment_is_exiting(env); #ifdef JERRY_DEBUGGER throw_exception = throw_exception && iotjs_environment_config(env)->debugger && !iotjs_environment_config(env)->debugger->context_reset; #endif if (throw_exception) { iotjs_uncaught_exception(errval); } jerry_release_value(errval); } jerry_release_value(jmain); } static int iotjs_start(iotjs_environment_t* env) { iotjs_environment_set_state(env, kRunningMain); #if ENABLE_MODULE_NAPI iotjs_setup_napi(); #endif // Load and call iotjs.js. iotjs_run(env); int exit_code = 0; if (!iotjs_environment_is_exiting(env)) { // Run event loop. iotjs_environment_set_state(env, kRunningLoop); bool more; do { more = uv_run(iotjs_environment_loop(env), UV_RUN_ONCE); more |= iotjs_process_next_tick(); jerry_value_t ret_val = jerry_run_all_enqueued_jobs(); if (jerry_value_is_error(ret_val)) { ret_val = jerry_get_value_from_error(ret_val, true); iotjs_uncaught_exception(ret_val); jerry_release_value(ret_val); } if (more == false) { more = uv_loop_alive(iotjs_environment_loop(env)); } } while (more && !iotjs_environment_is_exiting(env)); exit_code = iotjs_process_exitcode(); if (!iotjs_environment_is_exiting(env)) { // Emit 'exit' event. iotjs_process_emit_exit(exit_code); iotjs_environment_set_state(env, kExiting); } } exit_code = iotjs_process_exitcode(); return exit_code; } void iotjs_end(iotjs_environment_t* env) { uv_loop_t* loop = iotjs_environment_loop(env); // Close uv loop. uv_walk(loop, (uv_walk_cb)iotjs_uv_handle_close, NULL); uv_run(loop, UV_RUN_DEFAULT); int res = uv_loop_close(loop); IOTJS_ASSERT(res == 0); } void iotjs_terminate(iotjs_environment_t* env) { // Release builtin modules. iotjs_module_list_cleanup(); #if ENABLE_MODULE_NAPI iotjs_cleanup_napi(); #endif // Release JerryScript engine. jerry_cleanup(); } void iotjs_conf_console_out(int (*out)(int lv, const char* fmt, ...)) { iotjs_set_console_out(out); } int iotjs_entry(int argc, char** argv) { int ret_code = 0; // Initialize debug log and environments iotjs_debuglog_init(); srand((unsigned)jerry_port_get_current_time()); iotjs_environment_t* env = iotjs_environment_get(); if (!iotjs_environment_parse_command_line_arguments(env, (uint32_t)argc, argv)) { ret_code = 1; goto exit; } // Initialize IoT.js if (!iotjs_initialize(env)) { DLOG("iotjs_initialize failed"); ret_code = 1; goto terminate; } // Start IoT.js ret_code = iotjs_start(env); // Ends IoT.js iotjs_end(env); terminate: iotjs_terminate(env); exit: #ifdef JERRY_DEBUGGER if (iotjs_environment_config(env)->debugger && iotjs_environment_config(env)->debugger->context_reset) { iotjs_environment_release(); iotjs_debuglog_release(); return iotjs_entry(argc, argv); } #endif iotjs_environment_release(); iotjs_debuglog_release(); return ret_code; } iotjs-1.0+715/src/iotjs_binding.c000066400000000000000000000244001371177304000165720ustar00rootroot00000000000000/* 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 "iotjs_js.h" #include "modules/iotjs_module_buffer.h" #include jerry_value_t iotjs_jval_create_string(const iotjs_string_t* v) { jerry_value_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)) { jval = jerry_create_string_sz_from_utf8(data, size); } else { jval = JS_CREATE_ERROR(TYPE, "Invalid UTF-8 string"); } return jval; } jerry_value_t iotjs_jval_create_byte_array(uint32_t len, const char* data) { if (data == NULL) { len = 0; } jerry_value_t jval = 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(jval, i, val); jerry_release_value(val); } return jval; } jerry_value_t iotjs_jval_create_function(jerry_external_handler_t handler) { jerry_value_t jval = jerry_create_external_function(handler); IOTJS_ASSERT(jerry_value_is_constructor(jval)); return jval; } jerry_value_t iotjs_jval_create_error_without_error_flag(const char* msg) { jerry_value_t jval = jerry_create_error(JERRY_ERROR_COMMON, (const jerry_char_t*)(msg)); return jerry_get_value_from_error(jval, true); } bool iotjs_jval_as_boolean(jerry_value_t jval) { IOTJS_ASSERT(jerry_value_is_boolean(jval)); return jerry_get_boolean_value(jval); } double iotjs_jval_as_number(jerry_value_t jval) { IOTJS_ASSERT(jerry_value_is_number(jval)); return jerry_get_number_value(jval); } bool iotjs_jbuffer_as_string(jerry_value_t jval, iotjs_string_t* out_string) { if (out_string == NULL) { return false; } if (jerry_value_is_string(jval)) { jerry_size_t size = jerry_get_string_size(jval); if (size == 0) { return false; } char* buffer = iotjs_buffer_allocate(size + 1); size_t check = jerry_string_to_char_buffer(jval, (jerry_char_t*)buffer, size); IOTJS_ASSERT(check == size); buffer[size] = '\0'; *out_string = iotjs_string_create_with_buffer(buffer, size); return true; } iotjs_bufferwrap_t* buffer_wrap = iotjs_jbuffer_get_bufferwrap_ptr(jval); if (buffer_wrap == NULL || buffer_wrap->length == 0) { return false; } size_t size = buffer_wrap->length; char* buffer = iotjs_buffer_allocate(size + 1); memcpy(buffer, buffer_wrap->buffer, size); buffer[size] = '\0'; *out_string = iotjs_string_create_with_buffer(buffer, size); return true; } void iotjs_jval_as_tmp_buffer(jerry_value_t jval, iotjs_tmp_buffer_t* out_buffer) { out_buffer->jval = jerry_create_undefined(); out_buffer->buffer = NULL; out_buffer->length = 0; if (jerry_value_is_undefined(jval)) { return; } iotjs_bufferwrap_t* buffer_wrap = iotjs_jbuffer_get_bufferwrap_ptr(jval); if (buffer_wrap != NULL) { IOTJS_ASSERT(buffer_wrap->jobject == jval); jerry_acquire_value(jval); out_buffer->jval = buffer_wrap->jobject; out_buffer->buffer = buffer_wrap->buffer; out_buffer->length = buffer_wrap->length; return; } bool was_string = true; if (!jerry_value_is_string(jval)) { jval = jerry_value_to_string(jval); if (jerry_value_is_error(jval)) { out_buffer->jval = jval; return; } was_string = false; } jerry_size_t size = jerry_get_string_size(jval); if (size == 0) { if (!was_string) { jerry_release_value(jval); } return; } char* buffer = iotjs_buffer_allocate(size); size_t check = jerry_string_to_char_buffer(jval, (jerry_char_t*)buffer, size); IOTJS_ASSERT(check == size); out_buffer->buffer = buffer; out_buffer->length = size; if (!was_string) { jerry_release_value(jval); } } void iotjs_jval_get_jproperty_as_tmp_buffer(jerry_value_t jobj, const char* name, iotjs_tmp_buffer_t* out_buffer) { jerry_value_t jproperty = iotjs_jval_get_property(jobj, name); if (jerry_value_is_error(jproperty)) { out_buffer->jval = jproperty; out_buffer->buffer = NULL; out_buffer->length = 0; return; } iotjs_jval_as_tmp_buffer(jproperty, out_buffer); jerry_release_value(jproperty); } void iotjs_free_tmp_buffer(iotjs_tmp_buffer_t* tmp_buffer) { if (jerry_value_is_undefined(tmp_buffer->jval)) { if (tmp_buffer->buffer != NULL) { iotjs_buffer_release(tmp_buffer->buffer); } return; } IOTJS_ASSERT(!jerry_value_is_error(tmp_buffer->jval) || tmp_buffer->buffer == NULL); jerry_release_value(tmp_buffer->jval); } iotjs_string_t iotjs_jval_as_string(jerry_value_t jval) { IOTJS_ASSERT(jerry_value_is_string(jval)); jerry_size_t size = jerry_get_utf8_string_size(jval); 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_utf8_char_buffer(jval, jerry_buffer, size); IOTJS_ASSERT(check == size); buffer[size] = '\0'; iotjs_string_t res = iotjs_string_create_with_buffer(buffer, size); return res; } jerry_value_t iotjs_jval_as_object(jerry_value_t jval) { IOTJS_ASSERT(jerry_value_is_object(jval)); return jval; } jerry_value_t iotjs_jval_as_array(jerry_value_t jval) { IOTJS_ASSERT(jerry_value_is_array(jval)); return jval; } jerry_value_t iotjs_jval_as_function(jerry_value_t jval) { IOTJS_ASSERT(jerry_value_is_function(jval)); return jval; } bool iotjs_jval_set_prototype(jerry_value_t jobj, jerry_value_t jproto) { jerry_value_t ret = jerry_set_prototype(jobj, jproto); bool error_found = jerry_value_is_error(ret); jerry_release_value(ret); return !error_found; } void iotjs_jval_set_method(jerry_value_t jobj, const char* name, jerry_external_handler_t handler) { IOTJS_ASSERT(jerry_value_is_object(jobj)); jerry_value_t jfunc = jerry_create_external_function(handler); iotjs_jval_set_property_jval(jobj, name, jfunc); jerry_release_value(jfunc); } void iotjs_jval_set_property_jval(jerry_value_t jobj, const char* name, jerry_value_t value) { IOTJS_ASSERT(jerry_value_is_object(jobj)); jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)(name)); jerry_value_t ret_val = jerry_set_property(jobj, prop_name, value); jerry_release_value(prop_name); IOTJS_ASSERT(!jerry_value_is_error(ret_val)); jerry_release_value(ret_val); } void iotjs_jval_set_property_null(jerry_value_t jobj, const char* name) { iotjs_jval_set_property_jval(jobj, name, jerry_create_null()); } void iotjs_jval_set_property_undefined(jerry_value_t jobj, const char* name) { iotjs_jval_set_property_jval(jobj, name, jerry_create_undefined()); } void iotjs_jval_set_property_boolean(jerry_value_t jobj, const char* name, bool v) { iotjs_jval_set_property_jval(jobj, name, jerry_create_boolean(v)); } void iotjs_jval_set_property_number(jerry_value_t jobj, const char* name, double v) { jerry_value_t jval = jerry_create_number(v); iotjs_jval_set_property_jval(jobj, name, jval); jerry_release_value(jval); } void iotjs_jval_set_property_string(jerry_value_t jobj, const char* name, const iotjs_string_t* v) { jerry_value_t jval = iotjs_jval_create_string(v); iotjs_jval_set_property_jval(jobj, name, jval); jerry_release_value(jval); } void iotjs_jval_set_property_string_raw(jerry_value_t jobj, const char* name, const char* v) { jerry_value_t jval = jerry_create_string((const jerry_char_t*)v); iotjs_jval_set_property_jval(jobj, name, jval); jerry_release_value(jval); } jerry_value_t iotjs_jval_get_property(jerry_value_t jobj, const char* name) { IOTJS_ASSERT(jerry_value_is_object(jobj)); jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)(name)); jerry_value_t res = jerry_get_property(jobj, prop_name); jerry_release_value(prop_name); if (jerry_value_is_error(res)) { jerry_release_value(res); return jerry_create_undefined(); } return res; } void iotjs_jval_set_property_by_index(jerry_value_t jarr, uint32_t idx, jerry_value_t jval) { IOTJS_ASSERT(jerry_value_is_object(jarr)); jerry_value_t ret_val = jerry_set_property_by_index(jarr, idx, jval); IOTJS_ASSERT(!jerry_value_is_error(ret_val)); jerry_release_value(ret_val); } jerry_value_t iotjs_jval_get_property_by_index(jerry_value_t jarr, uint32_t idx) { IOTJS_ASSERT(jerry_value_is_object(jarr)); jerry_value_t res = jerry_get_property_by_index(jarr, idx); if (jerry_value_is_error(res)) { jerry_release_value(res); return jerry_create_undefined(); } return res; } jerry_value_t iotjs_jhelper_eval(const char* name, size_t name_len, const uint8_t* data, size_t size, bool strict_mode) { uint32_t opts = strict_mode ? JERRY_PARSE_STRICT_MODE : JERRY_PARSE_NO_OPTS; jerry_value_t jres = jerry_parse((const jerry_char_t*)name, name_len, (const jerry_char_t*)data, size, opts); if (!jerry_value_is_error(jres)) { jerry_value_t func = jres; jres = jerry_run(func); jerry_release_value(func); } return jres; } jerry_value_t vm_exec_stop_callback(void* user_p) { State* state_p = (State*)user_p; if (*state_p != kExiting) { return jerry_create_undefined(); } return jerry_create_string((const jerry_char_t*)"Abort script"); } iotjs-1.0+715/src/iotjs_binding.h000066400000000000000000000217101371177304000166000ustar00rootroot00000000000000/* 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 typedef const jerry_object_native_info_t JNativeInfoType; /* Constructors */ jerry_value_t iotjs_jval_create_string(const iotjs_string_t* v); jerry_value_t iotjs_jval_create_byte_array(uint32_t len, const char* data); jerry_value_t iotjs_jval_create_function(jerry_external_handler_t handler); jerry_value_t iotjs_jval_create_error_without_error_flag(const char* msg); /* Type Converters */ bool iotjs_jval_as_boolean(jerry_value_t); double iotjs_jval_as_number(jerry_value_t); iotjs_string_t iotjs_jval_as_string(jerry_value_t); jerry_value_t iotjs_jval_as_object(jerry_value_t); jerry_value_t iotjs_jval_as_array(jerry_value_t); jerry_value_t iotjs_jval_as_function(jerry_value_t); bool iotjs_jbuffer_as_string(jerry_value_t jval, iotjs_string_t* out_string); /* Temporary Buffers for JavaScript Values */ typedef struct { jerry_value_t jval; char* buffer; size_t length; } iotjs_tmp_buffer_t; void iotjs_jval_as_tmp_buffer(jerry_value_t jval, iotjs_tmp_buffer_t* out_buffer); void iotjs_jval_get_jproperty_as_tmp_buffer(jerry_value_t jobj, const char* name, iotjs_tmp_buffer_t* out_buffer); void iotjs_free_tmp_buffer(iotjs_tmp_buffer_t* tmp_buffer); /* Methods for General JavaScript Object */ void iotjs_jval_set_method(jerry_value_t jobj, const char* name, jerry_external_handler_t handler); bool iotjs_jval_set_prototype(jerry_value_t jobj, jerry_value_t jproto); void iotjs_jval_set_property_jval(jerry_value_t jobj, const char* name, jerry_value_t value); void iotjs_jval_set_property_null(jerry_value_t jobj, const char* name); void iotjs_jval_set_property_undefined(jerry_value_t jobj, const char* name); void iotjs_jval_set_property_boolean(jerry_value_t jobj, const char* name, bool v); void iotjs_jval_set_property_number(jerry_value_t jobj, const char* name, double v); void iotjs_jval_set_property_string(jerry_value_t jobj, const char* name, const iotjs_string_t* v); void iotjs_jval_set_property_string_raw(jerry_value_t jobj, const char* name, const char* v); jerry_value_t iotjs_jval_get_property(jerry_value_t jobj, const char* name); void iotjs_jval_set_property_by_index(jerry_value_t jarr, uint32_t idx, jerry_value_t jval); jerry_value_t iotjs_jval_get_property_by_index(jerry_value_t jarr, uint32_t idx); // Evaluates javascript source file. jerry_value_t iotjs_jhelper_eval(const char* name, size_t name_len, const uint8_t* data, size_t size, bool strict_mode); /* Note: * Defines started with underscores should not be used * outside of this header. */ #define JS_CREATE_ERROR(TYPE, message) \ jerry_create_error(JERRY_ERROR_##TYPE, (const jerry_char_t*)message) #define jerry_value_is_any(value) true #define iotjs_jval_as_any(value) (value) #define JS_CHECK(predicate) \ if (!(predicate)) { \ return JS_CREATE_ERROR(COMMON, "Internal error"); \ } #define __JS_CHECK_TYPE(index, type) jerry_value_is_##type(jargv[index]) #define JS_CHECK_ARG(index, type) JS_CHECK(__JS_CHECK_TYPE(index, type)) #define JS_CHECK_ARG_IF_EXIST(index, type) \ if (jargc > index) { \ JS_CHECK(__JS_CHECK_TYPE(index, type)) \ } #define JS_CHECK_ARGS_0() #define JS_CHECK_ARGS_1(type0) \ JS_CHECK_ARGS_0() \ __JS_CHECK_TYPE(0, type0) #define JS_CHECK_ARGS_2(type0, type1) \ JS_CHECK_ARGS_1(type0) \ &&__JS_CHECK_TYPE(1, type1) #define JS_CHECK_ARGS_3(type0, type1, type2) \ JS_CHECK_ARGS_2(type0, type1) \ &&__JS_CHECK_TYPE(2, type2) #define JS_CHECK_ARGS_4(type0, type1, type2, type3) \ JS_CHECK_ARGS_3(type0, type1, type2) \ &&__JS_CHECK_TYPE(3, type3) #define JS_CHECK_ARGS_5(type0, type1, type2, type3, type4) \ JS_CHECK_ARGS_4(type0, type1, type2, type3) \ &&__JS_CHECK_TYPE(4, type4) #define JS_CHECK_ARGS(argc, ...) \ JS_CHECK(jargc >= argc && JS_CHECK_ARGS_##argc(__VA_ARGS__)) #define JS_CHECK_THIS() JS_CHECK(jerry_value_is_object(jthis)) #define JS_GET_ARG(index, type) iotjs_jval_as_##type(jargv[index]) #define JS_GET_ARG_IF_EXIST(index, type) \ ((jargc > index) && jerry_value_is_##type(jargv[index]) \ ? jargv[index] \ : jerry_create_null()) #define JS_GET_THIS() iotjs_jval_as_object(jthis) #define JS_FUNCTION(name) \ static jerry_value_t name(const jerry_value_t jfunc, \ const jerry_value_t jthis, \ const jerry_value_t jargv[], \ const jerry_length_t jargc) #if defined(EXPERIMENTAL) && !defined(DEBUG) // This code branch is to be in #ifdef NDEBUG #define DJS_CHECK(predicate) ((void)0) #define DJS_CHECK_ARG(index, type) ((void)0) #define DJS_CHECK_ARGS(argc, ...) ((void)0) #define DJS_CHECK_THIS() ((void)0) #define DJS_CHECK_ARG_IF_EXIST(index, type) ((void)0) #else #define DJS_CHECK(predicate) JS_CHECK(predicate) #define DJS_CHECK_ARG(index, type) JS_CHECK_ARG(index, type) #define DJS_CHECK_ARGS(argc, ...) JS_CHECK_ARGS(argc, __VA_ARGS__) #define DJS_CHECK_THIS() JS_CHECK_THIS() #define DJS_CHECK_ARG_IF_EXIST(index, type) JS_CHECK_ARG_IF_EXIST(index, type) #endif #define JS_DECLARE_PTR(JOBJ, TYPE, NAME) \ TYPE* NAME = NULL; \ do { \ if (!jerry_get_object_native_pointer(JOBJ, (void**)&NAME, \ &this_module_native_info)) { \ return JS_CREATE_ERROR(COMMON, "Internal"); \ } \ } while (0) #define JS_DECLARE_THIS_PTR(type, name) \ JS_DECLARE_PTR(jthis, iotjs_##type##_t, name) #define JS_DECLARE_OBJECT_PTR(index, type, name) \ JS_DECLARE_PTR(jargv[index], iotjs_##type##_t, name) #define JS_GET_REQUIRED_ARG_VALUE(index, target, property, type) \ do { \ if (jerry_value_is_undefined(jargv[index])) { \ return JS_CREATE_ERROR(TYPE, "Missing argument, required " property); \ } else if (jerry_value_is_##type(jargv[index])) { \ target = iotjs_jval_as_##type(jargv[index]); \ } else { \ return JS_CREATE_ERROR(TYPE, "Bad arguments, required " property \ " is not a " #type); \ } \ } while (0) #define JS_GET_REQUIRED_CONF_VALUE(src, target, property, type) \ do { \ jerry_value_t value = iotjs_jval_get_property(src, property); \ if (jerry_value_is_undefined(value)) { \ jerry_release_value(value); \ return JS_CREATE_ERROR(TYPE, "Missing argument, required " property); \ } else if (jerry_value_is_##type(value)) { \ target = iotjs_jval_as_##type(value); \ jerry_release_value(value); \ } else { \ jerry_release_value(value); \ return JS_CREATE_ERROR(TYPE, "Bad arguments, required " property \ " is not a " #type); \ } \ } while (0) jerry_value_t vm_exec_stop_callback(void* user_p); #endif /* IOTJS_BINDING_H */ iotjs-1.0+715/src/iotjs_binding_helper.c000066400000000000000000000122221371177304000201300ustar00rootroot00000000000000/* 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 #include #include void iotjs_uncaught_exception(jerry_value_t jexception) { const jerry_value_t process = iotjs_module_get("process"); jerry_value_t jonuncaughtexception = iotjs_jval_get_property(process, IOTJS_MAGIC_STRING__ONUNCAUGHTEXCEPTION); IOTJS_ASSERT(jerry_value_is_function(jonuncaughtexception)); jerry_value_t jres = jerry_call_function(jonuncaughtexception, process, &jexception, 1); jerry_release_value(jonuncaughtexception); if (jerry_value_is_error(jres)) { iotjs_environment_t* env = iotjs_environment_get(); if (!iotjs_environment_is_exiting(env)) { iotjs_set_process_exitcode(2); iotjs_environment_set_state(env, kExiting); } } jerry_release_value(jres); } void iotjs_process_emit_exit(int code) { const jerry_value_t process = iotjs_module_get("process"); jerry_value_t jexit = iotjs_jval_get_property(process, IOTJS_MAGIC_STRING_EMITEXIT); if (jerry_value_is_function(jexit)) { jerry_value_t jcode = jerry_create_number(code); jerry_value_t jres = jerry_call_function(jexit, process, &jcode, 1); if (jerry_value_is_error(jres)) { iotjs_set_process_exitcode(2); } jerry_release_value(jcode); jerry_release_value(jres); } jerry_release_value(jexit); } // Calls next tick callbacks registered via `process.nextTick()`. bool iotjs_process_next_tick(void) { iotjs_environment_t* env = iotjs_environment_get(); if (iotjs_environment_is_exiting(env)) { return false; } const jerry_value_t process = iotjs_module_get("process"); jerry_value_t jon_next_tick = iotjs_jval_get_property(process, IOTJS_MAGIC_STRING__ONNEXTTICK); IOTJS_ASSERT(jerry_value_is_function(jon_next_tick)); jerry_value_t jres = jerry_call_function(jon_next_tick, jerry_create_undefined(), NULL, 0); bool ret = false; if (!jerry_value_is_error(jres)) { ret = iotjs_jval_as_boolean(jres); } jerry_release_value(jres); jerry_release_value(jon_next_tick); return ret; } // Make a callback for the given `function` with `this_` binding and `args` // arguments. The next tick callbacks registered via `process.nextTick()` // will be called after the callback function `function` returns. void iotjs_invoke_callback(jerry_value_t jfunc, jerry_value_t jthis, const jerry_value_t* jargv, size_t jargc) { jerry_value_t result = iotjs_invoke_callback_with_result(jfunc, jthis, jargv, jargc); jerry_release_value(result); } jerry_value_t iotjs_invoke_callback_with_result(jerry_value_t jfunc, jerry_value_t jthis, const jerry_value_t* jargv, size_t jargc) { IOTJS_ASSERT(jerry_value_is_function(jfunc)); // If the environment is already exiting just return an undefined value. if (iotjs_environment_is_exiting(iotjs_environment_get())) { return jerry_create_undefined(); } // Calls back the function. jerry_value_t jres = jerry_call_function(jfunc, jthis, jargv, jargc); if (jerry_value_is_error(jres)) { jerry_value_t errval = jerry_get_value_from_error(jres, false); iotjs_uncaught_exception(errval); jerry_release_value(errval); } // Calls the next tick callbacks. iotjs_process_next_tick(); // Return value. return jres; } int iotjs_process_exitcode(void) { const jerry_value_t process = iotjs_module_get("process"); jerry_value_t jexitcode = iotjs_jval_get_property(process, IOTJS_MAGIC_STRING_EXITCODE); uint8_t exitcode = 0; jerry_value_t num_val = jerry_value_to_number(jexitcode); if (jerry_value_is_error(num_val)) { exitcode = 1; } else { exitcode = (uint8_t)iotjs_jval_as_number(num_val); } uint8_t native_exitcode = iotjs_environment_get()->exitcode; if (native_exitcode != exitcode && native_exitcode) { exitcode = native_exitcode; } jerry_release_value(num_val); jerry_release_value(jexitcode); return (int)exitcode; } void iotjs_set_process_exitcode(int code) { const jerry_value_t process = iotjs_module_get("process"); jerry_value_t jstring = jerry_create_string((jerry_char_t*)IOTJS_MAGIC_STRING_EXITCODE); jerry_value_t jcode = jerry_create_number(code); jerry_value_t ret_val = jerry_set_property(process, jstring, jcode); if (jerry_value_is_error(ret_val)) { iotjs_environment_get()->exitcode = 1; } jerry_release_value(ret_val); jerry_release_value(jstring); jerry_release_value(jcode); } iotjs-1.0+715/src/iotjs_binding_helper.h000066400000000000000000000025711371177304000201430ustar00rootroot00000000000000/* 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_HELPER_H #define IOTJS_BINDING_HELPER_H #include "iotjs_binding.h" void iotjs_uncaught_exception(jerry_value_t jexception); void iotjs_process_emit_exit(int code); bool iotjs_process_next_tick(void); void iotjs_invoke_callback(jerry_value_t jfunc, jerry_value_t jthis, const jerry_value_t* jargv, size_t jargc); jerry_value_t iotjs_invoke_callback_with_result(jerry_value_t jfunc, jerry_value_t jthis, const jerry_value_t* jargv, size_t jargc); int iotjs_process_exitcode(void); void iotjs_set_process_exitcode(int code); #endif /* IOTJS_BINDING_HELPER_H */ iotjs-1.0+715/src/iotjs_compatibility.h000066400000000000000000000024041371177304000200360ustar00rootroot00000000000000/* Copyright 2018-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_COMPATIBILITY_H #define IOTJS_COMPATIBILITY_H /* Windows compatiblity defines */ #ifdef WIN32 #include #include /* Map windows _O_* to O_* defines as on Linux systems. */ #define O_APPEND _O_APPEND #define O_CREAT _O_CREAT #define O_EXCL _O_EXCL #define O_RDONLY _O_RDONLY #define O_RDWR _O_RDWR #define O_TRUNC _O_TRUNC #define O_WRONLY _O_WRONLY /* On windows there is no O_SYNC directly, disable it for now. */ #define O_SYNC 0x0 #ifndef PATH_MAX #define PATH_MAX MAX_PATH #endif #endif #ifndef S_ISREG #define S_ISREG(mode) (((mode) & (S_IFMT)) == S_IFREG) #endif #endif /* IOTJS_COMPATIBILITY_H */ iotjs-1.0+715/src/iotjs_debuglog.c000066400000000000000000000042401371177304000167500ustar00rootroot00000000000000/* 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 #include #include "iotjs_debuglog.h" iotjs_console_out_t iotjs_console_out = NULL; void iotjs_set_console_out(iotjs_console_out_t output) { iotjs_console_out = output; } #ifdef ENABLE_DEBUG_LOG int iotjs_debug_level = DBGLEV_ERR; FILE* iotjs_log_stream = NULL; const char* iotjs_debug_prefix[4] = { "", "ERR", "WRN", "INF" }; #endif // ENABLE_DEBUG_LOG void iotjs_debuglog_init(void) { #ifdef ENABLE_DEBUG_LOG const char* dbglevel = NULL; const char* dbglogfile = NULL; #if defined(__linux__) || defined(__APPLE__) dbglevel = getenv("IOTJS_DEBUG_LEVEL"); dbglogfile = getenv("IOTJS_DEBUG_LOGFILE"); #endif // defined(__linux__) || defined(__APPLE__) if (dbglevel) { iotjs_debug_level = atoi(dbglevel); if (iotjs_debug_level < 0) iotjs_debug_level = 0; if (iotjs_debug_level > DBGLEV_INFO) iotjs_debug_level = DBGLEV_INFO; } iotjs_log_stream = stderr; if (dbglogfile) { FILE* logstream; logstream = fopen(dbglogfile, "w+"); if (logstream != NULL) iotjs_log_stream = logstream; } // fprintf(stderr, "DBG LEV = %d", iotjs_debug_level); // fprintf(stderr, "DBG OUT = %s", (dbglogfile==NULL?"(stderr)":dbglogfile)); #endif // ENABLE_DEBUG_LOG } void iotjs_debuglog_release(void) { #ifdef ENABLE_DEBUG_LOG if (iotjs_log_stream && iotjs_log_stream != stderr && iotjs_log_stream != stdout) { fclose(iotjs_log_stream); } // some embed systems(ex, nuttx) may need this iotjs_log_stream = stderr; iotjs_debug_level = DBGLEV_ERR; #endif // ENABLE_DEBUG_LOG } iotjs-1.0+715/src/iotjs_debuglog.h000066400000000000000000000057331371177304000167650ustar00rootroot00000000000000/* 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_DEBUGLOG_H #define IOTJS_DEBUGLOG_H #define DBGLEV_ERR 1 #define DBGLEV_WARN 2 #define DBGLEV_INFO 3 typedef int (*iotjs_console_out_t)(int level, const char* format, ...); extern iotjs_console_out_t iotjs_console_out; extern void iotjs_set_console_out(iotjs_console_out_t output); #ifdef ENABLE_DEBUG_LOG extern int iotjs_debug_level; extern FILE* iotjs_log_stream; extern const char* iotjs_debug_prefix[4]; #if defined(__TIZEN__) #include #define DLOG_TAG "IOTJS" #define DLOG_PRINT(lvl, ...) \ dlog_print((lvl == DBGLEV_ERR \ ? DLOG_ERROR \ : (lvl == DBGLEV_WARN ? DLOG_WARN : DLOG_INFO)), \ DLOG_TAG, __VA_ARGS__); #else #include #define DLOG_PRINT(lvl, ...) \ fprintf(iotjs_log_stream, "[%s] ", iotjs_debug_prefix[lvl]); \ fprintf(iotjs_log_stream, __VA_ARGS__); \ fprintf(iotjs_log_stream, "\n"); \ fflush(iotjs_log_stream); #endif /* defined(__TIZEN__) */ #define IOTJS_DLOG(lvl, ...) \ do { \ if (0 <= lvl && lvl <= iotjs_debug_level && iotjs_log_stream) { \ if (iotjs_console_out) { \ iotjs_console_out(lvl, __VA_ARGS__); \ } else { \ DLOG_PRINT(lvl, __VA_ARGS__) \ } \ } \ } while (0) #define DLOG(...) IOTJS_DLOG(DBGLEV_ERR, __VA_ARGS__) #define DDLOG(...) IOTJS_DLOG(DBGLEV_WARN, __VA_ARGS__) #define DDDLOG(...) IOTJS_DLOG(DBGLEV_INFO, __VA_ARGS__) /* Use DLOG for errors, default you will see them Use DDLOG for warnings, set iotjs_debug_level=2 to see them USE DDDLOG for information, set iotjs_debug_level=3 to see them */ #else /* !ENABLE_DEBUG_LOG */ #define IOTJS_DLOG(...) #define DLOG(...) #define DDLOG(...) #define DDDLOG(...) #endif /* ENABLE_DEBUG_LOG */ void iotjs_debuglog_init(void); void iotjs_debuglog_release(void); #endif /* IOTJS_DEBUGLOG_H */ iotjs-1.0+715/src/iotjs_def.h000066400000000000000000000072271371177304000157330ustar00rootroot00000000000000/* 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 /* !__NUTTX__ && !__TIZENRT__ */ #define IOTJS_MAX_READ_BUFFER_SIZE 65535 #define IOTJS_MAX_PATH_SIZE PATH_MAX #endif /* __NUTTX__ || TIZENRT */ #endif /* IOTJS_MAX_READ_BUFFER_SIZE */ #ifndef IOTJS_ASSERT #ifdef NDEBUG #define IOTJS_ASSERT(x) ((void)(x)) #else /* !NDEBUG */ extern void print_stacktrace(void); extern void force_terminate(void); #define IOTJS_ASSERT(x) \ do { \ if (!(x)) { \ fprintf(stderr, "%s:%d: Assertion '%s' failed.\n", __FILE__, __LINE__, \ #x); \ print_stacktrace(); \ force_terminate(); \ } \ } while (0) #endif /* NDEBUG */ #endif /* IOTJS_ASSERT */ #if defined(__arm__) #define TARGET_ARCH "arm" #elif defined(__i686__) #define TARGET_ARCH "ia32" #elif defined(__x86_64__) #define TARGET_ARCH "x64" #else /* !__arm__ && !__i686__ && !__x86_64__ */ #define TARGET_ARCH "unknown" #endif /* __arm__ */ #if defined(__linux__) #if defined(__TIZEN__) #define TARGET_OS "tizen" #else #define TARGET_OS "linux" #endif /* __TIZEN__ */ #elif defined(__NUTTX__) #define TARGET_OS "nuttx" #elif defined(__APPLE__) #define TARGET_OS "darwin" #elif defined(__TIZENRT__) #define TARGET_OS "tizenrt" #elif defined(WIN32) #define TARGET_OS "windows" #else /* !__linux__ && !__NUTTX__ !__APPLE__ && !__TIZENRT__ && !WIN32 */ #define TARGET_OS "unknown" #endif /* __linux__ */ #define IOTJS_VERSION "1.0.0" #if !defined(STRINGIFY) #define STRINGIFY(x) #x #endif /* STRINGIFY */ #if !defined(TOSTRING) #define TOSTRING(x) STRINGIFY(x) #endif /* TOSTRING */ #if !defined(TARGET_BOARD) #define TARGET_BOARD "unknown" #endif /* TARGET_BOARD */ #define NODE_MAJOR_VERSION 1 #define NODE_MINOR_VERSION 0 #define NODE_PATCH_VERSION 0 /* Avoid compiler warnings if needed. */ #define IOTJS_UNUSED(x) ((void)(x)) #define IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(name) \ static void iotjs_##name##_destroy(iotjs_##name##_t* wrap); \ static const jerry_object_native_info_t this_module_native_info = { \ .free_cb = (jerry_object_native_free_callback_t)iotjs_##name##_destroy \ } #include #include #include /* PATH_MAX */ #include #include // 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 */ iotjs-1.0+715/src/iotjs_env.c000066400000000000000000000240331371177304000157520ustar00rootroot00000000000000/* 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_env.h" #include #include typedef enum { OPT_HELP, OPT_MEM_STATS, OPT_SHOW_OP, #ifdef JERRY_DEBUGGER OPT_DEBUG_SERVER, OPT_DEBUGGER_WAIT_SOURCE, OPT_DEBUG_PORT, OPT_DEBUG_CHANNEL, OPT_DEBUG_PROTOCOL, OPT_DEBUG_SERIAL_CONFIG, #endif NUM_OF_OPTIONS } cli_option_id_t; typedef struct { const cli_option_id_t id; const char* opt; const char* longopt; const char* help; const uint32_t more; // The number of options coming with the given option } cli_option_t; #define CLI_DEFAULT_HELP_STRING \ "Usage: iotjs [options] {FILE | FILE.js} [arguments]\n" static iotjs_environment_t current_env; static bool initialized = false; static void initialize(iotjs_environment_t* env); /** * Get the singleton instance of iotjs_environment_t. */ iotjs_environment_t* iotjs_environment_get(void) { if (!initialized) { initialize(¤t_env); initialized = true; } return ¤t_env; } /** * Release the singleton instance of iotjs_environment_t, and debugger config. */ void iotjs_environment_release(void) { if (!initialized) return; iotjs_environment_t* env = iotjs_environment_get(); #ifdef JERRY_DEBUGGER IOTJS_RELEASE(env->config.debugger); #endif IOTJS_RELEASE(env->argv); initialized = false; } static void initialize(iotjs_environment_t* env) { env->argc = 0; env->argv = NULL; env->loop = NULL; env->state = kInitializing; env->config.memstat = false; env->config.show_opcode = false; #ifdef JERRY_DEBUGGER env->config.debugger = NULL; #endif env->exitcode = 0; } /** * Parse command line arguments */ bool iotjs_environment_parse_command_line_arguments(iotjs_environment_t* env, uint32_t argc, char** argv) { // declare options const cli_option_t opts[] = { { .id = OPT_HELP, .opt = "h", .longopt = "help", .help = "print this help and exit", }, { .id = OPT_MEM_STATS, .longopt = "mem-stats", .help = "dump memory statistics", }, { .id = OPT_SHOW_OP, .longopt = "show-opcodes", .help = "dump parser byte-code", }, #ifdef JERRY_DEBUGGER { .id = OPT_DEBUG_SERVER, .opt = "d", .longopt = "start-debug-server", .help = "start debug server and wait for a connecting client", }, { .id = OPT_DEBUGGER_WAIT_SOURCE, .opt = "w", .longopt = "debugger-wait-source", .help = "wait for an executable source from the client", }, { .id = OPT_DEBUG_PORT, .longopt = "debug-port", .more = 1, .help = "debug server port (default: 5001)", }, { .id = OPT_DEBUG_CHANNEL, .longopt = "debug-channel", .help = "specify the debugger transmission channel" " (default: websocket)", }, { .id = OPT_DEBUG_PROTOCOL, .longopt = "debug-protocol", .help = "Specify the transmission protocol over the communication" " channel (default: tcp)", }, { .id = OPT_DEBUG_SERIAL_CONFIG, .longopt = "debug-serial-config", .help = "configure parameters for serial port" " (default: /dev/ttyS0,115200,8,N,1)", }, #endif }; const cli_option_t* cur_opt; uint32_t i = 1; while (i < argc && argv[i][0] == '-') { cur_opt = NULL; // check if the known option is given. for (uint32_t k = 0; k < NUM_OF_OPTIONS; k++) { if ((opts[k].opt && !strcmp(&argv[i][1], opts[k].opt)) || (opts[k].longopt && !strcmp(&argv[i][2], opts[k].longopt))) { cur_opt = &opts[k]; break; } } if (cur_opt == NULL) { fprintf(stderr, "unknown command line option: %s\n", argv[i]); return false; } switch (cur_opt->id) { case OPT_HELP: { fprintf(stderr, "%s\n Options:\n\n", CLI_DEFAULT_HELP_STRING); for (uint32_t k = 0; k < NUM_OF_OPTIONS; k++) { if (opts[k].opt) { fprintf(stderr, " -%s, --%-21s %s\n", opts[k].opt, opts[k].longopt, opts[k].help); } else { fprintf(stderr, " --%-25s %s\n", opts[k].longopt, opts[k].help); } } fprintf(stderr, "\n"); return false; } case OPT_MEM_STATS: { env->config.memstat = true; } break; case OPT_SHOW_OP: { env->config.show_opcode = true; } break; #ifdef JERRY_DEBUGGER case OPT_DEBUGGER_WAIT_SOURCE: case OPT_DEBUG_SERVER: { if (!env->config.debugger) { env->config.debugger = (DebuggerConfig*)iotjs_buffer_allocate(sizeof(DebuggerConfig)); } env->config.debugger->port = 5001; env->config.debugger->context_reset = false; env->config.debugger->wait_source = cur_opt->id == OPT_DEBUGGER_WAIT_SOURCE; char default_channel[] = "websocket"; char default_protocol[] = "tcp"; char default_serial_config[] = "/dev/ttyS0,115200,8,N,1"; memcpy(env->config.debugger->channel, default_channel, strlen(default_channel) + 1); memcpy(env->config.debugger->protocol, default_protocol, strlen(default_protocol) + 1); memcpy(env->config.debugger->serial_config, default_serial_config, strlen(default_serial_config) + 1); } break; case OPT_DEBUG_PORT: { if (env->config.debugger) { char* pos = NULL; env->config.debugger->port = (uint16_t)strtoul(argv[i + 1], &pos, 10); } i++; } break; case OPT_DEBUG_CHANNEL: { if (env->config.debugger) { memset(env->config.debugger->channel, 0, strlen(env->config.debugger->channel) + 1); memcpy(env->config.debugger->channel, argv[i + 1], strlen(argv[i + 1]) + 1); if (strcmp(env->config.debugger->channel, "websocket") && strcmp(env->config.debugger->channel, "rawpacket")) { fprintf(stderr, "Debug channel %s is not supported." " Only websocket or rawpacket is allowed\n", env->config.debugger->channel); return false; } } i++; } break; case OPT_DEBUG_PROTOCOL: { if (env->config.debugger) { memset(env->config.debugger->protocol, 0, strlen(env->config.debugger->protocol) + 1); memcpy(env->config.debugger->protocol, argv[i + 1], strlen(argv[i + 1]) + 1); if (strcmp(env->config.debugger->protocol, "tcp") && strcmp(env->config.debugger->protocol, "serial")) { fprintf(stderr, "Debug protocol %s is not supported." " Only tcp or serial is allowed\n", env->config.debugger->protocol); return false; } } i++; } break; case OPT_DEBUG_SERIAL_CONFIG: { if (env->config.debugger) { memset(env->config.debugger->serial_config, 0, strlen(env->config.debugger->serial_config) + 1); memcpy(env->config.debugger->serial_config, argv[i + 1], strlen(argv[i + 1]) + 1); } i++; } break; #endif default: break; } // increase index of argv i += (1 + cur_opt->more); } #ifdef JERRY_DEBUGGER // If IoT.js is waiting for source from the debugger client, // Further processing over command line argument is not needed. if (env->config.debugger && env->config.debugger->wait_source) return true; #endif // There must be at least one argument after processing the IoT.js args, if (argc - i < 1) { fprintf(stderr, CLI_DEFAULT_HELP_STRING); return false; } // Remaining arguments are for application. env->argc = 2; size_t buffer_size = ((size_t)(env->argc + argc - i)) * sizeof(char*); env->argv = (char**)iotjs_buffer_allocate(buffer_size); env->argv[0] = argv[0]; env->argv[1] = argv[i++]; // Clonning for argv is not required. // 1) We will only read // 2) Standard C guarantees that strings pointed by the argv array shall // retain between program startup and program termination while (i < argc) env->argv[env->argc++] = argv[i++]; return true; } uint32_t iotjs_environment_argc(const iotjs_environment_t* env) { return env->argc; } const char* iotjs_environment_argv(const iotjs_environment_t* env, uint32_t idx) { return env->argv[idx]; } uv_loop_t* iotjs_environment_loop(const iotjs_environment_t* env) { return env->loop; } void iotjs_environment_set_loop(iotjs_environment_t* env, uv_loop_t* loop) { env->loop = loop; } const Config* iotjs_environment_config(const iotjs_environment_t* env) { return &env->config; } void iotjs_environment_set_state(iotjs_environment_t* env, State s) { switch (s) { case kInitializing: break; case kRunningMain: IOTJS_ASSERT(env->state == kInitializing); break; case kRunningLoop: IOTJS_ASSERT(env->state == kRunningMain); break; case kExiting: IOTJS_ASSERT(env->state < kExiting); break; default: IOTJS_ASSERT(!"Should not reach here."); } env->state = s; } bool iotjs_environment_is_exiting(iotjs_environment_t* env) { return env->state == kExiting; } iotjs-1.0+715/src/iotjs_env.h000066400000000000000000000045171371177304000157640ustar00rootroot00000000000000/* 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_ENV_H #define IOTJS_ENV_H #include "uv.h" #ifdef JERRY_DEBUGGER typedef struct { bool wait_source; bool context_reset; uint16_t port; char channel[16]; char protocol[16]; char serial_config[64]; } DebuggerConfig; #endif typedef struct { uint32_t memstat : 1; uint32_t show_opcode : 1; #ifdef JERRY_DEBUGGER DebuggerConfig* debugger; #endif } Config; typedef enum { kInitializing, kRunningMain, kRunningLoop, kExiting, } State; typedef struct { // Number of application arguments including 'iotjs' and app name. uint32_t argc; // Application arguments list including 'iotjs' and app name. char** argv; // I/O event loop. uv_loop_t* loop; // Running state. State state; // Run config Config config; // Exitcode uint8_t exitcode; } iotjs_environment_t; iotjs_environment_t* iotjs_environment_get(void); void iotjs_environment_release(void); bool iotjs_environment_parse_command_line_arguments(iotjs_environment_t* env, uint32_t argc, char** argv); uint32_t iotjs_environment_argc(const iotjs_environment_t* env); const char* iotjs_environment_argv(const iotjs_environment_t* env, uint32_t idx); uv_loop_t* iotjs_environment_loop(const iotjs_environment_t* env); void iotjs_environment_set_loop(iotjs_environment_t* env, uv_loop_t* loop); const Config* iotjs_environment_config(const iotjs_environment_t* env); #ifdef JERRY_DEBUGGER const DebuggerConfig* iotjs_environment_dconfig(const iotjs_environment_t* env); #endif void iotjs_environment_set_state(iotjs_environment_t* env, State s); bool iotjs_environment_is_exiting(iotjs_environment_t* env); #endif /* IOTJS_ENV_H */ iotjs-1.0+715/src/iotjs_magic_strings.h000066400000000000000000000355661371177304000200350ustar00rootroot00000000000000/* 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_MAGIC_STRINGS_H #define IOTJS_MAGIC_STRINGS_H #if ENABLE_MODULE_SPI #define IOTJS_MAGIC_STRING_0 "0" #define IOTJS_MAGIC_STRING_1 "1" #define IOTJS_MAGIC_STRING_2 "2" #define IOTJS_MAGIC_STRING_3 "3" #endif #define IOTJS_MAGIC_STRING_ABORT "abort" #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_ACKTYPE "type" #endif #if ENABLE_MODULE_ADC #define IOTJS_MAGIC_STRING_ADC "Adc" #endif #define IOTJS_MAGIC_STRING_ADDHEADER "addHeader" #if ENABLE_MODULE_UDP #define IOTJS_MAGIC_STRING_ADDMEMBERSHIP "addMembership" #endif #define IOTJS_MAGIC_STRING_ADDRESS "address" #define IOTJS_MAGIC_STRING_ARCH "arch" #define IOTJS_MAGIC_STRING_ARGV "argv" #define IOTJS_MAGIC_STRING_BASE64 "base64" #if ENABLE_MODULE_CRYPTO #define IOTJS_MAGIC_STRING_BASE64ENCODE "base64Encode" #endif #if ENABLE_MODULE_UART #define IOTJS_MAGIC_STRING_BAUDRATE "baudRate" #endif #define IOTJS_MAGIC_STRING_BIND "bind" #if ENABLE_MODULE_BLE #define IOTJS_MAGIC_STRING_BINDCONTROL "bindControl" #endif #define IOTJS_MAGIC_STRING_BINDING "binding" #if ENABLE_MODULE_BLE #define IOTJS_MAGIC_STRING_BINDRAW "bindRaw" #define IOTJS_MAGIC_STRING_BINDUSER "bindUser" #endif #if ENABLE_MODULE_SPI #define IOTJS_MAGIC_STRING_BITORDER "bitOrder" #define IOTJS_MAGIC_STRING_BITORDER_U "BITORDER" #define IOTJS_MAGIC_STRING_BITSPERWORD "bitsPerWord" #endif #define IOTJS_MAGIC_STRING_BOARD "board" #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_BOTH_U "BOTH" #endif #define IOTJS_MAGIC_STRING_BUFFER "Buffer" #define IOTJS_MAGIC_STRING_BUILTIN_MODULES "builtin_modules" #if ENABLE_MODULE_I2C || ENABLE_MODULE_SPI #define IOTJS_MAGIC_STRING_BUS "bus" #endif #define IOTJS_MAGIC_STRING_BYTELENGTH "byteLength" #define IOTJS_MAGIC_STRING_BYTEPARSED "byteParsed" #define IOTJS_MAGIC_STRING_FROM_ARRAYBUFFER "fromArrayBuffer" #if ENABLE_MODULE_HTTPS || ENABLE_MODULE_TLS #define IOTJS_MAGIC_STRING_CA "ca" #define IOTJS_MAGIC_STRING_CERT "cert" #endif #define IOTJS_MAGIC_STRING_CHDIR "chdir" #if ENABLE_MODULE_PWM #define IOTJS_MAGIC_STRING_CHIP "chip" #endif #if ENABLE_MODULE_SPI #define IOTJS_MAGIC_STRING_CHIPSELECT "chipSelect" #define IOTJS_MAGIC_STRING_CHIPSELECT_U "CHIPSELECT" #endif #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_CLIENTID "clientId" #endif #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_COMPILEMODULE "compileModule" #define IOTJS_MAGIC_STRING_CONFIG "config" #define IOTJS_MAGIC_STRING_CONNECT "connect" #define IOTJS_MAGIC_STRING_COPY "copy" #if ENABLE_MODULE_HTTPS #define IOTJS_MAGIC_STRING_CREATEREQUEST "createRequest" #endif #define IOTJS_MAGIC_STRING__CREATESTAT "_createStat" #define IOTJS_MAGIC_STRING_CREATETCP "createTCP" #define IOTJS_MAGIC_STRING_CWD "cwd" #define IOTJS_MAGIC_STRING_DATA "data" #if ENABLE_MODULE_UART #define IOTJS_MAGIC_STRING_DATABITS "dataBits" #endif #ifdef DEBUG #define IOTJS_MAGIC_STRING_DEBUG "debug" #endif #define IOTJS_MAGIC_STRING_DEBUGGERGETSOURCE "debuggerGetSource" #define IOTJS_MAGIC_STRING_DEBUGGERWAITSOURCE "debuggerWaitSource" #if ENABLE_MODULE_WEBSOCKET #define IOTJS_MAGIC_STRING_DECODEFRAME "decodeFrame" #endif #define IOTJS_MAGIC_STRING_DEVICE "device" #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_DIRECTION "direction" #define IOTJS_MAGIC_STRING_DIRECTION_U "DIRECTION" #endif #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_DISCONNECT "disconnect" #endif #define IOTJS_MAGIC_STRING_DOEXIT "doExit" #if ENABLE_MODULE_UDP #define IOTJS_MAGIC_STRING_DROPMEMBERSHIP "dropMembership" #endif #if ENABLE_MODULE_PWM #define IOTJS_MAGIC_STRING_DUTYCYCLE "dutyCycle" #endif #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_EDGE "edge" #define IOTJS_MAGIC_STRING_EDGE_U "EDGE" #endif #define IOTJS_MAGIC_STRING_EMIT "emit" #define IOTJS_MAGIC_STRING_EMITEXIT "emitExit" #if ENABLE_MODULE_TLS #define IOTJS_MAGIC_STRING_END "end" #endif #define IOTJS_MAGIC_STRING_ENV "env" #define IOTJS_MAGIC_STRING_ERRNAME "errname" #define IOTJS_MAGIC_STRING_EXECUTE "execute" #define IOTJS_MAGIC_STRING_EXITCODE "exitCode" #define IOTJS_MAGIC_STRING_EXPORT "export" #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_FALLING_U "FALLING" #endif #define IOTJS_MAGIC_STRING_FAMILY "family" #define IOTJS_MAGIC_STRING_FINISH "finish" #if ENABLE_MODULE_HTTPS #define IOTJS_MAGIC_STRING_FINISHREQUEST "finishRequest" #endif #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_FLOAT_U "FLOAT" #endif #define IOTJS_MAGIC_STRING_FSTAT "fstat" #if EXPOSE_GC #define IOTJS_MAGIC_STRING_GC "gc" #endif #define IOTJS_MAGIC_STRING_GETADDRINFO "getaddrinfo" #define IOTJS_MAGIC_STRING_GETSOCKNAME "getsockname" #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_GPIO "Gpio" #endif #define IOTJS_MAGIC_STRING_HANDLER "handler" #define IOTJS_MAGIC_STRING_HANDLETIMEOUT "handleTimeout" #define IOTJS_MAGIC_STRING_HEADERS "headers" #define IOTJS_MAGIC_STRING_HEX "hex" #if ENABLE_MODULE_SPI #define IOTJS_MAGIC_STRING_HIGH_U "HIGH" #endif #define IOTJS_MAGIC_STRING_HOME_U "HOME" #define IOTJS_MAGIC_STRING_HOST "host" #define IOTJS_MAGIC_STRING_HTTPPARSER "HTTPParser" #define IOTJS_MAGIC_STRING_HTTP_VERSION_MAJOR "http_major" #define IOTJS_MAGIC_STRING_HTTP_VERSION_MINOR "http_minor" #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_IN "IN" #endif #define IOTJS_MAGIC_STRING__INCOMING "_incoming" #define IOTJS_MAGIC_STRING_IOTJS_ENV_U "IOTJS_ENV" #define IOTJS_MAGIC_STRING_IOTJS_PATH_U "IOTJS_PATH" #define IOTJS_MAGIC_STRING_IOTJS_EXTRA_MODULE_PATH_U "IOTJS_EXTRA_MODULE_PATH" #define IOTJS_MAGIC_STRING_IOTJS_WORKING_DIR_PATH_U "IOTJS_WORKING_DIR_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_ISDIRECTORY "isDirectory" #define IOTJS_MAGIC_STRING_ISFILE "isFile" #if ENABLE_MODULE_TLS #define IOTJS_MAGIC_STRING_ISSERVER "isServer" #endif #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_KEEPALIVE "keepalive" #endif #define IOTJS_MAGIC_STRING_KEY "key" #define IOTJS_MAGIC_STRING_LENGTH "length" #define IOTJS_MAGIC_STRING_LISTEN "listen" #define IOTJS_MAGIC_STRING_LOOPBACK "loopback" #if ENABLE_MODULE_SPI #define IOTJS_MAGIC_STRING_LSB "LSB" #define IOTJS_MAGIC_STRING_MAXSPEED "maxSpeed" #endif #if ENABLE_MODULE_MQTT || ENABLE_MODULE_WEBSOCKET #define IOTJS_MAGIC_STRING_MESSAGE "message" #endif #define IOTJS_MAGIC_STRING_METHOD "method" #define IOTJS_MAGIC_STRING_METHODS "methods" #define IOTJS_MAGIC_STRING_MKDIR "mkdir" #define IOTJS_MAGIC_STRING_MODE "mode" #if ENABLE_MODULE_SPI || ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_MODE_U "MODE" #endif #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_MQTTINIT "MqttInit" #define IOTJS_MAGIC_STRING_MQTTMESSAGE "MqttMessage" #define IOTJS_MAGIC_STRING_MQTTRECEIVE "MqttReceive" #endif #if ENABLE_MODULE_SPI #define IOTJS_MAGIC_STRING_MSB "MSB" #endif #if ENABLE_MODULE_SPI || ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_NONE_U "NONE" #endif #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_ONACK "onack" #endif #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" #if ENABLE_MODULE_TLS #define IOTJS_MAGIC_STRING_ONHANDSHAKEDONE "onhandshakedone" #endif #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" #if ENABLE_MODULE_WEBSOCKET #define IOTJS_MAGIC_STRING_ONPING "onping" #endif #if ENABLE_MODULE_MQTT || ENABLE_MODULE_WEBSOCKET #define IOTJS_MAGIC_STRING_ONPINGRESP "onpingresp" #endif #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_ONPUBREC "onpubrec" #define IOTJS_MAGIC_STRING_ONPUBREL "onpubrel" #endif #define IOTJS_MAGIC_STRING_ONREAD "onread" #define IOTJS_MAGIC_STRING_ONSOCKET "onSocket" #define IOTJS_MAGIC_STRING_ONTIMEOUT "onTimeout" #define IOTJS_MAGIC_STRING__ONUNCAUGHTEXCEPTION "_onUncaughtException" #if ENABLE_MODULE_TLS #define IOTJS_MAGIC_STRING_ONWRITE "onwrite" #endif #define IOTJS_MAGIC_STRING_ONWRITABLE "onWritable" #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_OPENDRAIN_U "OPENDRAIN" #endif #define IOTJS_MAGIC_STRING_OPEN "open" #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_OUT_U "OUT" #endif #define IOTJS_MAGIC_STRING_OWNER "owner" #if ENABLE_MODULE_WEBSOCKET #define IOTJS_MAGIC_STRING_PARSEHANDSHAKEDATA "parseHandshakeData" #endif #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_PASSWORD "password" #endif #define IOTJS_MAGIC_STRING_PAUSE "pause" #define IOTJS_MAGIC_STRING_PERIOD "period" #define IOTJS_MAGIC_STRING_PID "pid" #define IOTJS_MAGIC_STRING_PIN "pin" #if ENABLE_MODULE_MQTT || ENABLE_MODULE_WEBSOCKET #define IOTJS_MAGIC_STRING_PING "ping" #endif #define IOTJS_MAGIC_STRING_PLATFORM "platform" #if ENABLE_MODULE_WEBSOCKET #define IOTJS_MAGIC_STRING_PONG "pong" #endif #define IOTJS_MAGIC_STRING_PORT "port" #if ENABLE_MODULE_WEBSOCKET #define IOTJS_MAGIC_STRING_PREPAREHANDSHAKE "prepareHandshake" #endif #define IOTJS_MAGIC_STRING_PRIVATE "_private" #define IOTJS_MAGIC_STRING_PROTOTYPE "prototype" #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_PUBLISH "publish" #endif #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_PULLDOWN_U "PULLDOWN" #define IOTJS_MAGIC_STRING_PULLUP_U "PULLUP" #define IOTJS_MAGIC_STRING_PUSHPULL_U "PUSHPULL" #endif #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_QOS "qos" #endif #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" #if ENABLE_MODULE_DGRAM #define IOTJS_MAGIC_STRING_RECVSTART "recvStart" #define IOTJS_MAGIC_STRING_RECVSTOP "recvStop" #endif #define IOTJS_MAGIC_STRING_REF "ref" #if ENABLE_MODULE_TLS || ENABLE_MODULE_HTTPS #define IOTJS_MAGIC_STRING_REJECTUNAUTHORIZED "rejectUnauthorized" #endif #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_REMAINING "remaining" #endif #define IOTJS_MAGIC_STRING_RENAME "rename" #define IOTJS_MAGIC_STRING_REQUEST_U "REQUEST" #define IOTJS_MAGIC_STRING_RESPONSE_U "RESPONSE" #define IOTJS_MAGIC_STRING_RESUME "resume" #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_RETAIN "retain" #endif #define IOTJS_MAGIC_STRING__REUSEADDR "_reuseAddr" #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_RISING_U "RISING" #endif #define IOTJS_MAGIC_STRING_RMDIR "rmdir" #if ENABLE_MODULE_CRYPTO #define IOTJS_MAGIC_STRING_RSAVERIFY "rsaVerify" #endif #define IOTJS_MAGIC_STRING_SEND "send" #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_SENDACK "sendAck" #endif #define IOTJS_MAGIC_STRING_SENDREQUEST "sendRequest" #if ENABLE_MODULE_TLS #define IOTJS_MAGIC_STRING_SERVERNAME "servername" #endif #if ENABLE_MODULE_I2C #define IOTJS_MAGIC_STRING_SETADDRESS "setAddress" #endif #if ENABLE_MODULE_UDP #define IOTJS_MAGIC_STRING_CONFIGURE "configure" #endif #if ENABLE_MODULE_GPIO #define IOTJS_MAGIC_STRING_SETDIRECTIONSYNC "setDirectionSync" #endif #if ENABLE_MODULE_PWM #define IOTJS_MAGIC_STRING_SETDUTYCYCLE "setDutyCycle" #define IOTJS_MAGIC_STRING_SETDUTYCYCLESYNC "setDutyCycleSync" #define IOTJS_MAGIC_STRING_SETENABLE "setEnable" #define IOTJS_MAGIC_STRING_SETENABLESYNC "setEnableSync" #define IOTJS_MAGIC_STRING_SETFREQUENCY "setFrequency" #define IOTJS_MAGIC_STRING_SETFREQUENCYSYNC "setFrequencySync" #endif #if ENABLE_MODULE_BLE #define IOTJS_MAGIC_STRING_SETFILTER "setFilter" #endif #define IOTJS_MAGIC_STRING_SETKEEPALIVE "setKeepAlive" #if ENABLE_MODULE_PWM #define IOTJS_MAGIC_STRING_SETPERIOD "setPeriod" #define IOTJS_MAGIC_STRING_SETPERIODSYNC "setPeriodSync" #endif #define IOTJS_MAGIC_STRING_SETTIMEOUT "setTimeout" #if ENABLE_MODULE_CRYPTO #define IOTJS_MAGIC_STRING_SHAENCODE "shaEncode" #endif #define IOTJS_MAGIC_STRING_SHOULDKEEPALIVE "shouldkeepalive" #define IOTJS_MAGIC_STRING_SHUTDOWN "shutdown" #define IOTJS_MAGIC_STRING_SLICE "slice" #if ENABLE_MODULE_SPI #define IOTJS_MAGIC_STRING_SPI "Spi" #endif #define IOTJS_MAGIC_STRING_START "start" #define IOTJS_MAGIC_STRING_STAT "stat" #define IOTJS_MAGIC_STRING_STATS "stats" #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" #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_SUBSCRIBE "subscribe" #endif #if ENABLE_MODULE_TLS #define IOTJS_MAGIC_STRING_TLSSOCKET "TLSSocket" #define IOTJS_MAGIC_STRING_TLSCONTEXT "TlsContext" #define IOTJS_MAGIC_STRING_TLSINIT "TlsInit" #endif #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_TOPIC "topic" #endif #define IOTJS_MAGIC_STRING_TOSTRING "toString" #if ENABLE_MODULE_SPI #define IOTJS_MAGIC_STRING_TRANSFER "transfer" #define IOTJS_MAGIC_STRING_TRANSFERSYNC "transferSync" #endif #define IOTJS_MAGIC_STRING_UNLINK "unlink" #define IOTJS_MAGIC_STRING_UNREF "unref" #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_UNSUBSCRIBE "unsubscribe" #endif #define IOTJS_MAGIC_STRING_UPGRADE "upgrade" #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_USERNAME "username" #endif #define IOTJS_MAGIC_STRING_URL "url" #define IOTJS_MAGIC_STRING_VERSION "version" #if ENABLE_MODULE_MQTT #define IOTJS_MAGIC_STRING_WILL "will" #endif #define IOTJS_MAGIC_STRING_WRITEUINT8 "writeUInt8" #define IOTJS_MAGIC_STRING_WRITE "write" #define IOTJS_MAGIC_STRING_WRITEDECODE "writeDecode" #define IOTJS_MAGIC_STRING_WRITESYNC "writeSync" #if ENABLE_MODULE_HTTPS #define IOTJS_MAGIC_STRING__WRITE "_write" #endif #if ENABLE_MODULE_WEBSOCKET #define IOTJS_MAGIC_STRING_WSINIT "wsInit" #define IOTJS_MAGIC_STRING_WSRECEIVE "wsReceive" #define IOTJS_MAGIC_STRING_WSRECEIVEHANDSHAKEDATA "ReceiveHandshakeData" #endif #if ENABLE_MODULE_BRIDGE #define IOTJS_MAGIC_STRING_MODULE_NAME "MODULE_NAME" #endif #if ENABLE_MODULE_TIZEN #define IOTJS_MAGIC_STRING_TIZEN "tizen" #define IOTJS_MAGIC_STRING_APP_CONTROL "appControl" #endif #if ENABLE_MODULE_NAPI #define IOTJS_MAGIC_STRING_ERROR "Error" #endif #endif /* IOTJS_MAGIC_STRINGS_H */ iotjs-1.0+715/src/iotjs_module.c000066400000000000000000000030341371177304000164450ustar00rootroot00000000000000/* 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.h" typedef struct { jerry_value_t jmodule; } iotjs_module_rw_data_t; #include "iotjs_module_inl.h" /** * iotjs_module_inl.h provides: * - iotjs_module_count * - iotjs_module_ro_data[] * - iotjs_module_rw_data[] */ void iotjs_module_list_cleanup(void) { for (unsigned i = 0; i < iotjs_module_count; i++) { if (iotjs_module_rw_data[i].jmodule != 0) { jerry_release_value(iotjs_module_rw_data[i].jmodule); iotjs_module_rw_data[i].jmodule = 0; } } } jerry_value_t iotjs_module_get(const char* name) { for (unsigned i = 0; i < iotjs_module_count; i++) { if (!strcmp(name, iotjs_module_ro_data[i].name)) { if (iotjs_module_rw_data[i].jmodule == 0) { iotjs_module_rw_data[i].jmodule = iotjs_module_ro_data[i].fn_register(); } return iotjs_module_rw_data[i].jmodule; } } return jerry_create_undefined(); } iotjs-1.0+715/src/iotjs_module.h000066400000000000000000000020651371177304000164550ustar00rootroot00000000000000/* 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_MODULE_H #define IOTJS_MODULE_H #include "iotjs_binding.h" typedef jerry_value_t (*register_func)(void); typedef struct { const char* name; register_func fn_register; } iotjs_module_ro_data_t; extern const unsigned iotjs_module_count; extern const iotjs_module_ro_data_t iotjs_module_ro_data[]; void iotjs_module_list_cleanup(void); jerry_value_t iotjs_module_get(const char* name); #endif /* IOTJS_MODULE_H */ iotjs-1.0+715/src/iotjs_string.c000066400000000000000000000042311371177304000164660ustar00rootroot00000000000000/* 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_string.h" #include "iotjs_util.h" #include iotjs_string_t iotjs_string_create(void) { iotjs_string_t str; str.size = 0; str.data = NULL; return str; } iotjs_string_t iotjs_string_create_with_size(const char* data, size_t size) { iotjs_string_t str; str.size = size; if (data && size > 0) { str.data = iotjs_buffer_allocate(size); memcpy(str.data, data, size); } else { str.data = NULL; } return str; } iotjs_string_t iotjs_string_create_with_buffer(char* buffer, size_t size) { iotjs_string_t str; str.size = size; if (size > 0) { IOTJS_ASSERT(buffer != NULL); str.data = buffer; } else { str.data = NULL; } return str; } void iotjs_string_destroy(iotjs_string_t* str) { IOTJS_RELEASE(str->data); str->size = 0; } bool iotjs_string_is_empty(const iotjs_string_t* str) { return str->size == 0; } void iotjs_string_append(iotjs_string_t* str, const char* data, size_t size) { IOTJS_ASSERT(data != NULL); if (data == NULL || size == 0) { return; } if (str->data != NULL) { str->data = iotjs_buffer_reallocate(str->data, str->size + size); } else { IOTJS_ASSERT(str->size == 0); str->data = iotjs_buffer_allocate(size); } memcpy(str->data + str->size, data, size); str->size += size; } const char* iotjs_string_data(const iotjs_string_t* str) { if (str->data == NULL) { return ""; } return str->data; } unsigned iotjs_string_size(const iotjs_string_t* str) { return str->size; } iotjs-1.0+715/src/iotjs_string.h000066400000000000000000000026621371177304000165010ustar00rootroot00000000000000/* 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_STRING_H #define IOTJS_STRING_H #include typedef struct { size_t size; char* data; } iotjs_string_t; // Create new string iotjs_string_t iotjs_string_create(void); iotjs_string_t iotjs_string_create_with_size(const char* data, size_t size); iotjs_string_t iotjs_string_create_with_buffer(char* buffer, size_t size); // Destroy string void iotjs_string_destroy(iotjs_string_t* str); // Check if string is empty bool iotjs_string_is_empty(const iotjs_string_t* str); // Append `data` to tail of the string. void iotjs_string_append(iotjs_string_t* str, const char* data, size_t size); // Returns pointer to the bytes (never returns NULL) const char* iotjs_string_data(const iotjs_string_t* str); unsigned iotjs_string_size(const iotjs_string_t* str); #endif /* IOTJS_STRING_H */ iotjs-1.0+715/src/iotjs_string_ext.c000066400000000000000000000032511371177304000173470ustar00rootroot00000000000000/* 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" // // strings in iotjs built-in scripts // #include "iotjs_string_ext.inl.h" // // declare string items // #define MAGICSTR_EX_DEF(NAME, STRING) \ static const char jerry_magic_string_ex_##NAME[] = STRING; JERRY_MAGIC_STRING_ITEMS #undef MAGICSTR_EX_DEF // // declare strings length array // static const jerry_length_t magic_string_lengths[] = { #define MAGICSTR_EX_DEF(NAME, STRING) \ (jerry_length_t)(sizeof(jerry_magic_string_ex_##NAME) - 1u), JERRY_MAGIC_STRING_ITEMS #undef MAGICSTR_EX_DEF }; // // declare strings table // static const jerry_char_t *const magic_string_items[] = { #define MAGICSTR_EX_DEF(NAME, STRING) \ (const jerry_char_t *)jerry_magic_string_ex_##NAME, JERRY_MAGIC_STRING_ITEMS #undef MAGICSTR_EX_DEF }; void iotjs_register_jerry_magic_string(void) { uint32_t num_magic_string_items = (uint32_t)(sizeof(magic_string_items) / sizeof(jerry_char_t *)); jerry_register_magic_strings(magic_string_items, num_magic_string_items, magic_string_lengths); } iotjs-1.0+715/src/iotjs_string_ext.h000066400000000000000000000014111371177304000173500ustar00rootroot00000000000000/* 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_STRING_EXT_H #define IOTJS_STRING_EXT_H void iotjs_register_jerry_magic_string(void); #endif /* IOTJS_STRING_EXT_H */ iotjs-1.0+715/src/iotjs_util.c000066400000000000000000000075051371177304000161440ustar00rootroot00000000000000/* 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_util.h" #include #include #include #if defined(__linux__) && !defined(__OPENWRT__) #include #endif void force_terminate(void); iotjs_string_t iotjs_file_read(const char* path) { FILE* file = fopen(path, "rb"); if (file == NULL) { iotjs_string_t empty_content = iotjs_string_create(); return empty_content; } int fseek_ret = fseek(file, 0, SEEK_END); IOTJS_ASSERT(fseek_ret == 0); long ftell_ret = ftell(file); IOTJS_ASSERT(ftell_ret >= 0); size_t len = (size_t)ftell_ret; fseek_ret = fseek(file, 0, SEEK_SET); IOTJS_ASSERT(fseek_ret == 0); if (ftell_ret < 0 || fseek_ret != 0) { iotjs_string_t empty_content = iotjs_string_create(); fclose(file); DLOG("iotjs_file_read error"); return empty_content; } char* buffer = iotjs_buffer_allocate(len + 1); #if defined(__NUTTX__) || defined(__TIZENRT__) char* ptr = buffer; unsigned nread = 0; unsigned read = 0; while ((nread = fread(ptr, 1, IOTJS_MAX_READ_BUFFER_SIZE, file)) > 0) { read += nread; ptr = buffer + read; } #else size_t read = fread(buffer, 1, len, file); #endif IOTJS_ASSERT(read == len); *(buffer + len) = 0; fclose(file); iotjs_string_t contents = iotjs_string_create_with_buffer(buffer, len); return contents; } char* iotjs_buffer_allocate(size_t size) { char* buffer = (char*)(calloc(size, sizeof(char))); if (buffer == NULL) { DLOG("Out of memory"); force_terminate(); } return buffer; } char* iotjs_buffer_allocate_from_number_array(size_t size, const jerry_value_t array) { char* buffer = iotjs_buffer_allocate(size); for (size_t i = 0; i < size; i++) { jerry_value_t jdata = iotjs_jval_get_property_by_index(array, i); buffer[i] = iotjs_jval_as_number(jdata); jerry_release_value(jdata); } return buffer; } char* iotjs_buffer_reallocate(char* buffer, size_t size) { IOTJS_ASSERT(buffer != NULL); char* newbuffer = (char*)(realloc(buffer, size)); if (newbuffer == NULL) { DLOG("Out of memmory"); force_terminate(); } return newbuffer; } void iotjs_buffer_release(char* buffer) { if (buffer) { free(buffer); } } void print_stacktrace(void) { #if !defined(NDEBUG) && defined(__linux__) && defined(DEBUG) && \ !defined(__OPENWRT__) // TODO: support other platforms const int numOfStackTrace = 100; void* buffer[numOfStackTrace]; char command[256]; int nptrs = backtrace(buffer, numOfStackTrace); char** strings = backtrace_symbols(buffer, nptrs); if (strings == NULL) { perror("backtrace_symbols"); exit(EXIT_FAILURE); } printf("\n[Backtrace]:\n"); for (int j = 0; j < nptrs - 2; j++) { // remove the last two int idx = 0; while (strings[j][idx] != '\0') { if (strings[j][idx] == '(') { break; } idx++; } snprintf(command, sizeof(command), "addr2line %p -e %.*s", buffer[j], idx, strings[j]); if (system(command)) { break; } } free(strings); #endif // !defined(NDEBUG) && defined(__linux__) && defined(DEBUG) && // !defined(__OPENWRT__) } void force_terminate(void) { exit(EXIT_FAILURE); } iotjs-1.0+715/src/iotjs_util.h000066400000000000000000000032641371177304000161470ustar00rootroot00000000000000/* 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_UTIL_H #define IOTJS_UTIL_H #include "iotjs_string.h" #include "jerryscript.h" // Return value should be released with iotjs_string_destroy() iotjs_string_t iotjs_file_read(const char* path); char* iotjs_buffer_allocate(size_t size); char* iotjs_buffer_allocate_from_number_array(size_t size, const jerry_value_t array); char* iotjs_buffer_reallocate(char* buffer, size_t size); void iotjs_buffer_release(char* buff); void print_stacktrace(void); #define IOTJS_ALLOC(type) /* Allocate (type)-sized, (type*)-typed memory */ \ (type*)iotjs_buffer_allocate(sizeof(type)) #define IOTJS_CALLOC(num, type) \ (type*)iotjs_buffer_allocate((num * sizeof(type))) #define IOTJS_RELEASE(ptr) /* Release memory allocated by IOTJS_ALLOC() */ \ do { \ iotjs_buffer_release((char*)ptr); \ ptr = NULL; \ } while (0) #endif /* IOTJS_UTIL_H */ iotjs-1.0+715/src/iotjs_uv_handle.c000066400000000000000000000044641371177304000171350ustar00rootroot00000000000000/* Copyright 2018-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_uv_handle.h" uv_handle_t* iotjs_uv_handle_create(size_t handle_size, const jerry_value_t jobject, JNativeInfoType* native_info, size_t extra_data_size) { IOTJS_ASSERT(jerry_value_is_object(jobject)); /* Make sure that the jerry_value_t is aligned */ size_t aligned_request_size = IOTJS_ALIGNUP(handle_size, 8u); char* request_memory = iotjs_buffer_allocate( aligned_request_size + sizeof(iotjs_uv_handle_data) + extra_data_size); uv_handle_t* uv_handle = (uv_handle_t*)request_memory; uv_handle->data = request_memory + aligned_request_size; IOTJS_UV_HANDLE_DATA(uv_handle)->jobject = jobject; IOTJS_UV_HANDLE_DATA(uv_handle)->on_close_cb = NULL; jerry_acquire_value(jobject); jerry_set_object_native_pointer(jobject, uv_handle, native_info); return uv_handle; } static void iotjs_uv_handle_close_processor(uv_handle_t* handle) { iotjs_uv_handle_data* handle_data = IOTJS_UV_HANDLE_DATA(handle); if (handle_data->on_close_cb != NULL) { handle_data->on_close_cb(handle); } // Decrease ref count of Javascript object. From now the object can be // reclaimed. jerry_release_value(handle_data->jobject); IOTJS_RELEASE(handle); } void iotjs_uv_handle_close(uv_handle_t* handle, OnCloseHandler close_handler) { if (handle == NULL || uv_is_closing(handle)) { DDLOG("Attempt to close uninitialized or already closed handle"); return; } iotjs_uv_handle_data* handle_data = IOTJS_UV_HANDLE_DATA(handle); handle_data->on_close_cb = close_handler; uv_close(handle, iotjs_uv_handle_close_processor); } iotjs-1.0+715/src/iotjs_uv_handle.h000066400000000000000000000044141371177304000171350ustar00rootroot00000000000000/* Copyright 2018-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_UV_HANDLE #define IOTJS_UV_HANDLE #include #include "iotjs_binding.h" typedef void (*OnCloseHandler)(uv_handle_t*); typedef struct { jerry_value_t jobject; OnCloseHandler on_close_cb; } iotjs_uv_handle_data; #define IOTJS_ALIGNUP(value, alignment) \ (((value) + ((alignment)-1)) & ~((alignment)-1)) /** * Allocate and initialize an uv_handle_t structure with a jerry callback and * extra data. * * The allocated memory has the following layout: * * |-------------| <- start of uv_handle_t* * | uv_handle_t | * | | * |-------------| * | PADDING | <- alignment padding * |-------------| <- start of the iotjs_uv_handle_data struct * | handle_data | * |-------------| <- start of the extra data if required * | extra | * |-------------| * */ uv_handle_t* iotjs_uv_handle_create(size_t handle_size, const jerry_value_t jobject, JNativeInfoType* native_info, size_t extra_data_size); void iotjs_uv_handle_close(uv_handle_t* handle, OnCloseHandler close_handler); /** * Returns a pointer to the handle data struct referenced * by the uv_handle_t->data member. */ #define IOTJS_UV_HANDLE_DATA(UV_HANDLE) \ ((iotjs_uv_handle_data*)((UV_HANDLE)->data)) /** * Returns a char* pointer for any extra data. * * IMPORTANT! * Make sure that the extra data is correctly allocated by using the * iotjs_uv_handle_create method call. */ #define IOTJS_UV_HANDLE_EXTRA_DATA(UV_HANDLE) \ ((char*)((char*)((UV_HANDLE)->data) + sizeof(iotjs_uv_handle_data))) #endif /* IOTJS_UV_HANDLE */ iotjs-1.0+715/src/iotjs_uv_request.c000066400000000000000000000034171371177304000173670ustar00rootroot00000000000000/* Copyright 2018-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_uv_request.h" #include "iotjs_def.h" /** * Aligns @a value to @a alignment. @a must be the power of 2. * * Returns minimum positive value, that divides @a alignment and is more than or * equal to @a value */ #define IOTJS_ALIGNUP(value, alignment) \ (((value) + ((alignment)-1)) & ~((alignment)-1)) uv_req_t* iotjs_uv_request_create(size_t request_size, const jerry_value_t jcallback, size_t extra_data_size) { IOTJS_ASSERT(jerry_value_is_function(jcallback)); /* Make sure that the jerry_value_t is aligned */ size_t aligned_request_size = IOTJS_ALIGNUP(request_size, 8u); char* request_memory = iotjs_buffer_allocate( aligned_request_size + sizeof(jerry_value_t) + extra_data_size); uv_req_t* uv_request = (uv_req_t*)request_memory; uv_request->data = request_memory + aligned_request_size; *IOTJS_UV_REQUEST_JSCALLBACK(uv_request) = jcallback; jerry_acquire_value(jcallback); return uv_request; } void iotjs_uv_request_destroy(uv_req_t* request) { jerry_release_value(*IOTJS_UV_REQUEST_JSCALLBACK(request)); IOTJS_RELEASE(request); } iotjs-1.0+715/src/iotjs_uv_request.h000066400000000000000000000035641371177304000173770ustar00rootroot00000000000000/* Copyright 2018-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_UV_REQUEST #define IOTJS_UV_REQUEST #include #include "iotjs_binding.h" /** * Allocate and initialize an uv_req_t structure with a jerry callback and extra * data. * * The allocated memory has the following layout: * * |----------| <- start of uv_req_t* * | uv_req_t | * | | * |----------| * | PADDING | <- alignment padding * |----------| <- start of jerry_value_t* which is the callback * | callback | * |----------| <- start of the extra data if required * | extra | * |----------| * */ uv_req_t* iotjs_uv_request_create(size_t request_size, const jerry_value_t jcallback, size_t extra_data_size); void iotjs_uv_request_destroy(uv_req_t* request); /** * Returns a pointer to the js callback referenced by the uv_req_t->data member. */ #define IOTJS_UV_REQUEST_JSCALLBACK(UV_REQ) ((jerry_value_t*)(UV_REQ->data)) /** * Returns a char* pointer for any extra data. * * IMPORTANT! * Make sure that the extra data is correctly allocated via the * iotjs_uv_request_create method call. */ #define IOTJS_UV_REQUEST_EXTRA_DATA(UV_REQ) \ ((char*)((char*)(UV_REQ->data) + sizeof(jerry_value_t))) #endif /* IOTJS_UV_REQUEST */ iotjs-1.0+715/src/js/000077500000000000000000000000001371177304000142205ustar00rootroot00000000000000iotjs-1.0+715/src/js/adc.js000066400000000000000000000016001371177304000153020ustar00rootroot00000000000000/* 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 adc = { open: function(config, callback) { var adcPin = new native(config, function(err) { callback(err, adcPin); }); return adcPin; }, openSync: function(config) { return new native(config); }, }; module.exports = adc; iotjs-1.0+715/src/js/assert.js000066400000000000000000000077241371177304000160710ustar00rootroot00000000000000// Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // Copyright (c) 2015 Samsung Electronics Co., Ltd. // // 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 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. /* 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 util = require('util'); function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; } else { this.message = getMessage(this); } } util.inherits(AssertionError, Error); function getMessage(assertion) { return JSON.stringify(assertion, ['actual', 'expected', 'operator']); } function assert(value, message) { if (!value) { fail(value, true, message, '=='); } } function fail(actual, expected, message, operator) { throw new AssertionError({ message: message, actual: actual, expected: expected, operator: operator, }); } function equal(actual, expected, message) { if (actual != expected) { fail(actual, expected, message, '=='); } } function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!='); } } function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '==='); } } function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!=='); } } function throws(block, expected, message) { var actual; try { block(); } catch (e) { actual = e; } message = (expected && expected.name ? '(' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (!actual) { fail(actual, expected, 'Missing expected exception' + message); } if (expected && !(actual instanceof expected)) { throw actual; } } function doesNotThrow(block, message) { var actual; try { block(); } catch (e) { actual = e; } message = (message ? ' ' + message : ''); if (actual) { fail(actual, null, 'Got unwanted exception.' + message); } } assert.AssertionError = AssertionError; assert.assert = assert; assert.fail = fail; assert.equal = equal; assert.notEqual = notEqual; assert.strictEqual = strictEqual; assert.notStrictEqual = notStrictEqual; assert.throws = throws; assert.doesNotThrow = doesNotThrow; module.exports = assert; iotjs-1.0+715/src/js/ble.js000066400000000000000000000171561371177304000153320ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var debug = console.log; // require('debug')('ble'); var events = require('events'); var util = require('util'); var uuidUtil = require('ble_uuid_util'); var PrimaryService = require('ble_primary_service'); var Characteristic = require('ble_characteristic'); var Descriptor = require('ble_descriptor'); var bindings = null; var platform = process.platform; if (platform === 'darwin') { // bindings = require('./mac/bindings'); } else if (platform === 'linux' || platform === 'win32' || platform === 'android') { bindings = require('ble_hci_socket_bindings'); } else { throw new Error('Unsupported platform'); } function Bleno() { this.platform = 'unknown'; this.state = 'unknown'; this.address = 'unknown'; this.rssi = 0; this.mtu = 20; this._bindings = bindings; this._bindings.on('stateChange', this.onStateChange.bind(this)); this._bindings.on('platform', this.onPlatform.bind(this)); this._bindings.on('addressChange', this.onAddressChange.bind(this)); this._bindings.on('advertisingStart', this.onAdvertisingStart.bind(this)); this._bindings.on('advertisingStop', this.onAdvertisingStop.bind(this)); this._bindings.on('servicesSet', this.onServicesSet.bind(this)); this._bindings.on('accept', this.onAccept.bind(this)); this._bindings.on('mtuChange', this.onMtuChange.bind(this)); this._bindings.on('disconnect', this.onDisconnect.bind(this)); this._bindings.on('rssiUpdate', this.onRssiUpdate.bind(this)); this._bindings.init(); } util.inherits(Bleno, events.EventEmitter); Bleno.prototype.PrimaryService = PrimaryService; Bleno.prototype.Characteristic = Characteristic; Bleno.prototype.Descriptor = Descriptor; Bleno.prototype.onPlatform = function(platform) { debug('platform ' + platform); this.platform = platform; }; Bleno.prototype.onStateChange = function(state) { debug('stateChange ' + state); this.state = state; this.emit('stateChange', state); }; Bleno.prototype.onAddressChange = function(address) { debug('addressChange ' + address); this.address = address; }; Bleno.prototype.onAccept = function(clientAddress) { debug('accept ' + clientAddress); this.emit('accept', clientAddress); }; Bleno.prototype.onMtuChange = function(mtu) { debug('mtu ' + mtu); this.mtu = mtu; this.emit('mtuChange', mtu); }; Bleno.prototype.onDisconnect = function(clientAddress) { debug('disconnect' + clientAddress); this.emit('disconnect', clientAddress); }; Bleno.prototype.startAdvertising = function(name, serviceUuids, callback) { if (this.state !== 'poweredOn') { var error = new Error('Could not start advertising, state is ' + this.state + ' (not poweredOn)'); if (typeof callback === 'function') { callback(error); } else { throw error; } } else { if (callback) { this.once('advertisingStart', callback); } var undashedServiceUuids = []; if (serviceUuids && serviceUuids.length) { for (var i = 0; i < serviceUuids.length; i++) { undashedServiceUuids[i] = uuidUtil.removeDashes(serviceUuids[i]); } } this._bindings.startAdvertising(name, undashedServiceUuids); } }; Bleno.prototype.startAdvertisingIBeacon = function(uuid, major, minor, measuredPower, callback) { if (this.state !== 'poweredOn') { var error = new Error('Could not start advertising, state is ' + this.state + ' (not poweredOn)'); if (typeof callback === 'function') { callback(error); } else { throw error; } } else { var undashedUuid = uuidUtil.removeDashes(uuid); var uuidData = new Buffer(undashedUuid, 'hex'); var uuidDataLength = uuidData.length; var iBeaconData = new Buffer(uuidData.length + 5); for (var i = 0; i < uuidDataLength; i++) { iBeaconData[i] = uuidData[i]; } iBeaconData.writeUInt16BE(major, uuidDataLength); iBeaconData.writeUInt16BE(minor, uuidDataLength + 2); iBeaconData.writeInt8(measuredPower, uuidDataLength + 4); if (callback) { this.once('advertisingStart', callback); } debug('iBeacon data = ' + iBeaconData.toString('hex')); this._bindings.startAdvertisingIBeacon(iBeaconData); } }; Bleno.prototype.onAdvertisingStart = function(error) { debug('advertisingStart: ' + error); if (error) { this.emit('advertisingStartError', error); } this.emit('advertisingStart', error); }; Bleno.prototype.startAdvertisingWithEIRData = function(advertisementData, scanData, callback) { if (typeof scanData === 'function') { callback = scanData; scanData = null; } if (this.state !== 'poweredOn') { var error = new Error('Could not advertising scanning, state is ' + this.state + ' (not poweredOn)'); if (typeof callback === 'function') { callback(error); } else { throw error; } } else { if (callback) { this.once('advertisingStart', callback); } this._bindings.startAdvertisingWithEIRData(advertisementData, scanData); } }; Bleno.prototype.stopAdvertising = function(callback) { if (callback) { this.once('advertisingStop', callback); } this._bindings.stopAdvertising(); }; Bleno.prototype.onAdvertisingStop = function() { debug('advertisingStop'); this.emit('advertisingStop'); }; Bleno.prototype.setServices = function(services, callback) { if (callback) { this.once('servicesSet', callback); } this._bindings.setServices(services); }; Bleno.prototype.onServicesSet = function(error) { debug('servicesSet'); if (error) { this.emit('servicesSetError', error); } this.emit('servicesSet', error); }; Bleno.prototype.disconnect = function() { debug('disconnect'); this._bindings.disconnect(); }; Bleno.prototype.updateRssi = function(callback) { if (callback) { this.once('rssiUpdate', function(rssi) { callback(null, rssi); }); } this._bindings.updateRssi(); }; Bleno.prototype.onRssiUpdate = function(rssi) { this.emit('rssiUpdate', rssi); }; module.exports = new Bleno(); iotjs-1.0+715/src/js/ble_characteristic.js000066400000000000000000000111551371177304000203730ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var events = require('events'); var util = require('util'); var debug = console.log; // require('debug')('ble_characteristic'); var uuidUtil = require('ble_uuid_util'); function Characteristic(options) { this.uuid = uuidUtil.removeDashes(options.uuid); this.properties = options.properties || []; this.secure = options.secure || []; this.value = options.value || null; this.descriptors = options.descriptors || []; if (this.value && (this.properties.length !== 1 || this.properties[0] !== 'read')) { throw new Error('Characteristics with value can be read only!'); } if (options.onReadRequest) { this.onReadRequest = options.onReadRequest; } if (options.onWriteRequest) { this.onWriteRequest = options.onWriteRequest; } if (options.onSubscribe) { this.onSubscribe = options.onSubscribe; } if (options.onUnsubscribe) { this.onUnsubscribe = options.onUnsubscribe; } if (options.onNotify) { this.onNotify = options.onNotify; } if (options.onIndicate) { this.onIndicate = options.onIndicate; } this.on('readRequest', this.onReadRequest.bind(this)); this.on('writeRequest', this.onWriteRequest.bind(this)); this.on('subscribe', this.onSubscribe.bind(this)); this.on('unsubscribe', this.onUnsubscribe.bind(this)); this.on('notify', this.onNotify.bind(this)); this.on('indicate', this.onIndicate.bind(this)); } util.inherits(Characteristic, events.EventEmitter); Characteristic.RESULT_SUCCESS = Characteristic.prototype.RESULT_SUCCESS = 0x00; Characteristic.RESULT_INVALID_OFFSET = Characteristic.prototype.RESULT_INVALID_OFFSET = 0x07; Characteristic.RESULT_ATTR_NOT_LONG = Characteristic.prototype.RESULT_ATTR_NOT_LONG = 0x0b; Characteristic.RESULT_INVALID_ATTRIBUTE_LENGTH = Characteristic.prototype.RESULT_INVALID_ATTRIBUTE_LENGTH = 0x0d; Characteristic.RESULT_UNLIKELY_ERROR = Characteristic.prototype.RESULT_UNLIKELY_ERROR = 0x0e; Characteristic.prototype.toString = function() { return JSON.stringify({ uuid: this.uuid, properties: this.properties, secure: this.secure, value: this.value, descriptors: this.descriptors }); }; Characteristic.prototype.onReadRequest = function(offset, callback) { callback(this.RESULT_UNLIKELY_ERROR, null); }; Characteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) { callback(this.RESULT_UNLIKELY_ERROR); }; Characteristic.prototype.onSubscribe = function(maxValueSize, updateValueCallback) { this.maxValueSize = maxValueSize; this.updateValueCallback = updateValueCallback; }; Characteristic.prototype.onUnsubscribe = function() { this.maxValueSize = null; this.updateValueCallback = null; }; Characteristic.prototype.onNotify = function() { }; Characteristic.prototype.onIndicate = function() { }; module.exports = Characteristic; iotjs-1.0+715/src/js/ble_descriptor.js000066400000000000000000000042661371177304000175660ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var debug = console.log; // require('debug')('descriptor'); var uuidUtil = require('ble_uuid_util'); function Descriptor(options) { this.uuid = uuidUtil.removeDashes(options.uuid); this.value = options.value || new Buffer(0); } Descriptor.prototype.toString = function() { return JSON.stringify({ uuid: this.uuid, value: Buffer.isBuffer(this.value) ? this.value.toString('hex') : this.value }); }; module.exports = Descriptor; iotjs-1.0+715/src/js/ble_hci_socket.js000066400000000000000000000040351371177304000175150ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var events = require('events'); inherits(native /* BluetoothHciSocket */, events.EventEmitter); // extend prototype function inherits(target, source) { for (var k in source.prototype) { target.prototype[k] = source.prototype[k]; } } module.exports = native; /* BluetoothHciSocket */ iotjs-1.0+715/src/js/ble_hci_socket_acl_stream.js000066400000000000000000000054131371177304000217100ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var debug = console.log; // require('debug')('acl-att-stream'); var events = require('events'); var util = require('util'); var crypto = require('ble_hci_socket_crypto'); var Smp = require('ble_hci_socket_smp'); var AclStream = function(hci, handle, localAddressType, localAddress, remoteAddressType, remoteAddress) { this._hci = hci; this._handle = handle; this.encypted = false; this._smp = new Smp(this, localAddressType, localAddress, remoteAddressType, remoteAddress); }; util.inherits(AclStream, events.EventEmitter); AclStream.prototype.write = function(cid, data) { this._hci.writeAclDataPkt(this._handle, cid, data); }; AclStream.prototype.push = function(cid, data) { if (data) { this.emit('data', cid, data); } else { this.emit('end'); } }; AclStream.prototype.pushEncrypt = function(encrypt) { this.encrypted = encrypt ? true : false; this.emit('encryptChange', this.encrypted); }; AclStream.prototype.pushLtkNegReply = function() { this.emit('ltkNegReply'); }; module.exports = AclStream; iotjs-1.0+715/src/js/ble_hci_socket_bindings.js000066400000000000000000000174301371177304000213750ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var debug = console.log; // require('debug')('ble_hci-socket_bindings'); var events = require('events'); var util = require('util'); var AclStream = require('ble_hci_socket_acl_stream'); var Hci = require('ble_hci_socket_hci'); var Gap = require('ble_hci_socket_gap'); var Gatt = require('ble_hci_socket_gatt'); var BlenoBindings = function() { this._state = null; this._advertising = false; this._hci = new Hci(); this._gap = new Gap(this._hci); this._gatt = new Gatt(this._hci); this._address = null; this._handle = null; this._aclStream = null; }; util.inherits(BlenoBindings, events.EventEmitter); BlenoBindings.prototype.startAdvertising = function(name, serviceUuids) { this._advertising = true; this._gap.startAdvertising(name, serviceUuids); }; BlenoBindings.prototype.startAdvertisingIBeacon = function(data) { this._advertising = true; this._gap.startAdvertisingIBeacon(data); }; BlenoBindings.prototype.startAdvertisingWithEIRData = function(advertisementData, scanData) { this._advertising = true; this._gap.startAdvertisingWithEIRData(advertisementData, scanData); }; BlenoBindings.prototype.stopAdvertising = function() { this._advertising = false; this._gap.stopAdvertising(); }; BlenoBindings.prototype.setServices = function(services) { this._gatt.setServices(services); this.emit('servicesSet'); }; BlenoBindings.prototype.disconnect = function() { if (this._handle) { debug('disconnect by server'); this._hci.disconnect(this._handle); } }; BlenoBindings.prototype.updateRssi = function() { if (this._handle) { this._hci.readRssi(this._handle); } }; BlenoBindings.prototype.init = function() { this.onSigIntBinded = this.onSigInt.bind(this); process.on('SIGINT', this.onSigIntBinded); process.on('exit', this.onExit.bind(this)); this._gap.on('advertisingStart', this.onAdvertisingStart.bind(this)); this._gap.on('advertisingStop', this.onAdvertisingStop.bind(this)); this._gatt.on('mtuChange', this.onMtuChange.bind(this)); this._hci.on('stateChange', this.onStateChange.bind(this)); this._hci.on('addressChange', this.onAddressChange.bind(this)); this._hci.on('readLocalVersion', this.onReadLocalVersion.bind(this)); this._hci.on('leConnComplete', this.onLeConnComplete.bind(this)); this._hci.on('leConnUpdateComplete', this.onLeConnUpdateComplete.bind(this)); this._hci.on('rssiRead', this.onRssiRead.bind(this)); this._hci.on('disconnComplete', this.onDisconnComplete.bind(this)); this._hci.on('encryptChange', this.onEncryptChange.bind(this)); this._hci.on('leLtkNegReply', this.onLeLtkNegReply.bind(this)); this._hci.on('aclDataPkt', this.onAclDataPkt.bind(this)); this.emit('platform', process.platform); this._hci.init(); }; BlenoBindings.prototype.onStateChange = function(state) { if (this._state === state) { return; } this._state = state; if (state === 'unauthorized') { console.log('bleno warning: adapter state unauthorized, please run as root or with sudo'); console.log(' or see README for information on running without root/sudo:'); console.log(' https://github.com/sandeepmistry/bleno#running-on-linux'); } else if (state === 'unsupported') { console.log('bleno warning: adapter does not support Bluetooth Low Energy (BLE, Bluetooth Smart).'); console.log(' Try to run with environment variable:'); console.log(' [sudo] BLENO_HCI_DEVICE_ID=x node ...'); } this.emit('stateChange', state); }; BlenoBindings.prototype.onAddressChange = function(address) { this.emit('addressChange', address); }; BlenoBindings.prototype.onReadLocalVersion = function(hciVer, hciRev, lmpVer, manufacturer, lmpSubVer) { if (manufacturer === 93) { // Realtek Semiconductor Corporation this._gatt.maxMtu = 23; } }; BlenoBindings.prototype.onAdvertisingStart = function(error) { this.emit('advertisingStart', error); }; BlenoBindings.prototype.onAdvertisingStop = function() { this.emit('advertisingStop'); }; BlenoBindings.prototype.onLeConnComplete = function(status, handle, role, addressType, address, interval, latency, supervisionTimeout, masterClockAccuracy) { if (role !== 1) { // not slave, ignore return; } this._address = address; this._handle = handle; this._aclStream = new AclStream(this._hci, handle, this._hci.addressType, this._hci.address, addressType, address); this._gatt.setAclStream(this._aclStream); this.emit('accept', address); }; BlenoBindings.prototype.onLeConnUpdateComplete = function(handle, interval, latency, supervisionTimeout) { // no-op }; BlenoBindings.prototype.onDisconnComplete = function(handle, reason) { if (this._aclStream) { this._aclStream.push(null, null); } var address = this._address; this._address = null; this._handle = null; this._aclStream = null; if (address) { this.emit('disconnect', address); // TODO: use reason } if (this._advertising) { this._gap.restartAdvertising(); } }; BlenoBindings.prototype.onEncryptChange = function(handle, encrypt) { if (this._handle === handle && this._aclStream) { this._aclStream.pushEncrypt(encrypt); } }; BlenoBindings.prototype.onLeLtkNegReply = function(handle) { if (this._handle === handle && this._aclStream) { this._aclStream.pushLtkNegReply(); } }; BlenoBindings.prototype.onMtuChange = function(mtu) { this.emit('mtuChange', mtu); }; BlenoBindings.prototype.onRssiRead = function(handle, rssi) { this.emit('rssiUpdate', rssi); }; BlenoBindings.prototype.onAclDataPkt = function(handle, cid, data) { if (this._handle === handle && this._aclStream) { this._aclStream.push(cid, data); } }; BlenoBindings.prototype.onSigInt = function() { var sigIntListeners = process.listeners('SIGINT'); if (sigIntListeners[sigIntListeners.length - 1] === this.onSigIntBinded) { // we are the last listener, so exit // this will trigger onExit, and clean up process.exit(1); } }; BlenoBindings.prototype.onExit = function() { this._gap.stopAdvertising(); this.disconnect(); }; module.exports = new BlenoBindings(); iotjs-1.0+715/src/js/ble_hci_socket_crypto.js000066400000000000000000000057651371177304000211300ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var crypto = require('ble_hci_socket_crypto'); function r() { return crypto.randomBytes(16); } function c1(k, r, pres, preq, iat, ia, rat, ra) { var p1 = Buffer.concat([ iat, rat, preq, pres ]); var p2 = Buffer.concat([ ra, ia, new Buffer('00000000', 'hex') ]); var res = xor(r, p1); res = e(k, res); res = xor(res, p2); res = e(k, res); return res; } function s1(k, r1, r2) { return e(k, Buffer.concat([ r2.slice(0, 8), r1.slice(0, 8) ])); } function e(key, data) { key = swap(key); data = swap(data); var cipher = crypto.createCipheriv('aes-128-ecb', key, ''); cipher.setAutoPadding(false); return swap(Buffer.concat([ cipher.update(data), cipher.final() ])); } function xor(b1, b2) { var result = new Buffer(b1.length); for (var i = 0; i < b1.length; i++) { //result[i] = b1[i] ^ b2[i]; result.writeUInt8(b1.readUInt8(i) ^ b2.readUInt8(i), i); } return result; } function swap(input) { var output = new Buffer(input.length); for (var i = 0; i < output.length; i++) { //output[i] = input[input.length - i - 1]; output.writeUInt8(input.readUInt8(input.length - i - 1), i); } return output; } module.exports = { r: r, c1: c1, s1: s1, e: e }; iotjs-1.0+715/src/js/ble_hci_socket_gap.js000066400000000000000000000177431371177304000203560ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var debug = console.log; // require('debug')('gap'); var events = require('events'); var util = require('util'); var Hci = require('ble_hci_socket_hci'); var uuidUtil = require('ble_uuid_util'); var isLinux = (process.platform === 'linux'); var isIntelEdison = false; // isLinux && (os.release().indexOf('edison') !== -1); var isYocto = false; //TODO isLinux && (os.release().indexOf('yocto') !== -1); function Gap(hci) { this._hci = hci; this._advertiseState = null; this._hci.on('error', this.onHciError.bind(this)); this._hci.on('leAdvertisingParametersSet', this.onHciLeAdvertisingParametersSet.bind(this)); this._hci.on('leAdvertisingDataSet', this.onHciLeAdvertisingDataSet.bind(this)); this._hci.on('leScanResponseDataSet', this.onHciLeScanResponseDataSet.bind(this)); this._hci.on('leAdvertiseEnableSet', this.onHciLeAdvertiseEnableSet.bind(this)); } util.inherits(Gap, events.EventEmitter); Gap.prototype.startAdvertising = function(name, serviceUuids) { debug('startAdvertising: name = ' + name + ', serviceUuids = ' + JSON.stringify(serviceUuids, null, 2)); var advertisementDataLength = 3; var scanDataLength = 0; var serviceUuids16bit = []; var serviceUuids128bit = []; var i = 0; if (name && name.length) { scanDataLength += 2 + name.length; } if (serviceUuids && serviceUuids.length) { for (i = 0; i < serviceUuids.length; i++) { var serviceUuid = new Buffer(uuidUtil.reverseByteOrder(serviceUuids[i], ''), 'hex'); if (serviceUuid.length === 2) { serviceUuids16bit.push(serviceUuid); } else if (serviceUuid.length === 16) { serviceUuids128bit.push(serviceUuid); } } } if (serviceUuids16bit.length) { advertisementDataLength += 2 + 2 * serviceUuids16bit.length; } if (serviceUuids128bit.length) { advertisementDataLength += 2 + 16 * serviceUuids128bit.length; } var advertisementData = new Buffer(advertisementDataLength); var scanData = new Buffer(scanDataLength); // flags advertisementData.writeUInt8(2, 0); advertisementData.writeUInt8(0x01, 1); advertisementData.writeUInt8(0x06, 2); var advertisementDataOffset = 3; if (serviceUuids16bit.length) { advertisementData.writeUInt8(1 + 2 * serviceUuids16bit.length, advertisementDataOffset); advertisementDataOffset++; advertisementData.writeUInt8(0x03, advertisementDataOffset); advertisementDataOffset++; for (i = 0; i < serviceUuids16bit.length; i++) { serviceUuids16bit[i].copy(advertisementData, advertisementDataOffset); advertisementDataOffset += serviceUuids16bit[i].length; } } if (serviceUuids128bit.length) { advertisementData.writeUInt8(1 + 16 * serviceUuids128bit.length, advertisementDataOffset); advertisementDataOffset++; advertisementData.writeUInt8(0x06, advertisementDataOffset); advertisementDataOffset++; for (i = 0; i < serviceUuids128bit.length; i++) { serviceUuids128bit[i].copy(advertisementData, advertisementDataOffset); advertisementDataOffset += serviceUuids128bit[i].length; } } // name if (name && name.length) { var nameBuffer = new Buffer(name); scanData.writeUInt8(1 + nameBuffer.length, 0); scanData.writeUInt8(0x08, 1); nameBuffer.copy(scanData, 2); } this.startAdvertisingWithEIRData(advertisementData, scanData); }; Gap.prototype.startAdvertisingIBeacon = function(data) { debug('startAdvertisingIBeacon: data = ' + data.toString('hex')); var dataLength = data.length; var manufacturerDataLength = 4 + dataLength; var advertisementDataLength = 5 + manufacturerDataLength; var scanDataLength = 0; var advertisementData = new Buffer(advertisementDataLength); var scanData = new Buffer(0); // flags advertisementData.writeUInt8(2, 0); advertisementData.writeUInt8(0x01, 1); advertisementData.writeUInt8(0x06, 2); advertisementData.writeUInt8(manufacturerDataLength + 1, 3); advertisementData.writeUInt8(0xff, 4); advertisementData.writeUInt16LE(0x004c, 5); // Apple Company Identifier LE (16 bit) advertisementData.writeUInt8(0x02, 7); // type, 2 => iBeacon advertisementData.writeUInt8(dataLength, 8); data.copy(advertisementData, 9); this.startAdvertisingWithEIRData(advertisementData, scanData); }; Gap.prototype.startAdvertisingWithEIRData = function(advertisementData, scanData) { advertisementData = advertisementData || new Buffer(0); scanData = scanData || new Buffer(0); debug('startAdvertisingWithEIRData: advertisement data = ' + advertisementData.toString('hex') + ', scan data = ' + scanData.toString('hex')); var error = null; if (advertisementData.length > 31) { error = new Error('Advertisement data is over maximum limit of 31 bytes'); } else if (scanData.length > 31) { error = new Error('Scan data is over maximum limit of 31 bytes'); } if (error) { this.emit('advertisingStart', error); } else { this._advertiseState = 'starting'; if (isIntelEdison || isYocto) { // work around for Intel Edison debug('skipping first set of scan response and advertisement data'); } else { this._hci.setScanResponseData(scanData); this._hci.setAdvertisingData(advertisementData); } this._hci.setAdvertiseEnable(true); this._hci.setScanResponseData(scanData); this._hci.setAdvertisingData(advertisementData); } }; Gap.prototype.restartAdvertising = function() { this._advertiseState = 'restarting'; this._hci.setAdvertiseEnable(true); }; Gap.prototype.stopAdvertising = function() { this._advertiseState = 'stopping'; this._hci.setAdvertiseEnable(false); }; Gap.prototype.onHciError = function(error) { }; Gap.prototype.onHciLeAdvertisingParametersSet = function(status) { }; Gap.prototype.onHciLeAdvertisingDataSet = function(status) { }; Gap.prototype.onHciLeScanResponseDataSet = function(status) { }; Gap.prototype.onHciLeAdvertiseEnableSet = function(status) { if (this._advertiseState === 'starting') { this._advertiseState = 'started'; var error = null; if (status) { error = new Error(Hci.STATUS_MAPPER[status] || ('Unknown (' + status + ')')); } this.emit('advertisingStart', error); } else if (this._advertiseState === 'stopping') { this._advertiseState = 'stopped'; this.emit('advertisingStop'); } }; module.exports = Gap; iotjs-1.0+715/src/js/ble_hci_socket_gatt.js000066400000000000000000001025611371177304000205370ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ /*jshint loopfunc: true */ var debug = console.log; // require('debug')('ble_hci_socket_gatt'); var events = require('events'); var util = require('util'); var uuidUtil = require('ble_uuid_util'); var ATT_OP_ERROR = 0x01; var ATT_OP_MTU_REQ = 0x02; var ATT_OP_MTU_RESP = 0x03; var ATT_OP_FIND_INFO_REQ = 0x04; var ATT_OP_FIND_INFO_RESP = 0x05; var ATT_OP_FIND_BY_TYPE_REQ = 0x06; var ATT_OP_FIND_BY_TYPE_RESP = 0x07; var ATT_OP_READ_BY_TYPE_REQ = 0x08; var ATT_OP_READ_BY_TYPE_RESP = 0x09; var ATT_OP_READ_REQ = 0x0a; var ATT_OP_READ_RESP = 0x0b; var ATT_OP_READ_BLOB_REQ = 0x0c; var ATT_OP_READ_BLOB_RESP = 0x0d; var ATT_OP_READ_MULTI_REQ = 0x0e; var ATT_OP_READ_MULTI_RESP = 0x0f; var ATT_OP_READ_BY_GROUP_REQ = 0x10; var ATT_OP_READ_BY_GROUP_RESP = 0x11; var ATT_OP_WRITE_REQ = 0x12; var ATT_OP_WRITE_RESP = 0x13; var ATT_OP_WRITE_CMD = 0x52; var ATT_OP_PREP_WRITE_REQ = 0x16; var ATT_OP_PREP_WRITE_RESP = 0x17; var ATT_OP_EXEC_WRITE_REQ = 0x18; var ATT_OP_EXEC_WRITE_RESP = 0x19; var ATT_OP_HANDLE_NOTIFY = 0x1b; var ATT_OP_HANDLE_IND = 0x1d; var ATT_OP_HANDLE_CNF = 0x1e; var ATT_OP_SIGNED_WRITE_CMD = 0xd2; var GATT_PRIM_SVC_UUID = 0x2800; var GATT_INCLUDE_UUID = 0x2802; var GATT_CHARAC_UUID = 0x2803; var GATT_CLIENT_CHARAC_CFG_UUID = 0x2902; var GATT_SERVER_CHARAC_CFG_UUID = 0x2903; var ATT_ECODE_SUCCESS = 0x00; var ATT_ECODE_INVALID_HANDLE = 0x01; var ATT_ECODE_READ_NOT_PERM = 0x02; var ATT_ECODE_WRITE_NOT_PERM = 0x03; var ATT_ECODE_INVALID_PDU = 0x04; var ATT_ECODE_AUTHENTICATION = 0x05; var ATT_ECODE_REQ_NOT_SUPP = 0x06; var ATT_ECODE_INVALID_OFFSET = 0x07; var ATT_ECODE_AUTHORIZATION = 0x08; var ATT_ECODE_PREP_QUEUE_FULL = 0x09; var ATT_ECODE_ATTR_NOT_FOUND = 0x0a; var ATT_ECODE_ATTR_NOT_LONG = 0x0b; var ATT_ECODE_INSUFF_ENCR_KEY_SIZE = 0x0c; var ATT_ECODE_INVAL_ATTR_VALUE_LEN = 0x0d; var ATT_ECODE_UNLIKELY = 0x0e; var ATT_ECODE_INSUFF_ENC = 0x0f; var ATT_ECODE_UNSUPP_GRP_TYPE = 0x10; var ATT_ECODE_INSUFF_RESOURCES = 0x11; var ATT_CID = 0x0004; var Gatt = function() { this.maxMtu = 256; this._mtu = 23; this._preparedWriteRequest = null; this.setServices([]); this.onAclStreamDataBinded = this.onAclStreamData.bind(this); this.onAclStreamEndBinded = this.onAclStreamEnd.bind(this); }; util.inherits(Gatt, events.EventEmitter); Gatt.prototype.setServices = function(services) { var deviceName = process.env.BLENO_DEVICE_NAME || process.platform; // base services and characteristics var allServices = [ { uuid: '1800', characteristics: [ { uuid: '2a00', properties: ['read'], secure: [], value: new Buffer(deviceName), descriptors: [] }, { uuid: '2a01', properties: ['read'], secure: [], value: new Buffer([0x80, 0x00]), descriptors: [] } ] }, { uuid: '1801', characteristics: [ { uuid: '2a05', properties: ['indicate'], secure: [], value: new Buffer([0x00, 0x00, 0x00, 0x00]), descriptors: [] } ] } ].concat(services); this._handles = []; var handle = 0; var i; var j; for (i = 0; i < allServices.length; i++) { var service = allServices[i]; handle++; var serviceHandle = handle; this._handles[serviceHandle] = { type: 'service', uuid: service.uuid, attribute: service, startHandle: serviceHandle // endHandle filled in below }; for (j = 0; j < service.characteristics.length; j++) { var characteristic = service.characteristics[j]; var properties = 0; var secure = 0; if (characteristic.properties.indexOf('read') !== -1) { properties |= 0x02; if (characteristic.secure.indexOf('read') !== -1) { secure |= 0x02; } } if (characteristic.properties.indexOf('writeWithoutResponse') !== -1) { properties |= 0x04; if (characteristic.secure.indexOf('writeWithoutResponse') !== -1) { secure |= 0x04; } } if (characteristic.properties.indexOf('write') !== -1) { properties |= 0x08; if (characteristic.secure.indexOf('write') !== -1) { secure |= 0x08; } } if (characteristic.properties.indexOf('notify') !== -1) { properties |= 0x10; if (characteristic.secure.indexOf('notify') !== -1) { secure |= 0x10; } } if (characteristic.properties.indexOf('indicate') !== -1) { properties |= 0x20; if (characteristic.secure.indexOf('indicate') !== -1) { secure |= 0x20; } } handle++; var characteristicHandle = handle; handle++; var characteristicValueHandle = handle; this._handles[characteristicHandle] = { type: 'characteristic', uuid: characteristic.uuid, properties: properties, secure: secure, attribute: characteristic, startHandle: characteristicHandle, valueHandle: characteristicValueHandle }; this._handles[characteristicValueHandle] = { type: 'characteristicValue', handle: characteristicValueHandle, value: characteristic.value }; if (properties & 0x30) { // notify or indicate // add client characteristic configuration descriptor handle++; var clientCharacteristicConfigurationDescriptorHandle = handle; this._handles[clientCharacteristicConfigurationDescriptorHandle] = { type: 'descriptor', handle: clientCharacteristicConfigurationDescriptorHandle, uuid: '2902', attribute: characteristic, properties: (0x02 | 0x04 | 0x08), // read/write secure: (secure & 0x10) ? (0x02 | 0x04 | 0x08) : 0, value: new Buffer([0x00, 0x00]) }; } for (var k = 0; k < characteristic.descriptors.length; k++) { var descriptor = characteristic.descriptors[k]; handle++; var descriptorHandle = handle; this._handles[descriptorHandle] = { type: 'descriptor', handle: descriptorHandle, uuid: descriptor.uuid, attribute: descriptor, properties: 0x02, // read only secure: 0x00, value: descriptor.value }; } } this._handles[serviceHandle].endHandle = handle; } var debugHandles = []; for (i = 0; i < this._handles.length; i++) { handle = this._handles[i]; debugHandles[i] = {}; for(j in handle) { if (Buffer.isBuffer(handle[j])) { debugHandles[i][j] = handle[j] ? 'Buffer(\'' + handle[j].toString('hex') + '\', \'hex\')' : null; } else if (j !== 'attribute') { debugHandles[i][j] = handle[j]; } } } debug('handles = ' + JSON.stringify(debugHandles, null, 2)); }; Gatt.prototype.setAclStream = function(aclStream) { this._mtu = 23; this._preparedWriteRequest = null; this._aclStream = aclStream; this._aclStream.on('data', this.onAclStreamDataBinded); this._aclStream.on('end', this.onAclStreamEndBinded); }; Gatt.prototype.onAclStreamData = function(cid, data) { if (cid !== ATT_CID) { return; } this.handleRequest(data); }; Gatt.prototype.onAclStreamEnd = function() { this._aclStream.removeListener('data', this.onAclStreamDataBinded); this._aclStream.removeListener('end', this.onAclStreamEndBinded); }; Gatt.prototype.send = function(data) { debug('send: ' + data.toString('hex')); this._aclStream.write(ATT_CID, data); }; Gatt.prototype.errorResponse = function(opcode, handle, status) { var buf = new Buffer(5); buf.writeUInt8(ATT_OP_ERROR, 0); buf.writeUInt8(opcode, 1); buf.writeUInt16LE(handle, 2); buf.writeUInt8(status, 4); return buf; }; Gatt.prototype.handleRequest = function(request) { debug('handing request: ' + request.toString('hex')); var requestType = request.readUInt8(0); //buf[0]; var response = null; switch(requestType) { case ATT_OP_MTU_REQ: response = this.handleMtuRequest(request); break; case ATT_OP_FIND_INFO_REQ: response = this.handleFindInfoRequest(request); break; case ATT_OP_FIND_BY_TYPE_REQ: response = this.handleFindByTypeRequest(request); break; case ATT_OP_READ_BY_TYPE_REQ: response = this.handleReadByTypeRequest(request); break; case ATT_OP_READ_REQ: case ATT_OP_READ_BLOB_REQ: response = this.handleReadOrReadBlobRequest(request); break; case ATT_OP_READ_BY_GROUP_REQ: response = this.handleReadByGroupRequest(request); break; case ATT_OP_WRITE_REQ: case ATT_OP_WRITE_CMD: response = this.handleWriteRequestOrCommand(request); break; case ATT_OP_PREP_WRITE_REQ: response = this.handlePrepareWriteRequest(request); break; case ATT_OP_EXEC_WRITE_REQ: response = this.handleExecuteWriteRequest(request); break; case ATT_OP_HANDLE_CNF: response = this.handleConfirmation(request); break; default: case ATT_OP_READ_MULTI_REQ: case ATT_OP_SIGNED_WRITE_CMD: response = this.errorResponse(requestType, 0x0000, ATT_ECODE_REQ_NOT_SUPP); break; } if (response) { debug('response: ' + response.toString('hex')); this.send(response); } }; Gatt.prototype.handleMtuRequest = function(request) { var mtu = request.readUInt16LE(1); if (mtu < 23) { mtu = 23; } else if (mtu > this.maxMtu) { mtu = this.maxMtu; } this._mtu = mtu; this.emit('mtuChange', this._mtu); var response = new Buffer(3); response.writeUInt8(ATT_OP_MTU_RESP, 0); response.writeUInt16LE(mtu, 1); return response; }; Gatt.prototype.handleFindInfoRequest = function(request) { var response = null; var startHandle = request.readUInt16LE(1); var endHandle = request.readUInt16LE(3); var infos = []; var uuid = null; for (i = startHandle; i <= endHandle; i++) { var handle = this._handles[i]; if (!handle) { break; } uuid = null; if ('service' === handle.type) { uuid = '2800'; } else if ('includedService' === handle.type) { uuid = '2802'; } else if ('characteristic' === handle.type) { uuid = '2803'; } else if ('characteristicValue' === handle.type) { uuid = this._handles[i - 1].uuid; } else if ('descriptor' === handle.type) { uuid = handle.uuid; } if (uuid) { infos.push({ handle: i, uuid: uuid }); } } if (infos.length) { var uuidSize = infos[0].uuid.length / 2; var numInfo = 1; for (i = 1; i < infos.length; i++) { if (infos[0].uuid.length !== infos[i].uuid.length) { break; } numInfo++; } var lengthPerInfo = (uuidSize === 2) ? 4 : 18; var maxInfo = Math.floor((this._mtu - 2) / lengthPerInfo); numInfo = Math.min(numInfo, maxInfo); response = new Buffer(2 + numInfo * lengthPerInfo); //response[0] = ATT_OP_FIND_INFO_RESP; //response[1] = (uuidSize === 2) ? 0x01 : 0x2; response.writeUInt8(ATT_OP_FIND_INFO_RESP, 0); response.writeUInt8((uuidSize === 2) ? 0x01 : 0x2, 1); for (i = 0; i < numInfo; i++) { var info = infos[i]; response.writeUInt16LE(info.handle, 2 + i * lengthPerInfo); uuid = new Buffer(uuidUtil.reverseByteOrder(info.uuid, ''), 'hex'); for (var j = 0; j < uuid.length; j++) { //response[2 + i * lengthPerInfo + 2 + j] = uuid[j]; response.writeUInt8(uuid[j], 2 + i * lengthPerInfo + 2 + j); } } } else { response = this.errorResponse(ATT_OP_FIND_INFO_REQ, startHandle, ATT_ECODE_ATTR_NOT_FOUND); } return response; }; Gatt.prototype.handleFindByTypeRequest = function(request) { var response = null; var startHandle = request.readUInt16LE(1); var endHandle = request.readUInt16LE(3); var uuid = uuidUtil.reverseByteOrder(request.slice(5, 7).toString('hex'), ''); var value = uuidUtil.reverseByteOrder(request.slice(7).toString('hex'), ''); var handles = []; var handle; for (var i = startHandle; i <= endHandle; i++) { handle = this._handles[i]; if (!handle) { break; } if ('2800' === uuid && handle.type === 'service' && handle.uuid === value) { handles.push({ start: handle.startHandle, end: handle.endHandle }); } } if (handles.length) { var lengthPerHandle = 4; var numHandles = handles.length; var maxHandles = Math.floor((this._mtu - 1) / lengthPerHandle); numHandles = Math.min(numHandles, maxHandles); response = new Buffer(1 + numHandles * lengthPerHandle); //response[0] = ATT_OP_FIND_BY_TYPE_RESP; response.writeUInt8(ATT_OP_FIND_BY_TYPE_RESP, 0); for (i = 0; i < numHandles; i++) { handle = handles[i]; response.writeUInt16LE(handle.start, 1 + i * lengthPerHandle); response.writeUInt16LE(handle.end, 1 + i * lengthPerHandle + 2); } } else { response = this.errorResponse(ATT_OP_FIND_BY_TYPE_REQ, startHandle, ATT_ECODE_ATTR_NOT_FOUND); } return response; }; Gatt.prototype.handleReadByGroupRequest = function(request) { var response = null; var startHandle = request.readUInt16LE(1); var endHandle = request.readUInt16LE(3); var uuid = uuidUtil.reverseByteOrder(request.slice(5).toString('hex'), ''); debug('read by group: startHandle = 0x' + startHandle.toString(16) + ', endHandle = 0x' + endHandle.toString(16) + ', uuid = 0x' + uuid.toString(16)); if ('2800' === uuid || '2802' === uuid) { var services = []; var type = ('2800' === uuid) ? 'service' : 'includedService'; var i; for (i = startHandle; i <= endHandle; i++) { var handle = this._handles[i]; if (!handle) { break; } if (handle.type === type) { services.push(handle); } } if (services.length) { var uuidSize = services[0].uuid.length / 2; var numServices = 1; for (i = 1; i < services.length; i++) { if (services[0].uuid.length !== services[i].uuid.length) { break; } numServices++; } var lengthPerService = (uuidSize === 2) ? 6 : 20; var maxServices = Math.floor((this._mtu - 2) / lengthPerService); numServices = Math.min(numServices, maxServices); response = new Buffer(2 + numServices * lengthPerService); //response[0] = ATT_OP_READ_BY_GROUP_RESP; //response[1] = lengthPerService; response.writeUInt8(ATT_OP_READ_BY_GROUP_RESP, 0); response.writeUInt8(lengthPerService, 1); for (i = 0; i < numServices; i++) { var service = services[i]; response.writeUInt16LE(service.startHandle, 2 + i * lengthPerService); response.writeUInt16LE(service.endHandle, 2 + i * lengthPerService + 2); var serviceUuid = new Buffer(uuidUtil.reverseByteOrder(service.uuid, ''), 'hex'); for (var j = 0; j < serviceUuid.length; j++) { //response[2 + i * lengthPerService + 4 + j] = serviceUuid[j]; response.writeUInt8(serviceUuid.readUInt8(j), 2 + i * lengthPerService + 4 + j); } } } else { response = this.errorResponse(ATT_OP_READ_BY_GROUP_REQ, startHandle, ATT_ECODE_ATTR_NOT_FOUND); } } else { response = this.errorResponse(ATT_OP_READ_BY_GROUP_REQ, startHandle, ATT_ECODE_UNSUPP_GRP_TYPE); } return response; }; Gatt.prototype.handleReadByTypeRequest = function(request) { var response = null; var startHandle = request.readUInt16LE(1); var endHandle = request.readUInt16LE(3); var uuid = uuidUtil.reverseByteOrder(request.slice(5).toString('hex'), ''); var i; var handle; debug('read by type: startHandle = 0x' + startHandle.toString(16) + ', endHandle = 0x' + endHandle.toString(16) + ', uuid = 0x' + uuid.toString(16)); if ('2803' === uuid) { var characteristics = []; for (i = startHandle; i <= endHandle; i++) { handle = this._handles[i]; if (!handle) { break; } if (handle.type === 'characteristic') { characteristics.push(handle); } } if (characteristics.length) { var uuidSize = characteristics[0].uuid.length / 2; var numCharacteristics = 1; for (i = 1; i < characteristics.length; i++) { if (characteristics[0].uuid.length !== characteristics[i].uuid.length) { break; } numCharacteristics++; } var lengthPerCharacteristic = (uuidSize === 2) ? 7 : 21; var maxCharacteristics = Math.floor((this._mtu - 2) / lengthPerCharacteristic); numCharacteristics = Math.min(numCharacteristics, maxCharacteristics); response = new Buffer(2 + numCharacteristics * lengthPerCharacteristic); //response[0] = ATT_OP_READ_BY_TYPE_RESP; //response[1] = lengthPerCharacteristic; response.writeUInt8(ATT_OP_READ_BY_TYPE_RESP, 0); response.writeUInt8(lengthPerCharacteristic, 1); for (i = 0; i < numCharacteristics; i++) { var characteristic = characteristics[i]; response.writeUInt16LE(characteristic.startHandle, 2 + i * lengthPerCharacteristic); response.writeUInt8(characteristic.properties, 2 + i * lengthPerCharacteristic + 2); response.writeUInt16LE(characteristic.valueHandle, 2 + i * lengthPerCharacteristic + 3); var characteristicUuid = new Buffer(uuidUtil.reverseByteOrder(characteristic.uuid, ''), 'hex'); for (var j = 0; j < characteristicUuid.length; j++) { //response[2 + i * lengthPerCharacteristic + 5 + j] = characteristicUuid[j]; response.writeUInt8(characteristicUuid.readUInt8(j), 2 + i * lengthPerCharacteristic + 5 + j); } } } else { response = this.errorResponse(ATT_OP_READ_BY_TYPE_REQ, startHandle, ATT_ECODE_ATTR_NOT_FOUND); } } else { var handleAttribute = null; var valueHandle = null; var secure = false; for (i = startHandle; i <= endHandle; i++) { handle = this._handles[i]; if (!handle) { break; } if (handle.type === 'characteristic' && handle.uuid === uuid) { handleAttribute = handle.attribute; valueHandle = handle.valueHandle; secure = handle.secure & 0x02; break; } else if (handle.type === 'descriptor' && handle.uuid === uuid) { valueHandle = i; secure = handle.secure & 0x02; break; } } if (secure && !this._aclStream.encrypted) { response = this.errorResponse(ATT_OP_READ_BY_TYPE_REQ, startHandle, ATT_ECODE_AUTHENTICATION); } else if (valueHandle) { var callback = (function(valueHandle) { return function(result, data) { var callbackResponse = null; if (ATT_ECODE_SUCCESS === result) { var dataLength = Math.min(data.length, this._mtu - 4); callbackResponse = new Buffer(4 + dataLength); //callbackResponse[0] = ATT_OP_READ_BY_TYPE_RESP; //callbackResponse[1] = dataLength + 2; callbackResponse.writeUInt8(ATT_OP_READ_BY_TYPE_RESP, 0); callbackResponse.writeUInt8(dataLength + 2, 1); callbackResponse.writeUInt16LE(valueHandle, 2); for (i = 0; i < dataLength; i++) { //callbackResponse[4 + i] = data[i]; callbackResponse.writeUInt8(data.readUInt8(i), 4 + i); } } else { callbackResponse = this.errorResponse(requestType, valueHandle, result); } debug('read by type response: ' + callbackResponse.toString('hex')); this.send(callbackResponse); }.bind(this); }.bind(this))(valueHandle); var data = this._handles[valueHandle].value; if (data) { callback(ATT_ECODE_SUCCESS, data); } else if (handleAttribute) { handleAttribute.emit('readRequest', 0, callback); } else { callback(ATT_ECODE_UNLIKELY); } } else { response = this.errorResponse(ATT_OP_READ_BY_TYPE_REQ, startHandle, ATT_ECODE_ATTR_NOT_FOUND); } } return response; }; Gatt.prototype.handleReadOrReadBlobRequest = function(request) { var response = null; //var requestType = request[0]; var requestType = request.readUInt8(0); var valueHandle = request.readUInt16LE(1); var offset = (requestType === ATT_OP_READ_BLOB_REQ) ? request.readUInt16LE(3) : 0; var handle = this._handles[valueHandle]; if (handle) { var result = null; var data = null; var handleType = handle.type; var callback = (function(requestType, valueHandle) { return function(result, data) { var callbackResponse = null; if (ATT_ECODE_SUCCESS === result) { var dataLength = Math.min(data.length, this._mtu - 1); callbackResponse = new Buffer(1 + dataLength); //callbackResponse[0] = (requestType === ATT_OP_READ_BLOB_REQ) ? ATT_OP_READ_BLOB_RESP : ATT_OP_READ_RESP; callbackResponse.writeUInt8((requestType === ATT_OP_READ_BLOB_REQ) ? ATT_OP_READ_BLOB_RESP : ATT_OP_READ_RESP, 0); for (i = 0; i < dataLength; i++) { //callbackResponse[1 + i] = data[i]; callbackResponse.writeUInt8(data.readUInt8(i), 1 + i); } } else { callbackResponse = this.errorResponse(requestType, valueHandle, result); } debug('read response: ' + callbackResponse.toString('hex')); this.send(callbackResponse); }.bind(this); }.bind(this))(requestType, valueHandle); if (handleType === 'service' || handleType === 'includedService') { result = ATT_ECODE_SUCCESS; data = new Buffer(uuidUtil.reverseByteOrder(handle.uuid, ''), 'hex'); } else if (handleType === 'characteristic') { var uuid = new Buffer(uuidUtil.reverseByteOrder(handle.uuid, ''), 'hex'); result = ATT_ECODE_SUCCESS; data = new Buffer(3 + uuid.length); data.writeUInt8(handle.properties, 0); data.writeUInt16LE(handle.valueHandle, 1); for (i = 0; i < uuid.length; i++) { //data[i + 3] = uuid[i]; data.writeUInt8(uuid.readUInt8(i), i + 3); } } else if (handleType === 'characteristicValue' || handleType === 'descriptor') { var handleProperties = handle.properties; var handleSecure = handle.secure; var handleAttribute = handle.attribute; if (handleType === 'characteristicValue') { handleProperties = this._handles[valueHandle - 1].properties; handleSecure = this._handles[valueHandle - 1].secure; handleAttribute = this._handles[valueHandle - 1].attribute; } if (handleProperties & 0x02) { if (handleSecure & 0x02 && !this._aclStream.encrypted) { result = ATT_ECODE_AUTHENTICATION; } else { data = handle.value; if (data) { result = ATT_ECODE_SUCCESS; } else { handleAttribute.emit('readRequest', offset, callback); } } } else { result = ATT_ECODE_READ_NOT_PERM; // non-readable } } if (data && typeof data === 'string') { data = new Buffer(data); } if (result === ATT_ECODE_SUCCESS && data && offset) { if (data.length < offset) { errorCode = ATT_ECODE_INVALID_OFFSET; data = null; } else { data = data.slice(offset); } } if (result !== null) { callback(result, data); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_INVALID_HANDLE); } return response; }; Gatt.prototype.handleWriteRequestOrCommand = function(request) { var response = null; //var requestType = request[0]; var requestType = request.readUInt8(0); var withoutResponse = (requestType === ATT_OP_WRITE_CMD); var valueHandle = request.readUInt16LE(1); var data = request.slice(3); var offset = 0; var handle = this._handles[valueHandle]; if (handle) { if (handle.type === 'characteristicValue') { handle = this._handles[valueHandle - 1]; } var handleProperties = handle.properties; var handleSecure = handle.secure; if (handleProperties && (withoutResponse ? (handleProperties & 0x04) : (handleProperties & 0x08))) { var callback = (function(requestType, valueHandle, withoutResponse) { return function(result) { if (!withoutResponse) { var callbackResponse = null; if (ATT_ECODE_SUCCESS === result) { callbackResponse = new Buffer([ATT_OP_WRITE_RESP]); } else { callbackResponse = this.errorResponse(requestType, valueHandle, result); } debug('write response: ' + callbackResponse.toString('hex')); this.send(callbackResponse); } }.bind(this); }.bind(this))(requestType, valueHandle, withoutResponse); if (handleSecure & (withoutResponse ? 0x04 : 0x08) && !this._aclStream.encrypted) { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_AUTHENTICATION); } else if (handle.type === 'descriptor' || handle.uuid === '2902') { var result = null; if (data.length !== 2) { result = ATT_ECODE_INVAL_ATTR_VALUE_LEN; } else { var value = data.readUInt16LE(0); var handleAttribute = handle.attribute; handle.value = data; if (value & 0x0003) { var updateValueCallback = (function(valueHandle, attribute) { return function(data) { var dataLength = Math.min(data.length, this._mtu - 3); var useNotify = attribute.properties.indexOf('notify') !== -1; var useIndicate = attribute.properties.indexOf('indicate') !== -1; var i; if (useNotify) { var notifyMessage = new Buffer(3 + dataLength); notifyMessage.writeUInt8(ATT_OP_HANDLE_NOTIFY, 0); notifyMessage.writeUInt16LE(valueHandle, 1); for (i = 0; i < dataLength; i++) { //notifyMessage[3 + i] = data[i]; notifyMessage.writeUInt8(data.readUInt8(i), 3 + i); } debug('notify message: ' + notifyMessage.toString('hex')); this.send(notifyMessage); attribute.emit('notify'); } else if (useIndicate) { var indicateMessage = new Buffer(3 + dataLength); indicateMessage.writeUInt8(ATT_OP_HANDLE_IND, 0); indicateMessage.writeUInt16LE(valueHandle, 1); for (i = 0; i < dataLength; i++) { //indicateMessage[3 + i] = data[i]; indicateMessage.writeUInt8(data.readUInt8(i), 3 + i); } this._lastIndicatedAttribute = attribute; debug('indicate message: ' + indicateMessage.toString('hex')); this.send(indicateMessage); } }.bind(this); }.bind(this))(valueHandle - 1, handleAttribute); if (handleAttribute.emit) { handleAttribute.emit('subscribe', this._mtu - 3, updateValueCallback); } } else { handleAttribute.emit('unsubscribe'); } result = ATT_ECODE_SUCCESS; } callback(result); } else { handle.attribute.emit('writeRequest', data, offset, withoutResponse, callback); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_WRITE_NOT_PERM); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_INVALID_HANDLE); } return response; }; Gatt.prototype.handlePrepareWriteRequest = function(request) { var response = null; //var requestType = request[0]; var requestType = request.readUInt8(0); var valueHandle = request.readUInt16LE(1); var offset = request.readUInt16LE(3); var data = request.slice(5); var handle = this._handles[valueHandle]; if (handle) { if (handle.type === 'characteristicValue') { handle = this._handles[valueHandle - 1]; var handleProperties = handle.properties; var handleSecure = handle.secure; if (handleProperties && (handleProperties & 0x08)) { if ((handleSecure & 0x08) && !this._aclStream.encrypted) { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_AUTHENTICATION); } else if (this._preparedWriteRequest) { if (this._preparedWriteRequest.handle !== handle) { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_UNLIKELY); } else if (offset === (this._preparedWriteRequest.offset + this._preparedWriteRequest.data.length)) { this._preparedWriteRequest.data = Buffer.concat([ this._preparedWriteRequest.data, data ]); response = new Buffer(request.length); request.copy(response); //response[0] = ATT_OP_PREP_WRITE_RESP; response.writeUInt8(ATT_OP_PREP_WRITE_RESP, 0); } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_INVALID_OFFSET); } } else { this._preparedWriteRequest = { handle: handle, valueHandle: valueHandle, offset: offset, data: data }; response = new Buffer(request.length); request.copy(response); // response[0] = ATT_OP_PREP_WRITE_RESP; response.writeUInt8(ATT_OP_PREP_WRITE_RESP, 0); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_WRITE_NOT_PERM); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_ATTR_NOT_LONG); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_INVALID_HANDLE); } return response; }; Gatt.prototype.handleExecuteWriteRequest = function(request) { var response = null; //var requestType = request[0]; //var flag = request[1]; var requestType = request.readUInt8(0); var flag = request.readUInt8(1); if (this._preparedWriteRequest) { var valueHandle = this._preparedWriteRequest.valueHandle; if (flag === 0x00) { response = new Buffer([ATT_OP_EXEC_WRITE_RESP]); } else if (flag === 0x01) { var callback = (function(requestType, valueHandle) { return function(result) { var callbackResponse = null; if (ATT_ECODE_SUCCESS === result) { callbackResponse = new Buffer([ATT_OP_EXEC_WRITE_RESP]); } else { callbackResponse = this.errorResponse(requestType, valueHandle, result); } debug('execute write response: ' + callbackResponse.toString('hex')); this.send(callbackResponse); }.bind(this); }.bind(this))(requestType, this._preparedWriteRequest.valueHandle); this._preparedWriteRequest.handle.attribute.emit('writeRequest', this._preparedWriteRequest.data, this._preparedWriteRequest.offset, false, callback); } else { response = this.errorResponse(requestType, 0x0000, ATT_ECODE_UNLIKELY); } this._preparedWriteRequest = null; } else { response = this.errorResponse(requestType, 0x0000, ATT_ECODE_UNLIKELY); } return response; }; Gatt.prototype.handleConfirmation = function(request) { if (this._lastIndicatedAttribute) { if (this._lastIndicatedAttribute.emit) { this._lastIndicatedAttribute.emit('indicate'); } this._lastIndicatedAttribute = null; } }; module.exports = Gatt; iotjs-1.0+715/src/js/ble_hci_socket_hci.js000066400000000000000000000452041371177304000203430ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var debug = console.log; // require('debug')('ble_hci'); var events = require('events'); var util = require('util'); var uuidUtil = require('ble_uuid_util'); var BluetoothHciSocket = require('ble_hci_socket'); var HCI_COMMAND_PKT = 0x01; var HCI_ACLDATA_PKT = 0x02; var HCI_EVENT_PKT = 0x04; var ACL_START_NO_FLUSH = 0x00; var ACL_CONT = 0x01; var ACL_START = 0x02; var EVT_DISCONN_COMPLETE = 0x05; var EVT_ENCRYPT_CHANGE = 0x08; var EVT_CMD_COMPLETE = 0x0e; var EVT_CMD_STATUS = 0x0f; var EVT_LE_META_EVENT = 0x3e; var EVT_LE_CONN_COMPLETE = 0x01; var EVT_LE_CONN_UPDATE_COMPLETE = 0x03; var OGF_LINK_CTL = 0x01; var OCF_DISCONNECT = 0x0006; var OGF_HOST_CTL = 0x03; var OCF_SET_EVENT_MASK = 0x0001; var OCF_RESET = 0x0003; var OCF_READ_LE_HOST_SUPPORTED = 0x006c; var OCF_WRITE_LE_HOST_SUPPORTED = 0x006d; var OGF_INFO_PARAM = 0x04; var OCF_READ_LOCAL_VERSION = 0x0001; var OCF_READ_BD_ADDR = 0x0009; var OGF_STATUS_PARAM = 0x05; var OCF_READ_RSSI = 0x0005; var OGF_LE_CTL = 0x08; var OCF_LE_SET_EVENT_MASK = 0x0001; var OCF_LE_SET_ADVERTISING_PARAMETERS = 0x0006; var OCF_LE_SET_ADVERTISING_DATA = 0x0008; var OCF_LE_SET_SCAN_RESPONSE_DATA = 0x0009; var OCF_LE_SET_ADVERTISE_ENABLE = 0x000a; var OCF_LE_LTK_NEG_REPLY = 0x001B; var DISCONNECT_CMD = OCF_DISCONNECT | OGF_LINK_CTL << 10; var SET_EVENT_MASK_CMD = OCF_SET_EVENT_MASK | OGF_HOST_CTL << 10; var RESET_CMD = OCF_RESET | OGF_HOST_CTL << 10; var READ_LE_HOST_SUPPORTED_CMD = OCF_READ_LE_HOST_SUPPORTED | OGF_HOST_CTL << 10; var WRITE_LE_HOST_SUPPORTED_CMD = OCF_WRITE_LE_HOST_SUPPORTED | OGF_HOST_CTL << 10; var READ_LOCAL_VERSION_CMD = OCF_READ_LOCAL_VERSION | (OGF_INFO_PARAM << 10); var READ_BD_ADDR_CMD = OCF_READ_BD_ADDR | (OGF_INFO_PARAM << 10); var READ_RSSI_CMD = OCF_READ_RSSI | OGF_STATUS_PARAM << 10; var LE_SET_EVENT_MASK_CMD = OCF_LE_SET_EVENT_MASK | OGF_LE_CTL << 10; var LE_SET_ADVERTISING_PARAMETERS_CMD = OCF_LE_SET_ADVERTISING_PARAMETERS | OGF_LE_CTL << 10; var LE_SET_ADVERTISING_DATA_CMD = OCF_LE_SET_ADVERTISING_DATA | OGF_LE_CTL << 10; var LE_SET_SCAN_RESPONSE_DATA_CMD = OCF_LE_SET_SCAN_RESPONSE_DATA | OGF_LE_CTL << 10; var LE_SET_ADVERTISE_ENABLE_CMD = OCF_LE_SET_ADVERTISE_ENABLE | OGF_LE_CTL << 10; var LE_LTK_NEG_REPLY_CMD = OCF_LE_LTK_NEG_REPLY | OGF_LE_CTL << 10; var HCI_OE_USER_ENDED_CONNECTION = 0x13; var STATUS_MAPPER = require('ble_hci_socket_hci_status'); var Hci = function() { this._socket = new BluetoothHciSocket(); this._isDevUp = null; this._state = null; this._deviceId = null; this._handleBuffers = {}; this.on('stateChange', this.onStateChange.bind(this)); }; util.inherits(Hci, events.EventEmitter); Hci.STATUS_MAPPER = STATUS_MAPPER; Hci.prototype.init = function() { this._socket.on('data', this.onSocketData.bind(this)); this._socket.on('error', this.onSocketError.bind(this)); var deviceId = process.env.BLENO_HCI_DEVICE_ID ? parseInt(process.env.BLENO_HCI_DEVICE_ID) : undefined; if (process.env.HCI_CHANNEL_USER) { this._deviceId = this._socket.bindUser(deviceId); this._socket.start(); this.reset(); } else { this._deviceId = this._socket.bindRaw(deviceId); this._socket.start(); this.pollIsDevUp(); } }; Hci.prototype.pollIsDevUp = function() { var isDevUp = this._socket.isDevUp(); if (this._isDevUp !== isDevUp) { if (isDevUp) { this.setSocketFilter(); this.setEventMask(); this.setLeEventMask(); this.readLocalVersion(); this.writeLeHostSupported(); this.readLeHostSupported(); this.readBdAddr(); } else { this.emit('stateChange', 'poweredOff'); } this._isDevUp = isDevUp; } setTimeout(this.pollIsDevUp.bind(this), 1000); }; Hci.prototype.setSocketFilter = function() { var filter = new Buffer(14); var typeMask = (1 << HCI_EVENT_PKT)| (1 << HCI_ACLDATA_PKT); var eventMask1 = (1 << EVT_DISCONN_COMPLETE) | (1 << EVT_ENCRYPT_CHANGE) | (1 << EVT_CMD_COMPLETE) | (1 << EVT_CMD_STATUS); var eventMask2 = (1 << (EVT_LE_META_EVENT - 32)); var opcode = 0; filter.writeUInt32LE(typeMask, 0); filter.writeUInt32LE(eventMask1, 4); filter.writeUInt32LE(eventMask2, 8); filter.writeUInt16LE(opcode, 12); debug('setting filter to: ' + filter.toString('hex')); this._socket.setFilter(filter); }; Hci.prototype.setEventMask = function() { var cmd = new Buffer(12); var eventMask = new Buffer('fffffbff07f8bf3d', 'hex'); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(SET_EVENT_MASK_CMD, 1); // length cmd.writeUInt8(eventMask.length, 3); eventMask.copy(cmd, 4); debug('set event mask - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.reset = function() { var cmd = new Buffer(4); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(OCF_RESET | OGF_HOST_CTL << 10, 1); // length cmd.writeUInt8(0x00, 3); debug('reset - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.readLeHostSupported = function() { var cmd = new Buffer(4); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(READ_LE_HOST_SUPPORTED_CMD, 1); // length cmd.writeUInt8(0x00, 3); debug('read LE host supported - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.writeLeHostSupported = function() { var cmd = new Buffer(6); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(WRITE_LE_HOST_SUPPORTED_CMD, 1); // length cmd.writeUInt8(0x02, 3); // data cmd.writeUInt8(0x01, 4); // le cmd.writeUInt8(0x00, 5); // simul debug('write LE host supported - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.readLocalVersion = function() { var cmd = new Buffer(4); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(READ_LOCAL_VERSION_CMD, 1); // length cmd.writeUInt8(0x0, 3); debug('read local version - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.readBdAddr = function() { var cmd = new Buffer(4); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(READ_BD_ADDR_CMD, 1); // length cmd.writeUInt8(0x0, 3); debug('read bd addr - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.setLeEventMask = function() { var cmd = new Buffer(12); var leEventMask = new Buffer('1f00000000000000', 'hex'); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(LE_SET_EVENT_MASK_CMD, 1); // length cmd.writeUInt8(leEventMask.length, 3); leEventMask.copy(cmd, 4); debug('set le event mask - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.setAdvertisingParameters = function() { var cmd = new Buffer(19); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(LE_SET_ADVERTISING_PARAMETERS_CMD, 1); // length cmd.writeUInt8(15, 3); var advertisementInterval = Math.floor((process.env.BLENO_ADVERTISING_INTERVAL ? parseInt(process.env.BLENO_ADVERTISING_INTERVAL) : 100) * '1.6'); // data cmd.writeUInt16LE(advertisementInterval, 4); // min interval cmd.writeUInt16LE(advertisementInterval, 6); // max interval cmd.writeUInt8(0x00, 8); // adv type cmd.writeUInt8(0x00, 9); // own addr typ cmd.writeUInt8(0x00, 10); // direct addr type (new Buffer('000000000000', 'hex')).copy(cmd, 11); // direct addr cmd.writeUInt8(0x07, 17); cmd.writeUInt8(0x00, 18); debug('set advertisement parameters - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.setAdvertisingData = function(data) { var cmd = new Buffer(36); cmd.fill(0x00); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(LE_SET_ADVERTISING_DATA_CMD, 1); // length cmd.writeUInt8(32, 3); // data cmd.writeUInt8(data.length, 4); data.copy(cmd, 5); debug('set advertisement data - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.setScanResponseData = function(data) { var cmd = new Buffer(36); cmd.fill(0x00); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(LE_SET_SCAN_RESPONSE_DATA_CMD, 1); // length cmd.writeUInt8(32, 3); // data cmd.writeUInt8(data.length, 4); data.copy(cmd, 5); debug('set scan response data - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.setAdvertiseEnable = function(enabled) { var cmd = new Buffer(5); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(LE_SET_ADVERTISE_ENABLE_CMD, 1); // length cmd.writeUInt8(0x01, 3); // data cmd.writeUInt8(enabled ? 0x01 : 0x00, 4); // enable: 0 -> disabled, 1 -> enabled debug('set advertise enable - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.disconnect = function(handle, reason) { var cmd = new Buffer(7); reason = reason || HCI_OE_USER_ENDED_CONNECTION; // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(DISCONNECT_CMD, 1); // length cmd.writeUInt8(0x03, 3); // data cmd.writeUInt16LE(handle, 4); // handle cmd.writeUInt8(reason, 6); // reason debug('disconnect - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.readRssi = function(handle) { var cmd = new Buffer(6); // header cmd.writeUInt8(HCI_COMMAND_PKT, 0); cmd.writeUInt16LE(READ_RSSI_CMD, 1); // length cmd.writeUInt8(0x02, 3); // data cmd.writeUInt16LE(handle, 4); // handle debug('read rssi - writing: ' + cmd.toString('hex')); this._socket.write(cmd); }; Hci.prototype.writeAclDataPkt = function(handle, cid, data) { var pkt = new Buffer(9 + data.length); // header pkt.writeUInt8(HCI_ACLDATA_PKT, 0); pkt.writeUInt16LE(handle | ACL_START_NO_FLUSH << 12, 1); pkt.writeUInt16LE(data.length + 4, 3); // data length 1 pkt.writeUInt16LE(data.length, 5); // data length 2 pkt.writeUInt16LE(cid, 7); data.copy(pkt, 9); debug('write acl data pkt - writing: ' + pkt.toString('hex')); this._socket.write(pkt); }; Hci.prototype.onSocketData = function(data) { debug('onSocketData: ' + data.toString('hex')); var eventType = data.readUInt8(0); var handle; debug('\tevent type = ' + eventType); if (HCI_EVENT_PKT === eventType) { var subEventType = data.readUInt8(1); debug('\tsub event type = ' + subEventType); if (subEventType === EVT_DISCONN_COMPLETE) { handle = data.readUInt16LE(4); var reason = data.readUInt8(6); debug('\t\thandle = ' + handle); debug('\t\treason = ' + reason); this.emit('disconnComplete', handle, reason); } else if (subEventType === EVT_ENCRYPT_CHANGE) { handle = data.readUInt16LE(4); var encrypt = data.readUInt8(6); debug('\t\thandle = ' + handle); debug('\t\tencrypt = ' + encrypt); this.emit('encryptChange', handle, encrypt); } else if (subEventType === EVT_CMD_COMPLETE) { var cmd = data.readUInt16LE(4); var status = data.readUInt8(6); var result = data.slice(7); debug('\t\tcmd = ' + cmd); debug('\t\tstatus = ' + status); debug('\t\tresult = ' + result.toString('hex')); this.processCmdCompleteEvent(cmd, status, result); } else if (subEventType === EVT_LE_META_EVENT) { var leMetaEventType = data.readUInt8(3); var leMetaEventStatus = data.readUInt8(4); var leMetaEventData = data.slice(5); debug('\t\tLE meta event type = ' + leMetaEventType); debug('\t\tLE meta event status = ' + leMetaEventStatus); debug('\t\tLE meta event data = ' + leMetaEventData.toString('hex')); this.processLeMetaEvent(leMetaEventType, leMetaEventStatus, leMetaEventData); } } else if (HCI_ACLDATA_PKT === eventType) { var flags = data.readUInt16LE(1) >> 12; handle = data.readUInt16LE(1) & 0x0fff; if (ACL_START === flags) { var cid = data.readUInt16LE(7); var length = data.readUInt16LE(5); var pktData = data.slice(9); debug('\t\tcid = ' + cid); if (length === pktData.length) { debug('\t\thandle = ' + handle); debug('\t\tdata = ' + pktData.toString('hex')); this.emit('aclDataPkt', handle, cid, pktData); } else { this._handleBuffers[handle] = { length: length, cid: cid, data: pktData }; } } else if (ACL_CONT === flags) { if (!this._handleBuffers[handle] || !this._handleBuffers[handle].data) { return; } this._handleBuffers[handle].data = Buffer.concat([ this._handleBuffers[handle].data, data.slice(5) ]); if (this._handleBuffers[handle].data.length === this._handleBuffers[handle].length) { this.emit('aclDataPkt', handle, this._handleBuffers[handle].cid, this._handleBuffers[handle].data); delete this._handleBuffers[handle]; } } } }; Hci.prototype.onSocketError = function(error) { debug('onSocketError: ' + error.message); if (error.message === 'Operation not permitted') { this.emit('stateChange', 'unauthorized'); } else if (error.message === 'Network is down') { // no-op } }; Hci.prototype.processCmdCompleteEvent = function(cmd, status, result) { var handle; if (cmd === RESET_CMD) { this.setEventMask(); this.setLeEventMask(); this.readLocalVersion(); this.writeLeHostSupported(); this.readLeHostSupported(); this.readBdAddr(); } else if (cmd === READ_LE_HOST_SUPPORTED_CMD) { if (status === 0) { var le = result.readUInt8(0); var simul = result.readUInt8(1); debug('\t\t\tle = ' + le); debug('\t\t\tsimul = ' + simul); } } else if (cmd === READ_LOCAL_VERSION_CMD) { var hciVer = result.readUInt8(0); var hciRev = result.readUInt16LE(1); var lmpVer = result.readInt8(3); var manufacturer = result.readUInt16LE(4); var lmpSubVer = result.readUInt16LE(6); if (hciVer < 0x06) { this.emit('stateChange', 'unsupported'); } else if (this._state !== 'poweredOn') { this.setAdvertiseEnable(false); this.setAdvertisingParameters(); } this.emit('readLocalVersion', hciVer, hciRev, lmpVer, manufacturer, lmpSubVer); } else if (cmd === READ_BD_ADDR_CMD) { this.addressType = 'public'; this.address = uuidUtil.reverseByteOrder(result.toString('hex'), ':'); debug('address = ' + this.address); this.emit('addressChange', this.address); } else if (cmd === LE_SET_ADVERTISING_PARAMETERS_CMD) { this.emit('stateChange', 'poweredOn'); this.emit('leAdvertisingParametersSet', status); } else if (cmd === LE_SET_ADVERTISING_DATA_CMD) { this.emit('leAdvertisingDataSet', status); } else if (cmd === LE_SET_SCAN_RESPONSE_DATA_CMD) { this.emit('leScanResponseDataSet', status); } else if (cmd === LE_SET_ADVERTISE_ENABLE_CMD) { this.emit('leAdvertiseEnableSet', status); } else if (cmd === READ_RSSI_CMD) { handle = result.readUInt16LE(0); var rssi = result.readInt8(2); debug('\t\t\thandle = ' + handle); debug('\t\t\trssi = ' + rssi); this.emit('rssiRead', handle, rssi); } else if (cmd === LE_LTK_NEG_REPLY_CMD) { handle = result.readUInt16LE(0); debug('\t\t\thandle = ' + handle); this.emit('leLtkNegReply', handle); } }; Hci.prototype.processLeMetaEvent = function(eventType, status, data) { if (eventType === EVT_LE_CONN_COMPLETE) { this.processLeConnComplete(status, data); } else if (eventType === EVT_LE_CONN_UPDATE_COMPLETE) { this.processLeConnUpdateComplete(status, data); } }; Hci.prototype.processLeConnComplete = function(status, data) { var handle = data.readUInt16LE(0); var role = data.readUInt8(2); var addressType = data.readUInt8(3) === 0x01 ? 'random': 'public'; var address = uuidUtil.reverseByteOrder(data.slice(4, 10).toString('hex'), ':'); var interval = (data.readUInt16LE(10) * 5) >> 2; var latency = data.readUInt16LE(12); // TODO: multiplier? var supervisionTimeout = data.readUInt16LE(14) * 10; var masterClockAccuracy = data.readUInt8(16); // TODO: multiplier? debug('\t\t\thandle = ' + handle); debug('\t\t\trole = ' + role); debug('\t\t\taddress type = ' + addressType); debug('\t\t\taddress = ' + address); debug('\t\t\tinterval = ' + interval); debug('\t\t\tlatency = ' + latency); debug('\t\t\tsupervision timeout = ' + supervisionTimeout); debug('\t\t\tmaster clock accuracy = ' + masterClockAccuracy); this.emit('leConnComplete', status, handle, role, addressType, address, interval, latency, supervisionTimeout, masterClockAccuracy); }; Hci.prototype.processLeConnUpdateComplete = function(status, data) { var handle = data.readUInt16LE(0); var interval = (data.readUInt16LE(2) * 5) >> 2; var latency = data.readUInt16LE(4); // TODO: multiplier? var supervisionTimeout = data.readUInt16LE(6) * 10; debug('\t\t\thandle = ' + handle); debug('\t\t\tinterval = ' + interval); debug('\t\t\tlatency = ' + latency); debug('\t\t\tsupervision timeout = ' + supervisionTimeout); this.emit('leConnUpdateComplete', status, handle, interval, latency, supervisionTimeout); }; Hci.prototype.onStateChange = function(state) { this._state = state; }; module.exports = Hci; iotjs-1.0+715/src/js/ble_hci_socket_hci_status.js000066400000000000000000000077221371177304000217510ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ module.exports = [ "Success", "Unknown HCI Command", "Unknown Connection Identifier", "Hardware Failure", "Page Timeout", "Authentication Failure", "PIN or Key Missing", "Memory Capacity Exceeded", "Connection Timeout", "Connection Limit Exceeded", "Synchronous Connection Limit to a Device Exceeded", "ACL Connection Already Exists", "Command Disallowed", "Connection Rejected due to Limited Resources", "Connection Rejected due to Security Reasons", "Connection Rejected due to Unacceptable BD_ADDR", "Connection Accept Timeout Exceeded", "Unsupported Feature or Parameter Value", "Invalid HCI Command Parameters", "Remote User Terminated Connection", "Remote Device Terminated due to Low Resources", "Remote Device Terminated due to Power Off", "Connection Terminated By Local Host", "Repeated Attempts", "Pairing Not Allowed", "Unknown LMP PDU", "Unsupported Remote Feature / Unsupported LMP Feature", "SCO Offset Rejected", "SCO Interval Rejected", "SCO Air Mode Rejected", "Invalid LMP Parameters / Invalid LL Parameters", "Unspecified Error", "Unsupported LMP Parameter Value / Unsupported LL Parameter Value", "Role Change Not Allowed", "LMP Response Timeout / LL Response Timeout", "LMP Error Transaction Collision", "LMP PDU Not Allowed", "Encryption Mode Not Acceptable", "Link Key cannot be Changed", "Requested QoS Not Supported", "Instant Passed", "Pairing With Unit Key Not Supported", "Different Transaction Collision", "Reserved", "QoS Unacceptable Parameter", "QoS Rejected", "Channel Classification Not Supported", "Insufficient Security", "Parameter Out Of Manadatory Range", "Reserved", "Role Switch Pending", "Reserved", "Reserved Slot Violation", "Role Switch Failed", "Extended Inquiry Response Too Large", "Secure Simple Pairing Not Supported By Host", "Host Busy - Pairing", "Connection Rejected due to No Suitable Channel Found", "Controller Busy", "Unacceptable Connection Parameters" , "Directed Advertising Timeout", "Connection Terminated due to MIC Failure", "Connection Failed to be Established", "MAC Connection Failed", "Coarse Clock Adjustment Rejected but Will Try to Adjust Using Clock Dragging" ]; iotjs-1.0+715/src/js/ble_hci_socket_mgmt.js000066400000000000000000000074521371177304000205470ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var debug = console.log; // require('debug')('ble_mgmt'); var events = require('events'); var util = require('util'); var BluetoothHciSocket = require('ble_hci_socket'); var LTK_INFO_SIZE = 36; var MGMT_OP_LOAD_LONG_TERM_KEYS = 0x0013; function Mgmt() { this._socket = new BluetoothHciSocket(); this._ltkInfos = []; this._socket.on('data', this.onSocketData.bind(this)); this._socket.on('error', this.onSocketError.bind(this)); this._socket.bindControl(); this._socket.start(); } Mgmt.prototype.onSocketData = function(data) { debug('on data ->' + data.toString('hex')); }; Mgmt.prototype.onSocketError = function(error) { debug('on error ->' + error.message); }; Mgmt.prototype.addLongTermKey = function(address, addressType, authenticated, master, ediv, rand, key) { var ltkInfo = new Buffer(LTK_INFO_SIZE); address.copy(ltkInfo, 0); ltkInfo.writeUInt8(addressType.readUInt8(0) + 1, 6); // BDADDR_LE_PUBLIC = 0x01, BDADDR_LE_RANDOM 0x02, so add one ltkInfo.writeUInt8(authenticated, 7); ltkInfo.writeUInt8(master, 8); ltkInfo.writeUInt8(key.length, 9); ediv.copy(ltkInfo, 10); rand.copy(ltkInfo, 12); key.copy(ltkInfo, 20); this._ltkInfos.push(ltkInfo); this.loadLongTermKeys(); }; Mgmt.prototype.clearLongTermKeys = function() { this._ltkInfos = []; this.loadLongTermKeys(); }; Mgmt.prototype.loadLongTermKeys = function() { var numLongTermKeys = this._ltkInfos.length; var op = new Buffer(2 + numLongTermKeys * LTK_INFO_SIZE); op.writeUInt16LE(numLongTermKeys, 0); for (var i = 0; i < numLongTermKeys; i++) { this._ltkInfos[i].copy(op, 2 + i * LTK_INFO_SIZE); } this.write(MGMT_OP_LOAD_LONG_TERM_KEYS, 0, op); }; Mgmt.prototype.write = function(opcode, index, data) { var length = 0; if (data) { length = data.length; } var pkt = new Buffer(6 + length); pkt.writeUInt16LE(opcode, 0); pkt.writeUInt16LE(index, 2); pkt.writeUInt16LE(length, 4); if (length) { data.copy(pkt, 6); } debug('writing -> ' + pkt.toString('hex')); this._socket.write(pkt); }; module.exports = new Mgmt(); iotjs-1.0+715/src/js/ble_hci_socket_smp.js000066400000000000000000000145701371177304000204010ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var debug = console.log; // require('debug')('ble_hci_socket_smp'); var events = require('events'); var util = require('util'); var crypto = require('ble_hci_socket_crypto'); var mgmt = require('ble_hci_socket_mgmt'); var SMP_CID = 0x0006; var SMP_PAIRING_REQUEST = 0x01; var SMP_PAIRING_RESPONSE = 0x02; var SMP_PAIRING_CONFIRM = 0x03; var SMP_PAIRING_RANDOM = 0x04; var SMP_PAIRING_FAILED = 0x05; var SMP_ENCRYPT_INFO = 0x06; var SMP_MASTER_IDENT = 0x07; var SMP_UNSPECIFIED = 0x08; var Smp = function(aclStream, localAddressType, localAddress, remoteAddressType, remoteAddress) { this._aclStream = aclStream; this._iat = new Buffer([(remoteAddressType === 'random') ? 0x01 : 0x00]); this._ia = new Buffer(remoteAddress.split(':').reverse().join(''), 'hex'); this._rat = new Buffer([(localAddressType === 'random') ? 0x01 : 0x00]); this._ra = new Buffer(localAddress.split(':').reverse().join(''), 'hex'); this._stk = null; this._random = null; this._diversifier = null; this.onAclStreamDataBinded = this.onAclStreamData.bind(this); this.onAclStreamEncryptChangeBinded = this.onAclStreamEncryptChange.bind(this); this.onAclStreamLtkNegReplyBinded = this.onAclStreamLtkNegReply.bind(this); this.onAclStreamEndBinded = this.onAclStreamEnd.bind(this); this._aclStream.on('data', this.onAclStreamDataBinded); this._aclStream.on('encryptChange', this.onAclStreamEncryptChangeBinded); this._aclStream.on('ltkNegReply', this.onAclStreamLtkNegReplyBinded); this._aclStream.on('end', this.onAclStreamEndBinded); }; util.inherits(Smp, events.EventEmitter); Smp.prototype.onAclStreamData = function(cid, data) { if (cid !== SMP_CID) { return; } var code = data.readUInt8(0); if (SMP_PAIRING_REQUEST === code) { this.handlePairingRequest(data); } else if (SMP_PAIRING_CONFIRM === code) { this.handlePairingConfirm(data); } else if (SMP_PAIRING_RANDOM === code) { this.handlePairingRandom(data); } else if (SMP_PAIRING_FAILED === code) { this.handlePairingFailed(data); } }; Smp.prototype.onAclStreamEncryptChange = function(encrypted) { if (encrypted) { if (this._stk && this._diversifier && this._random) { this.write(Buffer.concat([ new Buffer([SMP_ENCRYPT_INFO]), this._stk ])); this.write(Buffer.concat([ new Buffer([SMP_MASTER_IDENT]), this._diversifier, this._random ])); } } }; Smp.prototype.onAclStreamLtkNegReply = function() { this.write(new Buffer([ SMP_PAIRING_FAILED, SMP_UNSPECIFIED ])); this.emit('fail'); }; Smp.prototype.onAclStreamEnd = function() { this._aclStream.removeListener('data', this.onAclStreamDataBinded); this._aclStream.removeListener('encryptChange', this.onAclStreamEncryptChangeBinded); this._aclStream.removeListener('ltkNegReply', this.onAclStreamLtkNegReplyBinded); this._aclStream.removeListener('end', this.onAclStreamEndBinded); }; Smp.prototype.handlePairingRequest = function(data) { this._preq = data; this._pres = new Buffer([ SMP_PAIRING_RESPONSE, 0x03, // IO capability: NoInputNoOutput 0x00, // OOB data: Authentication data not present 0x01, // Authentication requirement: Bonding - No MITM 0x10, // Max encryption key size 0x00, // Initiator key distribution: 0x01 // Responder key distribution: EncKey ]); this.write(this._pres); }; Smp.prototype.handlePairingConfirm = function(data) { this._pcnf = data; this._tk = new Buffer('00000000000000000000000000000000', 'hex'); this._r = crypto.r(); this.write(Buffer.concat([ new Buffer([SMP_PAIRING_CONFIRM]), crypto.c1(this._tk, this._r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra) ])); }; Smp.prototype.handlePairingRandom = function(data) { var r = data.slice(1); var pcnf = Buffer.concat([ new Buffer([SMP_PAIRING_CONFIRM]), crypto.c1(this._tk, r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra) ]); if (this._pcnf.toString('hex') === pcnf.toString('hex')) { this._diversifier = new Buffer('0000', 'hex'); this._random = new Buffer('0000000000000000', 'hex'); this._stk = crypto.s1(this._tk, this._r, r); mgmt.addLongTermKey(this._ia, this._iat, 0, 0, this._diversifier, this._random, this._stk); this.write(Buffer.concat([ new Buffer([SMP_PAIRING_RANDOM]), this._r ])); } else { this.write(new Buffer([ SMP_PAIRING_FAILED, SMP_PAIRING_CONFIRM ])); this.emit('fail'); } }; Smp.prototype.handlePairingFailed = function(data) { this.emit('fail'); }; Smp.prototype.write = function(data) { this._aclStream.write(SMP_CID, data); }; module.exports = Smp; iotjs-1.0+715/src/js/ble_primary_service.js000066400000000000000000000044371371177304000206130ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var events = require('events'); var util = require('util'); var debug = console.log; // require('debug')('ble_primary_service'); var uuidUtil = require('ble_uuid_util'); function PrimaryService(options) { this.uuid = uuidUtil.removeDashes(options.uuid); this.characteristics = options.characteristics || []; } util.inherits(PrimaryService, events.EventEmitter); PrimaryService.prototype.toString = function() { return JSON.stringify({ uuid: this.uuid, characteristics: this.characteristics }); }; module.exports = PrimaryService; iotjs-1.0+715/src/js/ble_uuid_util.js000066400000000000000000000043341371177304000174070ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ module.exports.removeDashes = function(uuid) { if (uuid) { uuid = uuid.split('-').join(''); } return uuid; }; module.exports.reverseByteOrder = function(str, joint) { str = String(str); var uuid = ''; var len = str.length; var i = 0; while (i < (len & ~0x1)) { uuid = joint + str.slice(i, i + 2) + uuid; i = i + 2; } if (len & 0x1) uuid = str.slice(i, i + 1) + uuid; else if (joint !== '') uuid = uuid.substring(1, uuid.length); return uuid; } iotjs-1.0+715/src/js/bridge.js000066400000000000000000000020141371177304000160070ustar00rootroot00000000000000/* Copyright 2018-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. */ function Bridge(moduleName) { this.moduleName = moduleName; } Bridge.prototype.send = function(command, message, callback) { native.send(this.moduleName, command, message, function(err, results) { callback(err, results); }); }; Bridge.prototype.sendSync = function(command, message) { return native.send(this.moduleName, command, message); }; module.exports = Bridge; iotjs-1.0+715/src/js/buffer.js000066400000000000000000000241671371177304000160410ustar00rootroot00000000000000/* 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. */ 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'); } function getEncodingType(encoding) { switch (encoding) { case 'hex': return 0; case 'base64': return 1; default: return -1; } } // 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 (!Buffer.isBuffer(this)) { return new Buffer(subject, encoding); } if (typeof subject === 'number') { this.length = subject > 0 ? subject >>> 0 : 0; } else if (typeof subject === 'string') { this.length = Buffer.byteLength(subject, encoding); } else if (Buffer.isBuffer(subject) || Array.isArray(subject)) { this.length = subject.length; } else { throw new TypeError('Bad arguments: Buffer(string|number|Buffer|Array)'); } // 'native' is the buffer object created via the C API. native(this, this.length); if (typeof subject === 'string') { if (typeof encoding === 'string') { encoding = getEncodingType(encoding); if (encoding != -1) { native.writeDecode(this, encoding, subject, 0, this.length); } else { this.write(subject); } } else { this.write(subject); } } else if (Buffer.isBuffer(subject)) { subject.copy(this); } else if (Array.isArray(subject)) { for (var i = 0; i < this.length; ++i) { native.writeUInt8(this, subject[i], i); } } } // Buffer.byteLength(string, encoding) Buffer.byteLength = function(str, encoding) { var bytes = native.byteLength(str); if (typeof encoding === 'string') { /* Might be invalid for incorrectly encoded strings. */ switch (encoding) { case 'hex': return bytes >>> 1; case 'base64': var len = str.length; if (len >= 4 && str.charCodeAt(len - 1) === 0x3D) { len--; if (str.charCodeAt(len - 2) === 0x3D) { len--; } } return len; } } return bytes; }; // Buffer.concat(list) Buffer.concat = function(list) { if (!Array.isArray(list)) { throw new TypeError('Bad arguments: Buffer.concat([Buffer])'); } var length = 0; var i; for (i = 0; i < list.length; ++i) { if (!Buffer.isBuffer(list[i])) { throw new TypeError('Bad arguments: Buffer.concat([Buffer])'); } length += list[i].length; } var buffer = new Buffer(length); var pos = 0; for (i = 0; i < list.length; ++i) { list[i].copy(buffer, pos); pos += list[i].length; } return buffer; }; // Buffer.isBuffer(object) Buffer.isBuffer = function(arg) { return arg instanceof Buffer; }; // buffer.equals(otherBuffer) Buffer.prototype.equals = function(otherBuffer) { if (!Buffer.isBuffer(otherBuffer)) { throw new TypeError('Bad arguments: buffer.equals(Buffer)'); } return native.compare(this, otherBuffer) == 0; }; // buffer.compare(otherBuffer) Buffer.prototype.compare = function(otherBuffer) { if (!Buffer.isBuffer(otherBuffer)) { throw new TypeError('Bad arguments: buffer.compare(Buffer)'); } return native.compare(this, otherBuffer); }; // 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 (!Buffer.isBuffer(target)) { throw new TypeError('Bad arguments: buff.copy(Buffer)'); } targetStart = targetStart === undefined ? 0 : ~~targetStart; sourceStart = sourceStart === undefined ? 0 : ~~sourceStart; sourceEnd = sourceEnd === undefined ? this.length : ~~ sourceEnd; if ((sourceEnd > sourceStart) && (targetStart < 0)) { throw new RangeError('Attempt to write outside buffer bounds'); } return native.copy(this, 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, encoding) { if (typeof string !== 'string') { throw new TypeError('Bad arguments: buff.write(string)'); } offset = offset === undefined ? 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 = length === undefined ? remaining : ~~length; if (typeof encoding === 'string') { encoding = getEncodingType(encoding); if (encoding != -1) { return native.writeDecode(this, encoding, string, offset, length); } } return native.write(this, 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 = start === undefined ? 0 : ~~start; end = end === undefined ? this.length : ~~end; return native.slice(this, start, end); }; // buff.toString([encoding,[,start[, end]]]) // [1] buff.toString() // [2] buff.toString(encoding) // [3] buff.toString(encoding, start) // [4] buff.toString(encoding, start, end) // * start - default to 0 // * end - default to buff.length Buffer.prototype.toString = function(encoding, start, end) { if (typeof encoding === 'string') { encoding = getEncodingType(encoding); } else { encoding = -1; } start = start === undefined ? 0 : ~~start; end = end === undefined ? this.length : ~~end; return native.toString(this, encoding, 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); native.writeUInt8(this, 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); native.writeUInt8(this, value & 0xff, offset); native.writeUInt8(this, (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, -1 >>> 0, 0); native.writeUInt8(this, (value >>> 24) & 0xff, offset + 3); native.writeUInt8(this, (value >>> 16) & 0xff, offset + 2); native.writeUInt8(this, (value >>> 8) & 0xff, offset + 1); native.writeUInt8(this, 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 native.readUInt8(this, 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 = native.readUInt8(this, 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 native.readUInt8(this, offset) | (native.readUInt8(this, offset + 1) << 8); }; // buff.fill(value) Buffer.prototype.fill = function(value) { if (typeof value === 'number') { value = value & 255; for (var i = 0; i < this.length; i++) { native.writeUInt8(this, value, i); } } return this; }; // Method: Buffer.from() // Buffer.from(Array) // Buffer.from(string,encoding) // Buffer.from(Buffer) // Buffer.from(ArrayBuffer) function from(value, encoding, length) { var arrayBuffer = native.fromArrayBuffer(value, encoding, length); if (arrayBuffer) { return arrayBuffer; } if (Buffer.isBuffer(value) || (typeof value) === 'string' || Array.isArray(value)) { return new Buffer(value, encoding); } throw new TypeError('First argument must be' + 'a string, Buffer, ArrayBuffer, Array, or array-like object'); } /* Register the Buffer object back to the native C * so the other side can get the prototype in a consistent * and safe manner. */ native.Buffer = Buffer; module.exports = Buffer; module.exports.Buffer = Buffer; module.exports.from = from; iotjs-1.0+715/src/js/console.js000066400000000000000000000017731371177304000162300ustar00rootroot00000000000000/* 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 util = require('util'); function Console() { } Console.prototype.log = Console.prototype.info = function() { native.stdout(util.format.apply(this, arguments) + '\n'); }; Console.prototype.warn = Console.prototype.error = function() { native.stderr(util.format.apply(this, arguments) + '\n'); }; module.exports = new Console(); module.exports.Console = Console; iotjs-1.0+715/src/js/crypto.js000066400000000000000000000062641371177304000161060ustar00rootroot00000000000000/* Copyright 2018-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 shaTypes = { 'sha1': 4, 'sha256': 6, }; var hashes = ['sha1', 'sha256']; function Verify(signtype) { if (!(this instanceof Verify)) { return new Verify(signtype); } signtype = signtype.toLowerCase(); if (hashes.indexOf(signtype) < 0) { throw new Error('Unknown signing algorithm.' + 'Please use crypto.getSignatures()'); } Object.defineProperty(this, 'hashtype', { // defaults to writable: false, configurable: false value: signtype, enumerable: true, }); } Verify.prototype.update = function(data) { if (this.data) { if (Buffer.isBuffer(data)) { this.data = Buffer.concat([this.data, data]); return; } this.data = Buffer.concat([this.data, new Buffer(data)]); return; } if (Buffer.isBuffer(data)) { this.data = data; return; } this.data = new Buffer(data); }; Verify.prototype.verify = function(publicKey, signature) { if (this.data) { var type = shaTypes[this.hashtype]; var hash = native.shaEncode(this.data, type); return native.rsaVerify(type, hash, publicKey, signature); } throw new Error('verify shouldn\'t be called on an empty Verify'); }; function Hash(hashtype) { if (!(this instanceof Hash)) { return new Hash(hashtype); } if (hashes.indexOf(hashtype) < 0) { throw new Error('Unknown hashing algorithm. Please use crypto.getHashes()'); } Object.defineProperty(this, 'hashtype', { value: hashtype, writable: false, enumerable: true, }); } Hash.prototype.update = function(data) { if (this.data) { if (Buffer.isBuffer(data)) { this.data = Buffer.concat(this.data, data); return; } this.data = Buffer.concat([this.data, new Buffer(data)]); return; } this.data = new Buffer(data); }; Hash.prototype.digest = function(encoding) { if (this._finished) { throw new Error('Digest can not be called twice on the same Hash object'); } var result; var type = shaTypes[this.hashtype]; result = native.shaEncode(this.data, type); if (encoding == 'base64') { result = native.base64Encode(result); } else if (encoding == 'hex') { result = result.toString('hex'); } Object.defineProperty(this, '_finished', { value: true, writable: false, enumerable: false, }); return result; }; function getHashes() { return hashes; } function createHash(hashtype) { return new Hash(hashtype); } function createVerify(signtype) { return new Verify(signtype); } exports.createHash = createHash; exports.getHashes = getHashes; exports.createVerify = createVerify; iotjs-1.0+715/src/js/dgram.js000066400000000000000000000261421371177304000156550ustar00rootroot00000000000000/* 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 EventEmitter = require('events').EventEmitter; var util = require('util'); var Udp = require('udp'); var BIND_STATE_UNBOUND = 0; var BIND_STATE_BINDING = 1; var BIND_STATE_BOUND = 2; // lazily loaded var dns = null; function lookup(address, family, callback) { if (!dns) dns = require('dns'); return dns.lookup(address, family, callback); } function lookup4(address, callback) { return lookup(address || '0.0.0.0', 4, callback); } function newHandle(type) { if (type == 'udp4') { var handle = new Udp(); handle.lookup = lookup4; return handle; } throw new Error('Bad socket type specified. Valid types are: udp4'); } function Socket(type, listener) { EventEmitter.call(this); var options = undefined; if (util.isObject(type)) { options = type; type = options.type; } var handle = newHandle(type); handle.owner = this; this._handle = handle; this._receiving = false; this._bindState = BIND_STATE_UNBOUND; this.type = type; this.fd = null; // compatibility hack // If true - UV_UDP_REUSEADDR flag will be set this._reuseAddr = options && options.reuseAddr; if (util.isFunction(listener)) this.on('message', listener); } util.inherits(Socket, EventEmitter); exports.Socket = Socket; exports.createSocket = function(type, listener) { return new Socket(type, listener); }; function startListening(socket) { socket._handle.onmessage = onMessage; // Todo: handle errors socket._handle.recvStart(); socket._receiving = true; socket._bindState = BIND_STATE_BOUND; socket.fd = -42; // compatibility hack socket.emit('listening'); } Socket.prototype.bind = function(port, address, callback) { var self = this; self._healthCheck(); if (this._bindState != BIND_STATE_UNBOUND) throw new Error('Socket is already bound'); this._bindState = BIND_STATE_BINDING; if (util.isFunction(port)) { callback = port; port = 0; address = ''; } else if (util.isObject(port)) { callback = address; address = port.address || ''; port = port.port; } else if (util.isFunction(address)) { callback = address; address = ''; } if (util.isFunction(callback)) self.once('listening', callback); // defaulting address for bind to all interfaces if (!address && self._handle.lookup === lookup4) { address = '0.0.0.0'; } // resolve address first self._handle.lookup(address, function(err, ip) { if (err) { self._bindState = BIND_STATE_UNBOUND; self.emit('error', err); return; } if (!self._handle) return; // handle has been closed in the mean time self._handle._reuseAddr = self._reuseAddr; err = self._handle.bind(ip, port | 0); if (err) { var ex = util.exceptionWithHostPort(err, 'bind', ip, port); self.emit('error', ex); self._bindState = BIND_STATE_UNBOUND; // Todo: close? return; } startListening(self); }); return self; }; // thin wrapper around `send`, here for compatibility with dgram_legacy.js Socket.prototype.sendto = function(buffer, offset, length, port, address, callback) { if (!(util.isNumber(offset)) || !(util.isNumber(length))) throw new Error('send takes offset and length as args 2 and 3'); if (!(util.isString(address))) throw new Error(this.type + ' sockets must send to port, address'); this.send(buffer, offset, length, port, address, callback); }; function sliceBuffer(buffer, offset, length) { if (util.isString(buffer)) buffer = new Buffer(buffer); else if (!(util.isBuffer(buffer))) throw new TypeError('First argument must be a buffer or string'); offset = offset >>> 0; length = length >>> 0; return buffer.slice(offset, offset + length); } function fixBufferList(list) { var newlist = new Array(list.length); for (var i = 0, l = list.length; i < l; i++) { var buf = list[i]; if (util.isString(buf)) newlist[i] = new Buffer(buf); else if (!(util.isBuffer(buf))) return null; else newlist[i] = buf; } return newlist; } function enqueue(self, toEnqueue) { // If the send queue hasn't been initialized yet, do it, and install an // event handler that flushes the send queue after binding is done. if (!self._queue) { self._queue = []; self.once('listening', clearQueue); } self._queue.push(toEnqueue); return; } function clearQueue() { var queue = this._queue; this._queue = undefined; // Flush the send queue. for (var i = 0; i < queue.length; i++) queue[i](); } // valid combinations // send(buffer, offset, length, port, address, callback) // send(buffer, offset, length, port, address) // send(buffer, offset, length, port) // send(bufferOrList, port, address, callback) // send(bufferOrList, port, address) // send(bufferOrList, port) Socket.prototype.send = function(buffer, offset, length, port, address, callback) { var self = this; var list; if (address || (port && !(util.isFunction(port)))) { buffer = sliceBuffer(buffer, offset, length); } else { callback = port; port = offset; address = length; } if (!util.isArray(buffer)) { if (util.isString(buffer)) { list = [new Buffer(buffer)]; } else if (!util.isBuffer(buffer)) { throw new TypeError('First argument must be a buffer or a string'); } else { list = [buffer]; } } else if (!(list = fixBufferList(buffer))) { throw new TypeError('Buffer list arguments must be buffers or strings'); } port = port >>> 0; if (port === 0 || port > 65535) throw new RangeError('Port should be > 0 and < 65536'); // Normalize callback so it's either a function or undefined but not anything // else. if (!(util.isFunction(callback))) callback = undefined; self._healthCheck(); if (self._bindState === BIND_STATE_UNBOUND) self.bind(0, null); if (list.length === 0) list.push(new Buffer(0)); // If the socket hasn't been bound yet, push the outbound packet onto the // send queue and send after binding is complete. if (self._bindState !== BIND_STATE_BOUND) { enqueue(self, self.send.bind(self, list, port, address, callback)); return; } self._handle.lookup(address, function afterDns(ex, ip) { doSend(ex, self, ip, list, address, port, callback); }); }; function doSend(ex, self, ip, list, address, port, callback) { if (ex) { if (util.isFunction(callback)) { callback(ex); return; } self.emit('error', ex); return; } else if (!self._handle) { return; } var buf = Buffer.concat(list); var err = self._handle.send(buf, port, ip, function(err, length) { if (err) { err = util.exceptionWithHostPort(err, 'send', address, port); } else { err = null; } if (util.isFunction(callback)) { callback(err, length); } }); if (err && callback) { // don't emit as error, dgram_legacy.js compatibility ex = util.exceptionWithHostPort(err, 'send', address, port); process.nextTick(callback, ex); } } Socket.prototype.close = function(callback) { if (util.isFunction(callback)) this.on('close', callback); if (this._queue) { this._queue.push(this.close.bind(this)); return this; } this._healthCheck(); this._stopReceiving(); this._handle.close(); this._handle = null; var self = this; process.nextTick(function() { self.emit('close'); }); return this; }; Socket.prototype.address = function() { this._healthCheck(); var out = {}; var err = this._handle.getsockname(out); if (err) { throw util.errnoException(err, 'getsockname'); } return out; }; // These object represents the different config types that // this._handle.configure can do. // The order of these must match the order in the udp C module. var configTypes = { 'BROADCAST': 0, 'TTL': 1, 'MULTICASTTTL': 2, 'MULTICASTLOOPBACK': 3, }; Socket.prototype.setBroadcast = function(arg) { var err = this._handle.configure(configTypes.BROADCAST, arg ? 1 : 0); if (err) { throw util.errnoException(err, 'setBroadcast'); } }; Socket.prototype.setTTL = function(arg) { if (!(util.isNumber(arg))) { throw new TypeError('Argument must be a number'); } var err = this._handle.configure(configTypes.TTL, arg); if (err) { throw util.errnoException(err, 'setTTL'); } return arg; }; Socket.prototype.setMulticastTTL = function(arg) { if (!(util.isNumber(arg))) { throw new TypeError('Argument must be a number'); } var err = this._handle.configure(configTypes.MULTICASTTTL, arg); if (err) { throw util.errnoException(err, 'setMulticastTTL'); } return arg; }; Socket.prototype.setMulticastLoopback = function(arg) { var err = this._handle.configure(configTypes.MULTICASTLOOPBACK, arg ? 1 : 0); if (err) { throw util.errnoException(err, 'setMulticastLoopback'); } return arg; // 0.4 compatibility }; Socket.prototype.addMembership = function(multicastAddress, interfaceAddress) { this._healthCheck(); if (!multicastAddress) { throw new Error('multicast address must be specified'); } var err = this._handle.addMembership(multicastAddress, interfaceAddress); if (err) { throw util.errnoException(err, 'addMembership'); } }; Socket.prototype.dropMembership = function(multicastAddress, interfaceAddress) { this._healthCheck(); if (!multicastAddress) { throw new Error('multicast address must be specified'); } var err = this._handle.dropMembership(multicastAddress, interfaceAddress); if (err) { throw util.errnoException(err, 'dropMembership'); } }; Socket.prototype._healthCheck = function() { if (!this._handle) throw new Error('Not running'); // error message from dgram_legacy.js }; Socket.prototype._stopReceiving = function() { if (!this._receiving) return; this._handle.recvStop(); this._receiving = false; this.fd = null; // compatibility hack }; function onMessage(nread, handle, buf, rinfo) { var self = handle.owner; if (nread < 0) { return self.emit('error', util.errnoException(nread, 'recvmsg')); } rinfo.size = buf.length; // compatibility self.emit('message', buf, rinfo); } /* TODO: Implement Socket.prototype.ref. Socket.prototype.ref = function() { if (this._handle) this._handle.ref(); return this; }; */ /* TODO: Implement Socket.prototype.unref. Socket.prototype.unref = function() { if (this._handle) this._handle.unref(); return this; }; */ iotjs-1.0+715/src/js/dns.js000066400000000000000000000040251371177304000153430ustar00rootroot00000000000000/* 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 util = require('util'); exports.lookup = function lookup(hostname, options, callback) { var hints = 0; var family = -1; // Parse arguments if (!util.isString(hostname)) { throw TypeError('invalid argument: hostname must be a string'); } if (util.isFunction(options)) { callback = options; family = 0; } else if (!util.isFunction(callback)) { throw TypeError('invalid argument: callback must be passed'); } else if (util.isObject(options)) { hints = options.hints >>> 0; family = options.family >>> 0; if (hints < 0 || hints > (exports.ADDRCONFIG | exports.V4MAPPED)) { throw new TypeError('invalid argument: invalid hints flags'); } } else if (util.isNumber(options)) { family = ~~options; } else { throw TypeError( 'invalid argument: options must be either an object or number'); } if (family !== 0 && family !== 4 && family !== 6) throw new TypeError('invalid argument: family must be 4 or 6'); if (process.platform != 'nuttx') { native.getaddrinfo(hostname, family, hints, callback); } else { // native.getaddrinfo is synchronous on these platforms. // needs to be wrapped into an asynchronous call. process.nextTick(function() { native.getaddrinfo(hostname, family, hints, callback); }); } }; // uv_getaddrinfo flags exports.ADDRCONFIG = native.AI_ADDRCONFIG; exports.V4MAPPED = native.AI_V4MAPPED; iotjs-1.0+715/src/js/events.js000066400000000000000000000057331371177304000160720ustar00rootroot00000000000000/* 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 util = require('util'); function EventEmitter() { this._events = {}; } module.exports = EventEmitter; EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype.emit = function(type) { if (!this._events) { this._events = {}; } // About to emit 'error' event but there are no listeners for it. if (type === 'error' && !this._events.error) { var err = arguments[1]; if (err instanceof Error) { throw err; } else { throw Error('Uncaught \'error\' event'); } } var listeners = this._events[type]; if (util.isArray(listeners)) { listeners = listeners.slice(); var args = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < listeners.length; ++i) { listeners[i].apply(this, args); } return true; } return false; }; EventEmitter.prototype.addListener = function(type, listener) { if (!util.isFunction(listener)) { throw new TypeError('listener must be a function'); } if (!this._events) { this._events = {}; } if (!this._events[type]) { this._events[type] = []; } this._events[type].push(listener); return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!util.isFunction(listener)) { throw new TypeError('listener must be a function'); } var f = function() { // here `this` is this not global, because EventEmitter binds event object // for this when it calls back the handler. this.removeListener(f.type, f); f.listener.apply(this, arguments); }; f.type = type; f.listener = listener; this.on(type, f); return this; }; EventEmitter.prototype.removeListener = function(type, listener) { if (!util.isFunction(listener)) { throw new TypeError('listener must be a function'); } var list = this._events[type]; if (Array.isArray(list)) { for (var i = list.length - 1; i >= 0; --i) { if (list[i] == listener || (list[i].listener && list[i].listener == listener)) { list.splice(i, 1); if (!list.length) { delete this._events[type]; } break; } } } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { if (arguments.length === 0) { this._events = {}; } else { delete this._events[type]; } return this; }; iotjs-1.0+715/src/js/fs.js000066400000000000000000000345351371177304000152000ustar00rootroot00000000000000/* 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 fs = exports; var constants = require('constants'); var util = require('util'); var fsBuiltin = native; fs.exists = function(path, callback) { if (!(util.isString(path)) && !(util.isBuffer(path))) { throw new TypeError('Path should be a string or a buffer'); } if (!path || !path.length) { process.nextTick(function() { if (callback) callback(false); }); return; } var cb = function(err/* , stat */) { if (callback) callback(err ? false : true); }; fsBuiltin.stat(checkArgString(path, 'path'), checkArgFunction(cb, 'callback')); }; fs.existsSync = function(path) { if (!path || !path.length) { return false; } try { fsBuiltin.stat(checkArgString(path, 'path')); return true; } catch (e) { return false; } }; fs.stat = function(path, callback) { fsBuiltin.stat(checkArgString(path, 'path'), checkArgFunction(callback, 'callback')); }; fs.statSync = function(path) { return fsBuiltin.stat(checkArgString(path, 'path')); }; fs.fstat = function(fd, callback) { fsBuiltin.fstat(checkArgNumber(fd, 'fd'), checkArgFunction(callback, 'callback')); }; fs.fstatSync = function(fd) { return fsBuiltin.fstat(checkArgNumber(fd, 'fd')); }; fs.close = function(fd, callback) { fsBuiltin.close(checkArgNumber(fd, 'fd'), checkArgFunction(callback, 'callback')); }; fs.closeSync = function(fd) { fsBuiltin.close(checkArgNumber(fd, 'fd')); }; fs.open = function(path, flags, mode/* , callback */) { fsBuiltin.open(checkArgString(path, 'path'), convertFlags(flags), convertMode(mode, 438), checkArgFunction(arguments[arguments.length - 1]), 'callback'); }; fs.openSync = function(path, flags, mode) { return fsBuiltin.open(checkArgString(path, 'path'), convertFlags(flags), convertMode(mode, 438)); }; fs.read = function(fd, buffer, offset, length, position, callback) { if (util.isNullOrUndefined(position)) { position = -1; // Read from the current position. } callback = checkArgFunction(callback, 'callback'); var cb = function(err, bytesRead) { callback(err, bytesRead || 0, buffer); }; return fsBuiltin.read(checkArgNumber(fd, 'fd'), checkArgBuffer(buffer, 'buffer'), checkArgNumber(offset, 'offset'), checkArgNumber(length, 'length'), checkArgNumber(position, 'position'), cb); }; fs.readSync = function(fd, buffer, offset, length, position) { if (util.isNullOrUndefined(position)) { position = -1; // Read from the current position. } return fsBuiltin.read(checkArgNumber(fd, 'fd'), checkArgBuffer(buffer, 'buffer'), checkArgNumber(offset, 'offset'), checkArgNumber(length, 'length'), checkArgNumber(position, 'position')); }; fs.write = function(fd, buffer, offset, length, position, callback) { if (util.isFunction(position)) { callback = position; position = -1; // write at current position. } else if (util.isNullOrUndefined(position)) { position = -1; // write at current position. } callback = checkArgFunction(callback, 'callback'); var cb = function(err, written) { callback(err, written, buffer); }; return fsBuiltin.write(checkArgNumber(fd, 'fd'), checkArgBuffer(buffer, 'buffer'), checkArgNumber(offset, 'offset'), checkArgNumber(length, 'length'), checkArgNumber(position, 'position'), cb); }; fs.writeSync = function(fd, buffer, offset, length, position) { if (util.isNullOrUndefined(position)) { position = -1; // write at current position. } return fsBuiltin.write(checkArgNumber(fd, 'fd'), checkArgBuffer(buffer, 'buffer'), checkArgNumber(offset, 'offset'), checkArgNumber(length, 'length'), checkArgNumber(position, 'position')); }; fs.readFile = function(path, callback) { checkArgString(path); checkArgFunction(callback); var fd; var buffers; fs.open(path, 'r', function(err, _fd) { if (err) { return callback(err); } fd = _fd; buffers = []; // start read read(); }); var read = function() { // Read segment of data. var buffer = new Buffer(1023); fs.read(fd, buffer, 0, 1023, -1, afterRead); }; var afterRead = function(err, bytesRead, buffer) { if (err) { fs.close(fd, function(err) { return callback(err); }); } if (bytesRead === 0) { // End of file. close(); } else { // continue reading. buffers.push(buffer.slice(0, bytesRead)); read(); } }; var close = function() { fs.close(fd, function(err) { return callback(err, Buffer.concat(buffers)); }); }; }; fs.readFileSync = function(path) { checkArgString(path); var fd = fs.openSync(path, 'r', 438); var buffers = []; while (true) { try { var buffer = new Buffer(1023); var bytesRead = fs.readSync(fd, buffer, 0, 1023); if (bytesRead) { buffers.push(buffer.slice(0, bytesRead)); } else { break; } } catch (e) { break; } } fs.closeSync(fd); return Buffer.concat(buffers); }; fs.writeFile = function(path, data, callback) { checkArgString(path); checkArgFunction(callback); var fd; var len; var bytesWritten; var buffer = ensureBuffer(data); fs.open(path, 'w', function(err, _fd) { if (err) { return callback(err); } fd = _fd; len = buffer.length; bytesWritten = 0; write(); }); var write = function() { var tryN = (len - bytesWritten) >= 1024 ? 1023 : (len - bytesWritten); fs.write(fd, buffer, bytesWritten, tryN, bytesWritten, afterWrite); }; var afterWrite = function(err, n) { if (err) { fs.close(fd, function(err) { return callback(err); }); } if (n <= 0 || bytesWritten + n == len) { // End of buffer fs.close(fd, function(err) { callback(err); }); } else { // continue writing bytesWritten += n; write(); } }; }; fs.writeFileSync = function(path, data) { checkArgString(path); var buffer = ensureBuffer(data); var fd = fs.openSync(path, 'w'); var len = buffer.length; var bytesWritten = 0; while (true) { try { var tryN = (len - bytesWritten) >= 1024 ? 1023 : (len - bytesWritten); var n = fs.writeSync(fd, buffer, bytesWritten, tryN, bytesWritten); bytesWritten += n; if (bytesWritten == len) { break; } } catch (e) { break; } } fs.closeSync(fd); return bytesWritten; }; fs.mkdir = function(path, mode, callback) { if (util.isFunction(mode)) callback = mode; checkArgString(path, 'path'); checkArgFunction(callback, 'callback'); fsBuiltin.mkdir(path, convertMode(mode, 511), callback); }; fs.mkdirSync = function(path, mode) { return fsBuiltin.mkdir(checkArgString(path, 'path'), convertMode(mode, 511)); }; fs.rmdir = function(path, callback) { checkArgString(path, 'path'); checkArgFunction(callback, 'callback'); fsBuiltin.rmdir(path, callback); }; fs.rmdirSync = function(path) { return fsBuiltin.rmdir(checkArgString(path, 'path')); }; fs.unlink = function(path, callback) { checkArgString(path); checkArgFunction(callback); fsBuiltin.unlink(path, callback); }; fs.unlinkSync = function(path) { return fsBuiltin.unlink(checkArgString(path, 'path')); }; fs.rename = function(oldPath, newPath, callback) { checkArgString(oldPath); checkArgString(newPath); checkArgFunction(callback); fsBuiltin.rename(oldPath, newPath, callback); }; fs.renameSync = function(oldPath, newPath) { checkArgString(oldPath); checkArgString(newPath); fsBuiltin.rename(oldPath, newPath); }; fs.readdir = function(path, callback) { checkArgString(path); checkArgFunction(callback); fsBuiltin.readdir(path, callback); }; fs.readdirSync = function(path) { return fsBuiltin.readdir(checkArgString(path, 'path')); }; try { var stream = require('stream'); var Readable = stream.Readable; var Writable = stream.Writable; var ReadStream = function(path, options) { if (!(this instanceof ReadStream)) { return new ReadStream(path, options); } options = options || {}; Readable.call(this, {defaultEncoding: options.encoding || null}); this.bytesRead = 0; this.path = path; this._autoClose = util.isNullOrUndefined(options.autoClose) || options.autoClose; this._fd = options.fd; this._buff = new Buffer(options.bufferSize || 4096); var self = this; if (util.isNullOrUndefined(this._fd)) { fs.open(this.path, options.flags || 'r', options.mode || 438, function(err, _fd) { if (err) { throw err; } self._fd = _fd; self.emit('open', self._fd); self.doRead(); }); } this.once('open', function(/* _fd */) { this.emit('ready'); }); if (this._autoClose) { this.on('end', function() { closeFile(self); }); } }; util.inherits(ReadStream, Readable); ReadStream.prototype.doRead = function() { var self = this; fs.read(this._fd, this._buff, 0, this._buff.length, null, function(err, bytes_read/* , buffer*/) { if (err) { if (self._autoClose) { closeFile(self); } throw err; } self.bytesRead += bytes_read; if (bytes_read === 0) { // Reached end of file. // null must be pushed so the 'end' event will be emitted. self.push(null); } else { self.push(bytes_read == self._buff.length ? self._buff : self._buff.slice(0, bytes_read)); self.doRead(); } }); }; fs.createReadStream = function(path, options) { return new ReadStream(path, options); }; var WriteStream = function(path, options) { if (!(this instanceof WriteStream)) { return new WriteStream(path, options); } options = options || {}; Writable.call(this); this._fd = options._fd; this._autoClose = util.isNullOrUndefined(options.autoClose) || options.autoClose; this.bytesWritten = 0; var self = this; if (!this._fd) { fs.open(path, options.flags || 'w', options.mode || 438, function(err, _fd) { if (err) { throw err; } self._fd = _fd; self.emit('open', self._fd); }); } this.once('open', function(/* _fd */) { self.emit('ready'); }); if (this._autoClose) { this.on('finish', function() { closeFile(self); }); } this._readyToWrite(); }; util.inherits(WriteStream, Writable); WriteStream.prototype._write = function(chunk, callback, onwrite) { var self = this; fs.write(this._fd, chunk, 0, chunk.length, function(err, bytes_written/* , buffer */) { if (err) { if (self._autoClose) { closeFile(self); } throw err; } this.bytesWritten += bytes_written; if (callback) { callback(); } onwrite(); }); }; fs.createWriteStream = function(path, options) { return new WriteStream(path, options); }; var closeFile = function(stream) { fs.close(stream._fd, function(err) { if (err) { throw err; } stream.emit('close'); }); }; } catch (e) { } function convertFlags(flag) { var O_APPEND = constants.O_APPEND; var O_CREAT = constants.O_CREAT; var O_EXCL = constants.O_EXCL; var O_RDONLY = constants.O_RDONLY; var O_RDWR = constants.O_RDWR; var O_SYNC = constants.O_SYNC; var O_TRUNC = constants.O_TRUNC; var O_WRONLY = constants.O_WRONLY; if (util.isString(flag)) { switch (flag) { case 'r': return O_RDONLY; case 'rs': case 'sr': return O_RDONLY | O_SYNC; case 'r+': return O_RDWR; case 'rs+': case 'sr+': return O_RDWR | O_SYNC; case 'w': return O_TRUNC | O_CREAT | O_WRONLY; case 'wx': case 'xw': return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL; case 'w+': return O_TRUNC | O_CREAT | O_RDWR; case 'wx+': case 'xw+': return O_TRUNC | O_CREAT | O_RDWR | O_EXCL; case 'a': return O_APPEND | O_CREAT | O_WRONLY; case 'ax': case 'xa': return O_APPEND | O_CREAT | O_WRONLY | O_EXCL; case 'a+': return O_APPEND | O_CREAT | O_RDWR; case 'ax+': case 'xa+': return O_APPEND | O_CREAT | O_RDWR | O_EXCL; } } throw new TypeError('Bad argument: flags'); } function convertMode(mode, def) { if (util.isNumber(mode)) { return mode; } else if (util.isString(mode)) { return parseInt(mode, 8); } else if (def) { return convertMode(def); } return undefined; } function ensureBuffer(data) { if (util.isBuffer(data)) { return data; } return new Buffer(data + ''); // coert to string and make it a buffer } function checkArgType(value, name, checkFunc) { if (checkFunc(value)) { return value; } else { throw new TypeError('Bad arguments: ' + name); } } function checkArgBuffer(value, name) { return checkArgType(value, name, util.isBuffer); } function checkArgNumber(value, name) { return checkArgType(value, name, util.isNumber); } function checkArgString(value, name) { return checkArgType(value, name, util.isString); } function checkArgFunction(value, name) { return checkArgType(value, name, util.isFunction); } iotjs-1.0+715/src/js/gpio.js000066400000000000000000000017171371177304000155220ustar00rootroot00000000000000/* 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 gpio = { open: function(config, callback) { var gpioPin = new native(config, function(err) { callback(err, gpioPin); }); return gpioPin; }, openSync: function(config) { return new native(config); }, DIRECTION: native.DIRECTION, EDGE: native.EDGE, MODE: native.MODE, }; module.exports = gpio; iotjs-1.0+715/src/js/http.js000066400000000000000000000036631371177304000155450ustar00rootroot00000000000000/* 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 net = require('net'); var ClientRequest = require('http_client').ClientRequest; var IncomingMessage = require('http_incoming').IncomingMessage; var HTTPParser = require('http_parser').HTTPParser; var HTTPServer = require('http_server'); var util = require('util'); exports.ClientRequest = ClientRequest; exports.request = function(options, cb) { // Create socket. var socket = new net.Socket(); options.port = options.port || 80; return new ClientRequest(options, cb, socket); }; function Server(options, requestListener) { if (!(this instanceof Server)) { return new Server(options, requestListener); } net.Server.call(this, {allowHalfOpen: true}, HTTPServer.connectionListener); HTTPServer.initServer.call(this, options, requestListener); } util.inherits(Server, net.Server); Server.prototype.setTimeout = function(ms, cb) { this.timeout = ms; if (cb) { this.on('timeout', cb); } }; exports.Server = Server; exports.createServer = function(options, requestListener) { return new Server(options, requestListener); }; exports.METHODS = HTTPParser.methods; exports.get = function(options, cb) { var req = exports.request(options, cb); req.end(); return req; }; exports.IncomingMessage = IncomingMessage; exports.ServerResponse = HTTPServer.ServerResponse; iotjs-1.0+715/src/js/http_client.js000066400000000000000000000116061371177304000170770ustar00rootroot00000000000000/* 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 util = require('util'); var OutgoingMessage = require('http_outgoing').OutgoingMessage; var common = require('http_common'); var HTTPParser = require('http_parser').HTTPParser; function ClientRequest(options, cb, socket) { OutgoingMessage.call(this); // get port, host and method. var method = options.method || 'GET'; var path = options.path || '/'; options.host = options.hostname || options.host || '127.0.0.1'; // If `options` contains header information, save it. if (options.headers) { var keys = Object.keys(options.headers); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; this.setHeader(key, options.headers[key]); } } if (options.host && !this.getHeader('host')) { var hostHeader = options.host; if (this._port && +this._port !== 80) { hostHeader += ':' + this._port; } this.setHeader('Host', hostHeader); } // store first header line to be sent. this._storeHeader(method + ' ' + path + ' HTTP/1.1\r\n'); // Register response event handler. if (cb) { this.once('response', cb); } this.socket = socket; this.options = options; } util.inherits(ClientRequest, OutgoingMessage); exports.ClientRequest = ClientRequest; ClientRequest.prototype.end = function(data, encoding, callback) { var self = this; // connect server. this.socket.connect(this.options, function() { self._connected = true; OutgoingMessage.prototype.end.call(self, data, encoding, callback); }); // setup connection information. setupConnection(this); }; function setupConnection(req) { var socket = req.socket; var parser = common.createHTTPParser(HTTPParser.RESPONSE); socket.parser = parser; socket._httpMessage = req; parser.socket = socket; parser.incoming = null; parser._headers = []; parser.onIncoming = parserOnIncomingClient; req.parser = parser; socket.on('error', socketOnError); socket.on('data', socketOnData); socket.on('end', socketOnEnd); socket.on('close', socketOnClose); // socket emitted when a socket is assigned to req process.nextTick(function() { req.emit('socket', socket); }); } function cleanUpSocket(socket) { var parser = socket.parser; var req = socket._httpMessage; if (parser) { // unref all links to parser, make parser GCed parser.finish(); parser = null; socket.parser = null; req.parser = null; } socket.destroy(); } function emitError(socket, err) { var req = socket._httpMessage; if (err) { var host; if ((host = req.getHeader('host'))) { err.message += ': ' + host; } req.emit('error', err); } } function socketOnClose() { var socket = this; var req = socket._httpMessage; req.emit('close'); if (req.res && req.res.readable) { // Socket closed before we emitted 'end' var res = req.res; res.on('end', function() { res.emit('close'); }); res.push(null); } cleanUpSocket(this); } function socketOnError(err) { cleanUpSocket(this); emitError(this, err); } function socketOnData(d) { var socket = this; var req = this._httpMessage; var parser = this.parser; var ret = parser.execute(d); if (ret instanceof Error) { cleanUpSocket(socket); req.emit('error', ret); } } function socketOnEnd() { cleanUpSocket(this); } // This is called by parserOnHeadersComplete after response header is parsed. // TODO: keepalive support function parserOnIncomingClient(res/* , shouldKeepAlive */) { var socket = this.socket; var req = socket._httpMessage; if (req.res) { // server sent responses twice. socket.destroy(); return false; } req.res = res; res.req = req; res.on('end', responseOnEnd); req.emit('response', res); // response to HEAD req has no body var isHeadResponse = (req.method == 'HEAD'); return isHeadResponse; } var responseOnEnd = function() { var res = this; var req = res.req; var socket = req.socket; if (socket._socketState.writable) { socket.destroySoon(); } }; ClientRequest.prototype.abort = function() { this.emit('abort'); if (this.socket) { cleanUpSocket(this.socket); } }; ClientRequest.prototype.setTimeout = function(ms, cb) { var self = this; if (cb) self.once('timeout', cb); setTimeout(function() { self.emit('timeout'); }, ms); }; iotjs-1.0+715/src/js/http_common.js000066400000000000000000000057721371177304000171200ustar00rootroot00000000000000/* 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 util = require('util'); var IncomingMessage = require('http_incoming').IncomingMessage; var HTTPParser = require('http_parser').HTTPParser; exports.createHTTPParser = function(type) { var parser = new HTTPParser(type); // cb during http parsing from C side(http_parser) parser.OnHeaders = parserOnHeaders; parser.OnHeadersComplete = parserOnHeadersComplete; parser.OnBody = parserOnBody; parser.OnMessageComplete = parserOnMessageComplete; parser._IncomingMessage = IncomingMessage; return parser; }; // This is called when parsing of incoming http msg done function parserOnMessageComplete() { var stream = this.incoming; if (!stream) { return; } stream.complete = true; // no more data from incoming, stream will emit 'end' event stream.push(null); stream.socket.resume(); } // This is called when header part in http msg is parsed. function parserOnHeadersComplete(info) { var headers = info.headers; var url = info.url; if (!url) { url = this._url; this.url = ''; } if (!headers) { headers = this._headers; this._headers = []; } this.incoming = new this._IncomingMessage(this.socket); this.incoming.url = url; this.incoming.httpVersion = info.http_major + '.' + info.http_minor; // add header fields of headers to incoming.headers this.incoming.addHeaders(headers); if (util.isNumber(info.method)) { // for server this.incoming.method = HTTPParser.methods[info.method]; } else { // for client this.incoming.statusCode = info.status; this.incoming.statusMessage = info.status_msg; } // For client side, if response to 'HEAD' request, we will skip parsing body var skipBody = this.onIncoming(this.incoming, info.shouldkeepalive); return skipBody; } // parserOnBody is called when HTTPParser parses http msg(incoming) and // get body part(buf from start at length of len) function parserOnBody(buf, start, len) { var stream = this.incoming; if (!stream) { return; } // Push body part into incoming stream, which will emit 'data' event var body = buf.slice(start, start+len); stream.push(body); } // This is called when http header is fragmented and // HTTPParser sends it to JS in separate pieces. function parserOnHeaders(headers, url) { // push new header parts into existing array this._headers.push.apply(this._headers, headers); if (url) { this._url += url; } } iotjs-1.0+715/src/js/http_incoming.js000066400000000000000000000031761371177304000174270ustar00rootroot00000000000000/* 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 util = require('util'); var stream = require('stream'); function IncomingMessage(socket) { stream.Readable.call(this); this.socket = socket; this.readable = true; this.headers = {}; this.complete = false; // for request (server) this.url = ''; this.method = null; this.httpVersion = ''; // for response (client) this.statusCode = null; this.statusMessage = null; } util.inherits(IncomingMessage, stream.Readable); exports.IncomingMessage = IncomingMessage; IncomingMessage.prototype.read = function(n) { this.read = stream.Readable.prototype.read; return this.read(n); }; IncomingMessage.prototype.addHeaders = function(headers) { if (!this.headers) { this.headers = {}; } // FIXME: handle headers as array if array C API is done. for (var i=0; i 0; } function nextTick(callback) { var args = Array.prototype.slice.call(arguments); args[0] = null; nextTickQueue.push(Function.prototype.bind.apply(callback, args)); } process._onUncaughtException = _onUncaughtException; function _onUncaughtException(error) { var event = 'uncaughtException'; if (process._events[event] && process._events[event].length > 0) { try { // Emit uncaughtException event. process.emit('uncaughtException', error); } catch (e) { // Even uncaughtException handler thrown, that could not be handled. console.error('uncaughtException handler throws: ' + e); process.exit(1); } } else { // Exit if there are no handler for uncaught exception. console.error(error); if (Array.isArray(error.stack)) { error.stack.forEach(function(line) { console.log(' at ' + line); }); } process.exit(1); } } process.exitCode = 0; process._exiting = false; process.emitExit = function(code) { code = code || process.exitCode; if (typeof code !== 'number') { code = 0; } if (!process._exiting) { process._exiting = true; if (code || code == 0) { process.exitCode = code; } process.emit('exit', process.exitCode); } }; process.exit = function(code) { if (!process._exiting) { try { process.emitExit(code); } catch (e) { process.exitCode = 1; process._onUncaughtException(e); } finally { process.doExit(process.exitCode); } } }; var module = Module.require('module'); module.runMain(); })(); iotjs-1.0+715/src/js/module.js000066400000000000000000000204531371177304000160470ustar00rootroot00000000000000/* 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 Builtin = require('builtin'); var fs = Builtin.require('fs'); var dynamicloader; try { dynamicloader = Builtin.require('napi'); } catch (e) { // the 'dynamicloader' module is not enabled, nothing to do. } function normalizePathString(path) { // Assume all path separators are '/' var input = path.split('/'); var output = []; while (input.length > 0) { if (input[0] === '.' || (input[0] === '' && input.length > 1)) { input.shift(); continue; } if (input[0] === '..') { input.shift(); if (output.length > 0 && output[output.length - 1] !== '..') { output.pop(); } else { throw new Error('Requested path is below root: ' + path); } continue; } output.push(input.shift()); } return output; } var path; if (process.platform === 'windows') { /* In case of windows: * replace all '\' characters to '/' for ease of use for now. */ path = { unixPathReplacer: new RegExp('/', 'g'), winPathReplacer: new RegExp('\\\\', 'g'), pathSeparator: '\\', toUnixPath: function(pathString) { return pathString.replace(path.winPathReplacer, '/'); }, toWindowsPath: function(pathString) { return pathString.replace(path.unixPathReplacer, '\\\\'); }, isDeviceRoot: function(pathString) { if (pathString.charCodeAt(1) !== 0x3A /* ':' */) { return false; } var drive = pathString.charCodeAt(0); return (drive >= 0x61 /* a */ && drive <= 0x7A /* z */) || (drive >= 0x41 /* A */ && drive <= 0x5A /* Z */); }, normalizePath: function(pathString) { pathString = path.toUnixPath(pathString); var deviceRoot = ''; if (!path.isDeviceRoot(pathString)) { deviceRoot = path.cwd().substr(0, 2) + '/'; } var pathElements = normalizePathString(pathString); return deviceRoot + pathElements.join('/'); }, cwd: function() { return path.toUnixPath(process.cwd()); }, }; } else { path = { isDeviceRoot: function(pathString) { return pathString.charCodeAt(0) === 0x2F; /* '/' */ }, normalizePath: function(path) { var beginning = ''; if (path.indexOf('/') === 0) { beginning = '/'; } var pathElements = normalizePathString(path); return beginning + pathElements.join('/'); }, cwd: process.cwd, }; } function Module(id, parent) { this.id = id; this.exports = {}; this.filename = null; this.parent = parent; } module.exports = Module; Module.cache = {}; // Cache to store not yet compiled remote modules Module.remoteCache = {}; var moduledirs = ['']; var cwd; try { cwd = process.env.IOTJS_WORKING_DIR_PATH || path.cwd(); } catch (e) { } if (cwd) { moduledirs.push(cwd + '/'); moduledirs.push(cwd + '/iotjs_modules/'); } if (process.env.HOME) { moduledirs.push(process.env.HOME + '/iotjs_modules/'); } if (process.env.IOTJS_PATH) { moduledirs.push(process.env.IOTJS_PATH + '/iotjs_modules/'); } if (process.env.IOTJS_EXTRA_MODULE_PATH) { var extra_paths = process.env.IOTJS_EXTRA_MODULE_PATH.split(':'); extra_paths.forEach(function(path) { if (path.slice(-1) !== '/') { path += '/'; } moduledirs.push(path); }); } function tryPath(modulePath, ext) { return Module.tryPath(modulePath) || Module.tryPath(modulePath + ext); } Module.resolveDirectories = function(id, parent) { var dirs = moduledirs; if (parent) { if (!parent.dirs) { parent.dirs = []; } dirs = parent.dirs.concat(dirs); } return dirs; }; Module.resolveFilepath = function(id, directories) { for (var i = 0; i < directories.length; i++) { var dir = directories[i]; var modulePath = dir + id; if (!path.isDeviceRoot(modulePath)) { modulePath = path.cwd() + '/' + modulePath; } if ((process.platform === 'tizenrt' || process.platform === 'nuttx') && (modulePath.indexOf('../') != -1 || modulePath.indexOf('./') != -1)) { modulePath = path.normalizePath(modulePath); } var filepath, ext = '.js'; // id[.ext] if ((filepath = tryPath(modulePath, ext))) { return filepath; } // 3. package path id/ var jsonpath = modulePath + '/package.json'; if (Module.tryPath(jsonpath)) { var pkgSrc = Builtin.readSource(jsonpath); var pkgMainFile = JSON.parse(pkgSrc).main; // pkgmain[.ext] if (pkgMainFile && (filepath = tryPath(modulePath + '/' + pkgMainFile, ext))) { return filepath; } } // index[.ext] as default if ((filepath = tryPath(modulePath + '/index', ext))) { return filepath; } // id[.node] if (dynamicloader && (filepath = tryPath(modulePath, '.node'))) { return filepath; } } return false; }; Module.resolveModPath = function(id, parent) { if (parent != null && id === parent.id) { return false; } // 0. resolve Directory for lookup var directories = Module.resolveDirectories(id, parent); var filepath = Module.resolveFilepath(id, directories); if (filepath) { return path.normalizePath(filepath); } return false; }; Module.tryPath = function(path) { try { var stats = fs.statSync(path); if (stats && !stats.isDirectory()) { return path; } } catch (ex) { } return false; }; Module.load = function(id, parent) { if (Builtin.builtin_modules[id]) { return Builtin.require(id); } if (Module.remoteCache[id]) { Module.compileRemoteSource(id, Module.remoteCache[id]); delete Module.remoteCache[id]; return Module.cache[id].exports; } var module = new Module(id, parent); var modPath = Module.resolveModPath(module.id, module.parent); var cachedModule = Module.cache[modPath]; if (cachedModule) { return cachedModule.exports; } if (!modPath) { throw new Error('Module not found: ' + id); } module.filename = modPath; module.dirs = [modPath.substring(0, modPath.lastIndexOf('/') + 1)]; Module.cache[modPath] = module; var ext = modPath.substr(modPath.lastIndexOf('.') + 1); var source; if (ext === 'js') { source = Builtin.readSource(modPath); module.compile(modPath, source); } else if (ext === 'json') { source = Builtin.readSource(modPath); module.exports = JSON.parse(source); } else if (dynamicloader && ext === 'node') { if (process.platform === 'windows') { module.exports = dynamicloader(path.toWindowsPath(modPath)); } else { module.exports = dynamicloader(modPath); } } Module.cache[modPath] = module; return module.exports; }; Module.compileRemoteSource = function(filename, source) { var module = new Module(filename, null); var cachedModule = Module.cache[filename]; if (cachedModule) { return cachedModule.exports; } module.filename = filename; module.compile(filename, source); Module.cache[filename] = module; return module.exports; }; Module.prototype.compile = function(filename, source) { var fn = Builtin.compile(filename, source); fn.call(this.exports, this.exports, this.require.bind(this), this); }; Module.runMain = function() { if (Builtin.debuggerWaitSource) { var sources = Builtin.debuggerGetSource(); if (sources.length == 0) { var err = new Error('No remote source received!'); return process._onUncaughtException(err); } sources.forEach(function(rModule) { Module.remoteCache[rModule[0]] = rModule[1]; }); // Name of the first module var fModName = sources[sources.length - 1][0]; Module.compileRemoteSource(fModName, Module.remoteCache[fModName]); } else { Module.load(process.argv[1], null); } while (process._onNextTick()); }; Module.prototype.require = function(id) { return Module.load(id, this); }; iotjs-1.0+715/src/js/mqtt.js000066400000000000000000000237411371177304000155520ustar00rootroot00000000000000/* Copyright 2018-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 EventEmitter = require('events').EventEmitter; var net, tls; var PacketTypeEnum = { PUBACK: 4, PUBREC: 5, PUBREL: 6, PUBCOMP: 7, }; // In seconds (should be divisible by 8) var MQTTTimeout = 64; function MQTTHandle(client, keepalive) { this.client = client; this.isConnected = false; this.nextPacketId = 0; this.keepalive = keepalive; this.keepaliveCounter = 0; this.pingrespCounter = 0; this.storage = { }; this.storageCount = 0; native.MqttInit(this); } MQTTHandle.prototype = {}; MQTTHandle.prototype.write = function(buf) { this.socket.write(buf); this.keepaliveCounter = 0; }; MQTTHandle.prototype.sendAck = function(type, packet_id) { this.write(native.sendAck(type, packet_id)); }; MQTTHandle.prototype.onconnection = function() { this.isConnected = true; this.timer = setInterval(storageTimerHit.bind(this), 1000); this.client.emit('connect'); }; MQTTHandle.prototype.onEnd = function() { this.isConnected = false; // Abort outgoing messages. clearInterval(this.timer); this.storage = null; this.storageCount = 0; this.client.emit('end'); }; MQTTHandle.prototype.onmessage = function(message, topic, qos, packet_id) { var data = { message: message, topic: topic, qos: qos, packet_id: packet_id, }; if (qos >= 1) { var type = (qos == 1) ? PacketTypeEnum.PUBACK : PacketTypeEnum.PUBREC; this.sendAck(type, packet_id); } this.client.emit('message', data); }; MQTTHandle.prototype.getPacketId = function() { while (true) { var packet_id = this.nextPacketId; this.nextPacketId = (this.nextPacketId + 1) & 0xffff; if (!(packet_id in this.storage)) { this.storage[packet_id] = { remainingTime: MQTTTimeout }; this.storageCount++; return packet_id; } } }; MQTTHandle.prototype.releasePacket = function(packet_id, error) { // callback will be invalid after delete var callback = this.storage[packet_id].callback; delete this.storage[packet_id]; this.storageCount--; // This function should never fail. try { if (typeof callback == 'function') { callback(error); } else if (error) { this.client.emit('error', error); } } catch (e) { // Do nothing. } }; MQTTHandle.prototype.onpingresp = function() { this.pingrespCounter = 0; }; MQTTHandle.prototype.onack = function(packet_id, error) { this.releasePacket(packet_id, error); }; MQTTHandle.prototype.onpubrec = function(packet_id) { /* * Qos level 2 * Handle PUBREC package. If this package is arrived, we have to send back * a PUBREL package to the server. */ var buffer = native.sendAck(PacketTypeEnum.PUBREL, packet_id); this.write(buffer); // Upodate packet rather than create a new one var packet = this.storage[packet_id]; packet.remainingTime = MQTTTimeout; packet.packet = buffer; }; MQTTHandle.prototype.onpubrel = function(data) { /* * Qos level 2 * Handle PUBREL package. If this package is arrived, we have to send back * a PUBCOMP package to the server. */ this.sendAck(PacketTypeEnum.PUBCOMP, data); }; function MQTTClient(url, options, callback) { if (!(this instanceof MQTTClient)) { return new MQTTClient(url, options, callback); } EventEmitter.call(this); var socket; if (typeof url == 'string') { if (typeof options == 'function') { callback = options; options = {}; } } else { if (typeof url == 'function') { callback = url; options = {}; } else if (typeof options == 'function') { callback = options; options = url; } else { options = url; } if (options.socket) { socket = options.socket; } else { url = options.host || '127.0.0.1'; } } if (typeof callback == 'function') { this.on('connect', callback); } if (options.will) { if (typeof options.topic == 'undefined' || typeof options.message == 'undefined' || options.qos < 0 || options.qos > 2) { throw new Error('Incorrect mqtt will options'); } } var host = ''; var create_tls = false; if (!socket) { if (url.substring(0, 8) == 'mqtts://') { create_tls = true; host = url.substring(8); } else if (url.substring(0, 7) == 'mqtt://') { host = url.substring(7); } else { host = url; } } var keepalive = (options.keepalive || 60) | 0; if (keepalive < 30) { keepalive = 30; } if (keepalive > 65535) { keepalive = 65535; } options = Object.create(options, { clientId: { value: options.clientId || defaultClientId() }, host: { value: host }, port: { value: options.port || 8883 }, qos: { value: options.qos || 0 }, keepalive: { value: keepalive }, }); // Since network transmission takes time, the // actual keepalive message is sent a bit earlier this._handle = new MQTTHandle(this, keepalive - 5); var connectionMessage = native.connect(options); var onconnect = function() { // Currently the connect message is tried only once. // Multiple tries can be implemented later. this.write(connectionMessage); }; if (socket) { onconnect.call(socket); } else { if (create_tls) { if (!tls) { tls = require('tls'); } socket = tls.connect(options, onconnect); } else { if (!net) { net = require('net'); } socket = net.connect(options, onconnect); } } this._handle.socket = socket; socket._mqttSocket = this; socket.on('error', onerror); socket.on('data', ondata); socket.on('finish', onfinish); } util.inherits(MQTTClient, EventEmitter); MQTTClient.prototype.end = function(force) { var handle = this._handle; handle.isConnected = false; if (force || handle.storageCount == 0) { handle.socket.end(native.disconnect()); // Abort ongoing messages. clearInterval(this.timer); this.storage = null; this.storageCount = 0; } }; MQTTClient.prototype.checkConnection = function() { if (!this._handle.isConnected) { throw new Error('MQTT client is not connected'); } }; MQTTClient.prototype.publish = function(topic, message, options, callback) { this.checkConnection(); var handle = this._handle; // header bits: | 16 bit packet id | 4 bit PUBLISH header | var header = 0; var qos = 0; if (options) { if (options.retain) { header = 0x1; } qos = options.qos; if (qos !== 1 && qos !== 2) { qos = 0; } header |= (qos << 1); } if (qos > 0) { var packet_id = handle.getPacketId(); header |= (packet_id << 4); var buffer = native.publish(topic, message, header); handle.write(buffer); // Set dup flag. buffer.writeUInt8(buffer.readUInt8(0) | 0x08, 0); var packet = handle.storage[packet_id]; packet.packet = buffer; packet.callback = callback; return; } handle.write(native.publish(topic, message, header)); if (typeof callback == 'function') { process.nextTick(callback); } }; MQTTClient.prototype.subscribe = function(topic, options, callback) { this.checkConnection(); var handle = this._handle; var packet_id = handle.getPacketId(); // header bits: | 2 bit qos | 16 bit packet id | var header = packet_id; var qos = 0; if (options) { qos = options.qos; if (qos !== 1 || qos !== 2) { qos = 0; } header |= (qos << 16); } var buffer = native.subscribe(topic, header); handle.write(buffer); var packet = handle.storage[packet_id]; packet.packet = buffer; packet.callback = callback; }; MQTTClient.prototype.unsubscribe = function(topic, callback) { this.checkConnection(); var handle = this._handle; var packet_id = handle.getPacketId(); // header bits: | 16 bit packet id | var header = packet_id; var buffer = native.unsubscribe(topic, header); handle.write(buffer); var packet = handle.storage[packet_id]; packet.packet = buffer; packet.callback = callback; }; function onerror(error) { this._mqttSocket.emit('error', error); } function ondata(data) { native.MqttReceive(this._mqttSocket._handle, data); } function onfinish() { this._mqttSocket._handle.onEnd(); } function storageTimerHit() { // this: MQTTHandle // eslint-disable-next-line guard-for-in for (var packet_id in this.storage) { var packet = this.storage[packet_id]; packet.remainingTime--; if (packet.remainingTime <= 0) { this.releasePacket(packet_id, new Error('Undelivered message')); continue; } // Every 8 seconds, the message is retransmitted. if (!(packet.remainingTime & 0x7)) { this.write(packet.packet); } } if (this.storageCount == 0 && !this.isConnected) { // Graceful disconnect after all messages transmitted. this.socket.end(native.disconnect()); clearInterval(this.timer); this.storage = null; return; } if (this.pingrespCounter > 0) { this.pingrespCounter--; if (this.pingrespCounter <= 0) { this.onEnd(); } } this.keepaliveCounter++; if (this.keepaliveCounter >= this.keepalive) { this.write(native.ping()); if (this.pingrespCounter == 0) { this.pingrespCounter = (this.keepalive + 5) * 3 >> 1; } } } /* * Returns an unique client ID based on current time. */ function defaultClientId() { return 'iotjs_mqtt_client_' + Date.now(); } function connect(url, options, callback) { return new MQTTClient(url, options, callback); } exports.connect = connect; iotjs-1.0+715/src/js/net.js000066400000000000000000000346631371177304000153600ustar00rootroot00000000000000/* 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 EventEmitter = require('events').EventEmitter; var stream = require('stream'); var util = require('util'); var assert = require('assert'); var Tcp = require('tcp'); function createTCP() { var _tcp = new Tcp(); return _tcp; } // Expected end message on nuttx platform. var expectedEnding; if (process.platform == 'nuttx') { expectedEnding = new Buffer('\\e\\n\\d'); } function SocketState(options) { // 'true' during connection handshaking. this.connecting = false; // become 'true' when connection established. this.connected = false; this.writable = true; this.readable = true; this.destroyed = false; this.errored = false; this.allowHalfOpen = options && options.allowHalfOpen || false; } function Socket(options) { if (!(this instanceof Socket)) { return new Socket(options); } if (options === undefined) { options = {}; } stream.Duplex.call(this, options); this._timer = null; this._timeout = 0; this._socketState = new SocketState(options); if (options.handle) { this._handle = options.handle; this._handle.owner = this; } this.on('finish', onSocketFinish); this.on('end', onSocketEnd); } // Socket inherits Duplex. util.inherits(Socket, stream.Duplex); Socket.prototype.connect = function() { var self = this; var state = self._socketState; var args = normalizeConnectArgs(arguments); var options = args[0]; var callback = args[1]; if (state.connecting || state.connected) { return self; } if (!self._handle) { self._handle = createTCP(); self._handle.owner = self; } if (util.isFunction(callback)) { self.once('connect', callback); } resetSocketTimeout(self); state.connecting = true; var dns = require('dns'); var host = options.host ? options.host : 'localhost'; var port = options.port; var dnsopts = { family: options.family >>> 0, hints: 0, }; if (!util.isNumber(port) || port < 0 || port > 65535) throw new RangeError('port should be >= 0 and < 65536: ' + options.port); if (dnsopts.family !== 0 && dnsopts.family !== 4 && dnsopts.family !== 6) throw new RangeError('family should be 4 or 6: ' + dnsopts.family); self._host = host; dns.lookup(host, dnsopts, function(err, ip, family) { if (self._socketState.destroyed) { return; } self.emit('lookup', err, ip, family); if (err) { process.nextTick(function() { self.emit('error', err); self.destroy(); }); } else { resetSocketTimeout(self); connect(self, ip, port); } }); return self; }; Socket.prototype.write = function(data, callback) { if (!util.isString(data) && !util.isBuffer(data)) { throw new TypeError('invalid argument'); } return stream.Duplex.prototype.write.call(this, data, callback); }; Socket.prototype._write = function(chunk, callback, afterWrite) { assert(util.isBuffer(chunk)); assert(util.isFunction(afterWrite)); var self = this; if (self.errored) { process.nextTick(afterWrite, 1); if (util.isFunction(callback)) { process.nextTick(function(self, status) { callback.call(self, status); }, self, 1); } } else { resetSocketTimeout(self); self._handle.owner = self; self._handle.write(chunk, function(status) { afterWrite(status); if (util.isFunction(callback)) { callback.call(self, status); } }); } }; Socket.prototype.end = function(data, callback) { var self = this; var state = self._socketState; // end of writable stream. stream.Writable.prototype.end.call(self, data, callback); // this socket is no longer writable. state.writable = false; }; // Destroy this socket as fast as possible. Socket.prototype.destroy = function() { var self = this; var state = self._socketState; if (state.destroyed) { return; } if (state.writable) { self.end(); } // unset timeout clearSocketTimeout(self); if (self._writableState.ended && self._handle) { close(self); state.destroyed = true; } else { self.once('finish', function() { self.destroy(); }); } }; // Destroy this socket as fast as possible if this socket is no longer readable. Socket.prototype.destroySoon = function() { var self = this; var state = self._socketState; if (state.writable) { self.end(); } if (self._writableState.finished) { self.destroy(); } else { self.once('finish', self.destroy); } }; Socket.prototype.setKeepAlive = function(enable, delay) { var self = this; enable = +Boolean(enable); if (self._handle && self._handle.setKeepAlive) { self._handle.setKeepAlive(enable, ~~(delay / 1000)); } }; Socket.prototype.address = function() { if (!this._handle || !this._handle.getsockname) { return {}; } if (!this._sockname) { var out = {}; var err = this._handle.getsockname(out); if (err) return {}; // FIXME(bnoordhuis) Throw? this._sockname = out; } return this._sockname; }; Socket.prototype.setTimeout = function(msecs, callback) { var self = this; self._timeout = msecs; clearSocketTimeout(self); if (msecs === 0) { if (callback) { self.removeListener('timeout', callback); } } else { self._timer = setTimeout(function() { self.emit('timeout'); clearSocketTimeout(self); }, msecs); if (callback) { self.once('timeout', callback); } } }; function connect(socket, ip, port) { var afterConnect = function(status) { var state = socket._socketState; state.connecting = false; if (state.destroyed) { return; } if (status == 0) { onSocketConnect(socket); socket.emit('connect'); } else { socket.destroy(); emitError(socket, new Error('connect failed - status: ' + Tcp.errname(status))); } }; var err = socket._handle.connect(ip, port, afterConnect); if (err) { emitError(socket, new Error('connect failed - status: ' + Tcp.errname(err))); } } function close(socket) { socket._handle.owner = socket; socket._handle.onclose = function() { socket.emit('close'); }; var handle = socket._handle; socket._handle = null; handle.close(); if (socket._server) { var server = socket._server; server._socketCount--; server._emitCloseIfDrained(); socket._server = null; } } function resetSocketTimeout(socket) { var state = socket._socketState; if (!state.destroyed) { // start timeout over again clearSocketTimeout(socket); socket._timer = setTimeout(function() { socket.emit('timeout'); clearSocketTimeout(socket); }, socket._timeout); } } function clearSocketTimeout(socket) { if (socket._timer) { clearTimeout(socket._timer); socket._timer = null; } } function emitError(socket, err) { socket.errored = true; stream.Duplex.prototype.end.call(socket, '', function() { socket.destroy(); }); socket._readyToWrite(); socket.emit('error', err); } function maybeDestroy(socket) { var state = socket._socketState; if (!state.connecting && !state.writable && !state.readable) { socket.destroy(); } } function onSocketConnect(socket) { var state = socket._socketState; state.connecting = false; state.connected = true; resetSocketTimeout(socket); socket._readyToWrite(); // `readStart` on next tick, after connection event handled. process.nextTick(function() { socket._handle.owner = socket; socket._handle.onread = onread; socket._handle.readStart(); }); } function onread(socket, nread, isEOF, buffer) { var state = socket._socketState; resetSocketTimeout(socket); if (isEOF) { // pushing readable stream null means EOF. stream.Readable.prototype.push.call(socket, null); if (socket._readableState.length == 0) { // this socket is no longer readable. state.readable = false; // destroy if this socket is not writable. maybeDestroy(socket); } } else if (nread < 0) { var err = new Error('read error: ' + nread); stream.Readable.prototype.error.call(socket, err); } else if (nread > 0) { if (process.platform !== 'nuttx') { stream.Readable.prototype.push.call(socket, buffer); return; } // We know for sure the last 6 characters are going to be the ending. // Lets create a buffer with those 6 characters without toString conversion. var eofLength = 6; var bufferLength = buffer.length; var eofNeeded = false; if (bufferLength >= eofLength && expectedEnding.compare(buffer.slice(bufferLength - eofLength, bufferLength)) == 0) { eofNeeded = true; buffer = buffer.slice(0, bufferLength - eofLength); } if (bufferLength == eofLength && eofNeeded) { // Socket.prototype.end with no argument } else { stream.Readable.prototype.push.call(socket, buffer); } if (eofNeeded) { onread(socket, 0, true, null); } } } // Writable stream finished. function onSocketFinish() { var self = this; var state = self._socketState; if (!state.readable || self._readableState.ended || !self._handle) { // no readable stream or ended, destroy(close) socket. return self.destroy(); } else { // Readable stream alive, shutdown only outgoing stream. self._handle.shutdown(function() { if (self._readableState.ended) { self.destroy(); } }); } } // Readable stream ended. function onSocketEnd() { var state = this._socketState; maybeDestroy(this); if (!state.allowHalfOpen) { this.destroySoon(); } } function Server(options, connectionListener) { if (!(this instanceof Server)) { return new Server(options, connectionListener); } EventEmitter.call(this); if (util.isFunction(options)) { connectionListener = options; options = {}; } else { options = options || {}; } if (util.isFunction(connectionListener)) { this.on('connection', connectionListener); } this._handle = null; this._socketCount = 0; this.allowHalfOpen = options.allowHalfOpen || false; } // Server inherits EventEmitter. util.inherits(Server, EventEmitter); // listen Server.prototype.listen = function() { var self = this; var args = normalizeListenArgs(arguments); var options = args[0]; var callback = args[1]; var port = options.port; var host = util.isString(options.host) ? options.host : '0.0.0.0'; var backlog = util.isNumber(options.backlog) ? options.backlog : 511; if (!util.isNumber(port)) { throw new Error('invalid argument - need port number'); } // register listening event listener. if (util.isFunction(callback)) { self.once('listening', callback); } // Create server handle. if (!self._handle) { self._handle = createTCP(); } // bind port var err = self._handle.bind(host, port); if (err) { self._handle.close(); return self.emit('error', err); } // listen self._handle.onconnection = onconnection; self._handle.createTCP = createTCP; self._handle.owner = self; err = self._handle.listen(backlog); if (err) { self._handle.close(); return self.emit('error', err); } process.nextTick(function() { if (self._handle) { self.emit('listening'); } }); return this; }; Server.prototype.address = function() { if (this._handle && this._handle.getsockname) { var out = {}; this._handle.getsockname(out); // TODO(bnoordhuis) Check err and throw? return out; } return null; }; Server.prototype.close = function(callback) { if (util.isFunction(callback)) { if (!this._handle) { this.once('close', function() { callback(new Error('Not running')); }); } else { this.once('close', callback); } } if (this._handle) { this._handle.close(); this._handle = null; } this._emitCloseIfDrained(); return this; }; Server.prototype._emitCloseIfDrained = function() { var self = this; if (self._handle || self._socketCount > 0) { return; } process.nextTick(function() { self.emit('close'); }); }; // This function is called after server accepted connection request // from a client. // This binding // * server tcp handle // Parameters // * status - status code // * clientHandle - client socket handle (tcp). function onconnection(status, clientHandle) { var server = this.owner; if (status) { server.emit('error', new Error('accept error: ' + Tcp.errname(status))); return; } // Create socket object for connecting client. var socket = new Socket({ handle: clientHandle, allowHalfOpen: server.allowHalfOpen, }); socket._server = server; onSocketConnect(socket); server._socketCount++; server.emit('connection', socket); } function normalizeListenArgs(args) { var options = {}; if (util.isObject(args[0])) { options = args[0]; } else { var idx = 0; options.port = args[idx++]; if (util.isString(args[idx])) { options.host = args[idx++]; } if (util.isNumber(args[idx])) { options.backlog = args[idx++]; } } var cb = args[args.length - 1]; return util.isFunction(cb) ? [options, cb] : [options]; } function normalizeConnectArgs(args) { var options = {}; if (util.isObject(args[0])) { options = args[0]; } else { options.port = args[0]; if (util.isString(args[1])) { options.host = args[1]; } } var cb = args[args.length - 1]; return util.isFunction(cb) ? [options, cb] : [options]; } exports.createServer = function(options, callback) { return new Server(options, callback); }; // net.connect(options[, connectListener]) // net.connect(port[, host][, connectListener]) exports.connect = exports.createConnection = function() { var args = normalizeConnectArgs(arguments); var socket = new Socket(args[0]); return Socket.prototype.connect.apply(socket, args); }; module.exports.Socket = Socket; module.exports.Server = Server; iotjs-1.0+715/src/js/pwm.js000066400000000000000000000016001371177304000153560ustar00rootroot00000000000000/* 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 pwm = { open: function(config, callback) { var pwmPin = new native(config, function(err) { callback(err, pwmPin); }); return pwmPin; }, openSync: function(config) { return new native(config); }, }; module.exports = pwm; iotjs-1.0+715/src/js/spi.js000066400000000000000000000017231371177304000153540ustar00rootroot00000000000000/* 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 spi = { open: function(config, callback) { var spiBus = new native(config, function(err) { callback(err, spiBus); }); return spiBus; }, openSync: function(config) { return new native(config); }, MODE: native.MODE, CHIPSELECT: native.CHIPSELECT, BITORDER: native.BITORDER, }; module.exports = spi; iotjs-1.0+715/src/js/stream.js000066400000000000000000000017201371177304000160510ustar00rootroot00000000000000/* 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 StreamInternal = require('stream_internal'); var util = require('util'); function Stream() { StreamInternal.call(this); } util.inherits(Stream, StreamInternal); exports.Stream = Stream; exports.Readable = require('stream_readable'); exports.Writable = require('stream_writable'); exports.Duplex = require('stream_duplex'); iotjs-1.0+715/src/js/stream_duplex.js000066400000000000000000000025671371177304000174440ustar00rootroot00000000000000/* 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 util = require('util'); var Readable = require('stream_readable'); var Writable = require('stream_writable'); function Duplex(options) { if (!(this instanceof Duplex)) { return new Duplex(options); } Readable.call(this, options); options = options || {}; options._isDuplex = true; Writable.call(this, options); } // Duplex inherits Readable. util.inherits(Duplex, Readable); // Duplex should also inherits Writable but there are no way for inheriting // from multiple parents. Copy properties from Writable. var keys = Object.keys(Writable.prototype); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!Duplex.prototype[key]) { Duplex.prototype[key] = Writable.prototype[key]; } } module.exports = Duplex; iotjs-1.0+715/src/js/stream_internal.js000066400000000000000000000015041371177304000177450ustar00rootroot00000000000000/* Copyright 2018-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 eventEmitter = require('events').EventEmitter; var util = require('util'); function Stream() { eventEmitter.call(this); } util.inherits(Stream, eventEmitter); module.exports = Stream; iotjs-1.0+715/src/js/stream_readable.js000066400000000000000000000135201371177304000176710ustar00rootroot00000000000000/* 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 Stream = require('stream_internal'); var Writable = require('stream_writable'); var util = require('util'); function ReadableState(options) { options = options || {}; // the internal array of buffers. this.buffer = []; // the sum of length of buffers. this.length = 0; this.defaultEncoding = options.defaultEncoding || 'utf8'; // true if in flowing mode. this.flowing = false; // become `true` when the stream meet EOF. this.ended = false; // become `true` just before emit 'end' event. this.endEmitted = false; } function Readable(options) { if (!(this instanceof Readable)) { return new Readable(options); } this._readableState = new ReadableState(options); Stream.call(this); } util.inherits(Readable, Stream); Readable.prototype.read = function(n) { var state = this._readableState; var res; if (!util.isNumber(n) || n > state.length) { n = state.length; } else if (n < 0) { n = 0; } if (n > 0) { res = readBuffer(this, n); } else { res = null; } return res; }; Readable.prototype.on = function(ev, cb) { var res = Stream.prototype.on.call(this, ev, cb); if (ev === 'data') { this.resume(); } return res; }; Readable.prototype.isPaused = function() { return !this._readableState.flowing; }; Readable.prototype.pause = function() { var state = this._readableState; if (state.flowing) { state.flowing = false; this.emit('pause'); } return this; }; Readable.prototype.resume = function() { var state = this._readableState; if (!state.flowing) { state.flowing = true; this.read(); } return this; }; Readable.prototype.error = function(error) { this.emit('error', error); }; Readable.prototype.push = function(chunk, encoding) { var state = this._readableState; if (chunk === null) { onEof(this); } else if (!util.isString(chunk) && !util.isBuffer(chunk)) { this.error(TypeError('Invalid chunk')); } else if (state.ended) { this.error(Error('stream.push() after EOF')); } else { if (util.isString(chunk)) { encoding = encoding || state.defaultEncoding; chunk = new Buffer(chunk, encoding); } if (state.flowing) { emitData(this, chunk); } else { state.length += chunk.length; state.buffer.push(chunk); this.emit('readable'); } } }; Readable.prototype.pipe = function(destination, options) { if (!(destination instanceof Writable || isDuplex(destination))) { throw new TypeError('pipe excepts stream.Writable or' + ' stream.Duplex as argument'); } options = options || {'end': true}; var listeners = { readableListener: readableListener.bind(this), dataListener: dataListener.bind(destination), endListener: endListener.bind(destination), }; this.on('readable', listeners.readableListener); this.on('data', listeners.dataListener); if (options.end) { this.on('end', listeners.endListener); } this._piped = this._piped || []; this._piped.push(destination); this._piped_listeners = this._piped_listeners || []; this._piped_listeners.push(listeners); return destination; }; Readable.prototype.unpipe = function(destination) { if (destination === undefined) { this.removeAllListeners(); this._piped = undefined; this._piped_listeners = undefined; return; } var idx = this._piped.indexOf(destination); if (idx === -1) { return; } this._piped.splice(idx, 1); var listeners = this._piped_listeners.splice(idx, 1)[0]; this.removeListener('readable', listeners.readableListener); this.removeListener('data', listeners.dataListener); this.removeListener('end', listeners.endListener); return destination; }; function readableListener() { this.resume(); } function dataListener(data) { this.write(data); } function endListener() { this.end(); } function readBuffer(stream, n) { var state = stream._readableState; var res; if (n == 0 || util.isNullOrUndefined(n)) { n = state.length; } if (state.buffer.length === 0 || state.length === 0) { res = null; } else if (n >= state.length) { res = Buffer.concat(state.buffer); state.buffer = []; state.length = 0; emitData(stream, res); } else { throw new Error('not implemented'); } return res; } function emitEnd(stream) { var state = stream._readableState; if (stream.length > 0 || !state.ended) { throw new Error('stream ended on non-EOF stream'); } if (!state.endEmitted) { state.endEmitted = true; stream.emit('end'); } } function emitData(stream, data) { var state = stream._readableState; if (state.buffer.length === 0 || state.length === 0) { stream.emit('data', data); } if (state.ended && state.length == 0) { emitEnd(stream); } } function onEof(stream) { var state = stream._readableState; state.ended = true; if (state.length == 0) { emitEnd(stream); } } function isDuplex(stream) { if (!(stream instanceof Readable)) { return false; } var wr_keys = Object.keys(Writable.prototype); for (var i = 0; i < wr_keys.length; i++) { var wr_key = wr_keys[i]; if (!stream[wr_key]) { return false; } } return true; } module.exports = Readable; iotjs-1.0+715/src/js/stream_writable.js000066400000000000000000000145321371177304000177470ustar00rootroot00000000000000/* 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 Stream = require('stream_internal'); var util = require('util'); var defaultHighWaterMark = 128; function WriteReq(chunk, callback) { this.chunk = chunk; this.callback = callback; } function WritableState(options) { // buffer of WriteReq this.buffer = []; // total length of messages not flushed yet. this.length = 0; // high water mark. // The point where write() starts returning false. this.highWaterMark = (options && util.isNumber(options.highWaterMark)) ? options.highWaterMark : defaultHighWaterMark; // 'true' if stream is ready to write. this.ready = false; // `true` if stream is writing down data underlying system. this.writing = false; // the length of message being writing. this.writingLength = 0; // turn 'true' when some messages are buffered. After buffered messages are // all sent, 'drain' event will be emitted. this.needDrain = false; // become `true` when `end()` called. this.ending = false; // become `true` when there are no date to write. this.ended = false; } function Writable(options) { if (!(this instanceof Writable) && options._isDuplex !== true) { return new Writable(options); } this._writableState = new WritableState(options); Stream.call(this); } util.inherits(Writable, Stream); // Write chunk of data to underlying system stream. // Control flow in general description // Writable.prototype.write() // || // writeOrBuffer() // || // doWrite() // || // ConcreteStream.prototype._write() // | // underlying stream // | // Writable.prototype._onwrite() Writable.prototype.write = function(chunk, callback) { var state = this._writableState; if (state.ended) { writeAfterEnd(this, callback); return false; } return writeOrBuffer(this, chunk, callback); }; // This function object never to be called. concrete stream should override // this method. Writable.prototype._write = function(/* chunk, callback, onwrite */) { throw new Error('unreachable'); }; Writable.prototype.end = function(chunk, callback) { var state = this._writableState; // Because NuttX cannot poll 'EOF',so forcely raise EOF event. if (process.platform === 'nuttx') { if (!state.ending) { var eof = '\\e\\n\\d'; if (util.isNullOrUndefined(chunk)) { chunk = eof; } else if (Buffer.isBuffer(chunk)) { chunk = Buffer.concat([chunk, new Buffer(eof)]); } else { chunk += eof; } } } if (!util.isNullOrUndefined(chunk)) { this.write(chunk); } if (!state.ending) { endWritable(this, callback); } }; // When stream is ready to write, concrete stream implementation should call // this method to inform it. Writable.prototype._readyToWrite = function() { var state = this._writableState; state.ready = true; writeBuffered(this); }; // A chunk of data has been written down to stream. Writable.prototype._onwrite = function() { var state = this._writableState; state.length -= state.writingLength; state.writing = false; state.writingLength = 0; writeBuffered(this); }; // A write call occured after end. function writeAfterEnd(stream, callback) { var err = new Error('write after end'); stream.emit('error', err); if (util.isFunction(callback)) { process.nextTick(callback.bind(undefined, err)); } } function writeOrBuffer(stream, chunk, callback) { var state = stream._writableState; if (util.isString(chunk)) { chunk = new Buffer(chunk); } state.length += chunk.length; if (!state.ready || state.writing || state.buffer.length > 0) { // stream not yet ready or there is pending request to write. // push this request into write queue. state.buffer.push(new WriteReq(chunk, callback)); } else { // here means there is no pending data. write out. doWrite(stream, chunk, callback); } // total length of buffered message exceeded high water mark. if (state.length >= state.highWaterMark) { state.needDrain = true; } return !state.needDrain; } function writeBuffered(stream) { var state = stream._writableState; if (!state.writing) { if (state.buffer.length == 0) { onEmptyBuffer(stream); } else { var req = state.buffer.shift(); doWrite(stream, req.chunk, req.callback); } } } function doWrite(stream, chunk, callback) { var state = stream._writableState; if (state.writing) { return new Error('write during writing'); } // The stream is now writing. state.writing = true; state.writingLength = chunk.length; // Write down the chunk data. stream._write(chunk, callback, stream._onwrite.bind(stream)); } // No more data to write. if this stream is being finishing, emit 'finish'. function onEmptyBuffer(stream) { var state = stream._writableState; if (state.ending) { emitFinish(stream); } else if (state.needDrain) { emitDrain(stream); } } // Writable.prototype.end() was called. register callback for 'finish' event. // After finish writing out buffered data, 'finish' event will be fired. function endWritable(stream, callback) { var state = stream._writableState; state.ending = true; if (callback) { stream.once('finish', callback); } // If nothing left, emit finish event at next tick. if (!state.writing && state.buffer.length == 0) { process.nextTick(emitFinish.bind(undefined, stream)); } } // Emit 'drain' event function emitDrain(stream) { var state = stream._writableState; if (state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // Emit 'finish' event to notify this stream is finished. function emitFinish(stream) { var state = stream._writableState; if (!state.ended) { state.ended = true; stream.emit('finish'); } } module.exports = Writable; iotjs-1.0+715/src/js/timers.js000066400000000000000000000060711371177304000160650ustar00rootroot00000000000000/* 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 util = require('util'); var TIMEOUT_MAX = '2147483647.0' - 0; // 2^31-1 var TIMER_TYPES = { setTimeout: 0, setInterval: 1, setImmediate: 2, }; function Timeout(after) { this.after = after; this.isRepeat = false; this.callback = null; this.handler = null; } native.prototype.handleTimeout = function() { var timeout = this.timeoutObj; // 'this' is native object if (timeout && timeout.callback) { try { timeout.callback(); } catch (e) { timeout.unref(); throw e; } if (!timeout.isRepeat) { timeout.unref(); } } }; Timeout.prototype.ref = function() { var repeat = 0; var handler = new native(); if (this.isRepeat) { repeat = this.after; } handler.timeoutObj = this; this.handler = handler; handler.start(this.after, repeat); }; Timeout.prototype.unref = function() { this.callback = undefined; if (this.handler) { this.handler.timeoutObj = undefined; this.handler.stop(); this.handler = undefined; } }; function timeoutConfigurator(type, callback, delay) { if (!util.isFunction(callback)) { throw new TypeError('Bad arguments: callback must be a Function'); } if (type === TIMER_TYPES.setImmediate) { delay = 0; } else { delay *= 1; if (delay < 1 || delay > TIMEOUT_MAX) { delay = 1; } } var timeout = new Timeout(delay); // set timeout handler. if (arguments.length <= 3) { timeout.callback = callback; } else { var args = Array.prototype.slice.call(arguments, 3); args.splice(0, 0, timeout); timeout.callback = callback.bind.apply(callback, args); } timeout.isRepeat = type == TIMER_TYPES.setInterval; timeout.ref(); return timeout; } exports.setTimeout = timeoutConfigurator.bind(undefined, TIMER_TYPES.setTimeout); exports.setInterval = timeoutConfigurator.bind(undefined, TIMER_TYPES.setInterval); exports.setImmediate = timeoutConfigurator.bind(undefined, TIMER_TYPES.setImmediate); function clearTimeoutBase(timeoutType, timeout) { if (timeout) { if (timeout instanceof Timeout) { timeout.unref(); } else { throw new Error(timeoutType + '() - invalid timeout'); } } } exports.clearTimeout = clearTimeoutBase.bind(undefined, 'clearTimeout'); exports.clearInterval = clearTimeoutBase.bind(undefined, 'clearInterval'); iotjs-1.0+715/src/js/tizen.js000066400000000000000000000077011371177304000157140ustar00rootroot00000000000000/* Copyright 2018-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 Bridge = require('bridge'); var EventEmitter = require('events').EventEmitter; var util = require('util'); var APP_CONTROL_EVENT_TYPE = 'appControl'; var BUNDLE_KEY_OPERATION = '__APP_SVC_OP_TYPE__'; var BUNDLE_KEY_URI = '__APP_SVC_URI__'; var BUNDLE_KEY_MIME = '__APP_SVC_MIME_TYPE__'; var BUNDLE_KEY_LAUNCH_MODE = '__APP_SVC_LAUNCH_MODE__'; var BUNDLE_KEY_CATEGORY = '__APP_SVC_CATEGORY__'; var BUNDLE_KEY_PACKAGE = '__APP_SVC_PKG_NAME__'; var bridge = new Bridge(native.MODULE_NAME); var startsWith = function(searchString, position) { position = position || 0; return this.substr(position, searchString.length) === searchString; }; function ApplicationControl(bundle) { if (!util.isObject(bundle)) { return this; } this.operation = bundle[BUNDLE_KEY_OPERATION]; this.uri = bundle[BUNDLE_KEY_URI]; this.mime = bundle[BUNDLE_KEY_MIME]; this.launch_mode = bundle[BUNDLE_KEY_LAUNCH_MODE]; this.category = bundle[BUNDLE_KEY_CATEGORY]; this.app_id = bundle[BUNDLE_KEY_PACKAGE]; var extra_data = {}; for (var prop in bundle) { if (bundle.hasOwnProperty(prop) && !startsWith.call(prop, '__')) { extra_data[prop] = bundle[prop]; } } this.extra_data = Object.keys(extra_data).length ? extra_data : undefined; return this; } function Bundle(appcontrol) { if (!util.isObject(appcontrol)) { return this; } var bundle = this; if (util.isString(appcontrol.operation)) { bundle[BUNDLE_KEY_OPERATION] = appcontrol.operation; } if (util.isString(appcontrol.uri)) { bundle[BUNDLE_KEY_URI] = appcontrol.uri; } if (util.isString(appcontrol.mime)) { bundle[BUNDLE_KEY_MIME] = appcontrol.mime; } if (util.isString(appcontrol.launch_mode)) { if (appcontrol.launch_mode === 'group' || appcontrol.launch_mode === 'single') { bundle[BUNDLE_KEY_LAUNCH_MODE] = appcontrol.launch_mode; } } if (util.isString(appcontrol.category)) { bundle[BUNDLE_KEY_CATEGORY] = appcontrol.category; } if (util.isString(appcontrol.app_id)) { bundle[BUNDLE_KEY_PACKAGE] = appcontrol.app_id; } var extra_data = appcontrol.extra_data; if (util.isObject(extra_data)) { for (var prop in extra_data) { if (extra_data.hasOwnProperty(prop)) { // a bundle is a dictionary which consists of key and value pairs bundle[prop] = extra_data[prop].toString(); } } } return this; } function on(type, listener) { var callback = listener; if (type === APP_CONTROL_EVENT_TYPE) { // replace callback for application control callback = function(msg) { if (util.isString(msg)) { try { var json = JSON.parse(msg); listener(new ApplicationControl(json)); } catch (e) { return; // ignore msg. data should be a json string } } }; } return EventEmitter.prototype.on.call(this, type, callback); } function launchAppControl(option) { var bundle = new Bundle(option); return 'OK' === bridge.sendSync('launchAppControl', JSON.stringify(bundle)); } var getResPath = function() { return bridge.sendSync('getResPath', ''); }; var getDataPath = function() { return bridge.sendSync('getDataPath', ''); }; module.exports = util.mixin(native, EventEmitter.prototype, { launchAppControl: launchAppControl, getResPath: getResPath, getDataPath: getDataPath, on: on, }); iotjs-1.0+715/src/js/tls.js000066400000000000000000000153401371177304000153630ustar00rootroot00000000000000/* Copyright 2018-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 util = require('util'); var Duplex = require('stream').Duplex; function TLSSocket(socket, options) { if (!(this instanceof TLSSocket)) { return new TLSSocket(socket, options); } if ('_tlsSocket' in socket) { throw Error('Socket already bound'); } this._socket = socket; socket._tlsSocket = this; Duplex.call(this); this.authorized = false; this._socket.on('connect', this.onconnect); this._socket.on('data', this.ondata); this._socket.on('error', this.onerror); this._socket.on('close', this.onclose); if (this._socket instanceof net.Socket) { this._socket.on('finish', this.onfinish); } else { this._socket.on('finish', this.onend); } this._socket.on('end', this.onend); // Native handle var secureContext = options.secureContext; if (!secureContext) { secureContext = createSecureContext(options); } native.TlsInit(this, options, secureContext); this._socketState = socket._socketState; var self = this; if (socket._writableState.ready && !options.isServer) { process.nextTick(function() { self._native_connect(options.servername || options.host || 'localhost'); self._native_read(null); }); } } util.inherits(TLSSocket, Duplex); TLSSocket.prototype._native_read = native.read; TLSSocket.prototype._native_write = native.write; TLSSocket.prototype._native_connect = native.connect; TLSSocket.prototype.connect = function(options, callback) { this._native_connect(options.servername || options.host || 'localhost'); if (util.isFunction(callback)) { this.on('secureConnect', callback); } this._socket.connect(options); }; TLSSocket.prototype._write = function(chunk, callback, onwrite) { chunk = this._native_write(chunk); this._socket.write(chunk, callback); onwrite(); }; TLSSocket.prototype.end = function(data, callback) { Duplex.prototype.end.call(this, data, callback); this._socket.end(); }; TLSSocket.prototype.destroy = function() { this._socket.destroy(); }; TLSSocket.prototype.destroySoon = function() { this._socket.destroySoon(); }; TLSSocket.prototype.onconnect = function() { this._tlsSocket._native_read(null); }; TLSSocket.prototype.encrypted = function() { return true; }; TLSSocket.prototype.address = function() { return this._socket.address(); }; TLSSocket.prototype.localAddress = function() { return this._socket.address().address; }; TLSSocket.prototype.setTimeout = function(msecs, callback) { return this._socket.setTimeout(msecs, callback); }; TLSSocket.prototype.ondata = function(data) { var self = this._tlsSocket; self._native_read(data); }; TLSSocket.prototype.onerror = function(error) { this._tlsSocket.emit('error', error); }; TLSSocket.prototype.onclose = function() { this._tlsSocket.emit('close'); }; TLSSocket.prototype.onfinish = function() { this._tlsSocket.emit('finish'); }; TLSSocket.prototype.onend = function() { this._tlsSocket.emit('end'); }; TLSSocket.prototype.onwrite = function(data) { return this._socket.write(data); }; TLSSocket.prototype.onread = function(chunk) { this.emit('data', chunk); }; TLSSocket.prototype.onhandshakedone = function(error, authorized) { this.authorized = authorized; var server = this._server; if (error) { error = Error('handshake failed'); if (server) { server.emit('tlsClientError', error, this); } else { this.emit('error', error); } this.end(); return; } this._readyToWrite(); if (server) { server.emit('secureConnection', this); } else { this.emit('secureConnect'); } }; function tlsConnectionListener(rawSocket) { var tlsSocket = new TLSSocket(rawSocket, { isServer: true, secureContext: this._secureContext, }); tlsSocket._server = this; } function Server(options, listener) { if (!(this instanceof Server)) { return new Server(options, listener); } this._secureContext = createSecureContext(options); // constructor call net.Server.call(this, options, tlsConnectionListener); if (listener) { this.on('secureConnection', listener); } } util.inherits(Server, net.Server); function createSecureContext(options) { return new native.TlsContext(options); } function createServer(options, secureConnectionListener) { return new Server(options, secureConnectionListener); } function connect(arg0, arg1, arg2, callback) { var options = {}; if (typeof arg0 == 'object') { options = Object.create(arg0, { isServer: { value: false, enumerable: true }, }); options.host = options.host || 'localhost'; options.port = options.port || 443; options.rejectUnauthorized = options.rejectUnauthorized || false; callback = arg1; } else if (typeof arg0 == 'number') { if (typeof arg1 == 'string') { if (typeof arg2 == 'object') { options = Object.create(arg2, { isServer: { value: false, enumerable: true }, }); options.port = arg0; options.host = arg1; options.rejectUnauthorized = options.rejectUnauthorized || false; } else { options = { isServer: false, rejectUnauthorized: false, port: arg0, host: arg1, }; callback = arg2; } } else if (typeof arg1 == 'object') { options = Object.create(arg1, { isServer: { value: false, enumerable: true }, }); options.port = arg0; options.host = options.host || 'localhost'; options.rejectUnauthorized = options.rejectUnauthorized || false; callback = arg2; } else { options = { isServer: false, rejectUnauthorized: false, host: 'localhost', port: arg0, }; callback = arg1; } } var tlsSocket = new TLSSocket(options.socket || new net.Socket(), options); if (tlsSocket._socket instanceof net.Socket) { tlsSocket.connect(options, callback); } else if (util.isFunction(callback)) { tlsSocket.on('secureConnect', callback); } return tlsSocket; } exports.TLSSocket = TLSSocket; exports.Server = Server; exports.createSecureContext = createSecureContext; exports.createServer = createServer; exports.connect = connect; iotjs-1.0+715/src/js/uart.js000066400000000000000000000020051371177304000155260ustar00rootroot00000000000000/* 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 EventEmitter = require('events').EventEmitter; var util = require('util'); util.mixin(native.prototype, EventEmitter.prototype); var uart = { open: function(config, callback) { var uartPort = new native(config, function(err) { callback(err); }); return uartPort; }, openSync: function(config) { return new native(config); }, }; module.exports = uart; iotjs-1.0+715/src/js/util.js000066400000000000000000000114471371177304000155420ustar00rootroot00000000000000/* 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 Buffer = require('buffer'); function isNull(arg) { return arg === null; } function isUndefined(arg) { return arg === undefined; } function isNullOrUndefined(arg) { return arg === null || arg === undefined; } function isNumber(arg) { return typeof arg === 'number'; } function isFinite(arg) { return (arg == 0) || (arg != arg / 2); } function isBoolean(arg) { return typeof arg === 'boolean'; } function isString(arg) { return typeof arg === 'string'; } function isObject(arg) { return typeof arg === 'object' && arg != null; } function isFunction(arg) { return typeof arg === 'function'; } function inherits(ctor, superCtor) { ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true, }, }); } function mixin(target) { if (isNullOrUndefined(target)) { throw new TypeError('target cannot be null or undefined'); } for (var i = 1; i < arguments.length; ++i) { var source = arguments[i]; if (!isNullOrUndefined(source)) { for (var prop in source) { if (source.hasOwnProperty(prop)) { target[prop] = source[prop]; } } } } return target; } function format(s) { var i; if (!isString(s)) { var arrs = []; for (i = 0; i < arguments.length; ++i) { arrs.push(formatValue(arguments[i])); } return arrs.join(' '); } i = 1; var args = arguments; var arg_string; var str = ''; var start = 0; var end = 0; while (end < s.length) { if (s.charAt(end) !== '%') { end++; continue; } str += s.slice(start, end); switch (s.charAt(end + 1)) { case 's': arg_string = String(args[i]); break; case 'd': arg_string = Number(args[i]); break; case 'j': try { arg_string = JSON.stringify(args[i]); } catch (_) { arg_string = '[Circular]'; } break; case '%': str += '%'; start = end = end + 2; continue; default: str = str + '%' + s.charAt(end + 1); start = end = end + 2; continue; } if (i >= args.length) { str = str + '%' + s.charAt(end + 1); } else { i++; str += arg_string; } start = end = end + 2; } str += s.slice(start, end); while (i < args.length) { str += ' ' + formatValue(args[i++]); } return str; } function formatValue(v) { if (v === undefined) { return 'undefined'; } else if (v === null) { return 'null'; } else if (Array.isArray(v)) { return '[' + v.toString() + ']'; } else if (v instanceof Error) { return v.toString(); } else if (typeof v === 'object') { return JSON.stringify(v, null, 2); } else { return v.toString(); } } function stringToNumber(value, default_value) { var num = Number(value); return isNaN(num) ? default_value : num; } function errnoException(err, syscall, original) { var errname = 'error'; // uv.errname(err); var message = syscall + ' ' + errname; if (original) message += ' ' + original; var e = new Error(message); e.code = errname; e.errno = errname; e.syscall = syscall; return e; } function exceptionWithHostPort(err, syscall, address, port, additional) { var details; if (port && port > 0) { details = address + ':' + port; } else { details = address; } if (additional) { details += ' - Local (' + additional + ')'; } var ex = exports.errnoException(err, syscall, details); ex.address = address; if (port) { ex.port = port; } return ex; } exports.isNull = isNull; exports.isUndefined = isUndefined; exports.isNullOrUndefined = isNullOrUndefined; exports.isNumber = isNumber; exports.isBoolean = isBoolean; exports.isString = isString; exports.isObject = isObject; exports.isFinite = isFinite; exports.isFunction = isFunction; exports.isBuffer = Buffer.isBuffer; exports.isArray = Array.isArray; exports.exceptionWithHostPort = exceptionWithHostPort; exports.errnoException = errnoException; exports.stringToNumber = stringToNumber; exports.inherits = inherits; exports.mixin = mixin; exports.format = format; iotjs-1.0+715/src/js/websocket.js000066400000000000000000000271041371177304000165500ustar00rootroot00000000000000/* Copyright 2018-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 util = require('util'); var EventEmitter = require('events').EventEmitter; var tls; try { tls = require('tls'); } catch (e) { // tls remains undefined; } util.inherits(Websocket, EventEmitter); util.inherits(WebsocketClient, EventEmitter); util.inherits(Server, EventEmitter); function WebSocketHandle(client) { this.client = client; this.pings = []; this.connected = false; native.wsInit(this); } function Websocket(options) { if (!(this instanceof Websocket)) { return new Websocket(options); } EventEmitter.call(this); this._firstMessage = true; this._handle = new WebSocketHandle(this); this._secure = false; } function WebsocketClient(socket, handle) { if (!(this instanceof WebsocketClient)) { return new WebsocketClient(socket, handle); } if ((tls && (socket instanceof tls.TLSSocket)) || (socket instanceof net.Socket)) { this._socket = socket; this.readyState = 'CONNECTING'; } else { this._firstMessage = true; } this._handle = handle; EventEmitter.call(this); } function ServerHandle() { this.clients = []; native.wsInit(this); } function connectionListener(socket) { var ws = new WebsocketClient(socket, this._serverHandle); this._serverHandle.clients.push(ws); var self = this; ws._socket.on('data', function(data) { if (ws.readyState === 'CONNECTING') { parseServerHandshakeData(data, ws, self); } else if (ws.readyState === 'OPEN') { self._serverHandle.ondata(data, ws); } }); } function parseServerHandshakeData(data, client, server) { data = data.toString(); var res = data.split('\r\n'); var method = res[0].split(' '); // All header keys are converted to lower case // to ease the processing of the values. // Based on the HTTP/1.1 RFC (https://tools.ietf.org/html/rfc7230#section-3.2) // this conversion is ok as the header field names are case-insensitive. var headers = { 'connection': '', 'upgrade': '', 'host': '', 'sec-websocket-key': '', 'sec-websocket-version': -1, }; for (var i = 1; i < res.length; i++) { var temp = res[i].split(': '); headers[temp[0].toLowerCase()] = temp[1]; } var response = ''; if (method[0] === 'GET' && method[2] === 'HTTP/1.1' && method[1] === server.path && headers['connection'].toLowerCase().indexOf('upgrade') !== -1 && headers['upgrade'].toLowerCase() === 'websocket' && headers['sec-websocket-version'] === '13') { response = native.ReceiveHandshakeData( headers['sec-websocket-key'] ).toString(); client.readyState = 'OPEN'; client._socket.write(response); server.emit('open', client); } else { response = method[2] + ' 400 Bad Request\r\nConnection: Closed\r\n\r\n'; client._socket.write(response); } } function Server(options, listener) { if (!(this instanceof Server)) { return new Server(options); } EventEmitter.call(this); var emit_type = 'connection'; this._netserver = null; if (options.server) { if (tls && (options.server instanceof tls.Server)) { this._netserver = options.server; emit_type = 'secureConnection'; } else if (options.server instanceof net.Server) { this._netserver = options.server; } } else if (options.port) { if (options.secure == true) { if (!tls) { throw new Error('TLS module is required to create a secure server.'); } this._netserver = tls.createServer(options); emit_type = 'secureConnection'; } else { this._netserver = net.createServer(options); } this._netserver.listen(options.port); } else { throw new Error('One of port or server must be provided as option'); } this._netserver.path = options.path || '/'; this._netserver.on('error', this.onError); this._netserver.on(emit_type, connectionListener); this._netserver._serverHandle = new ServerHandle(); if (listener) { this._netserver.on('open', listener); } this.options = options; } ServerHandle.prototype.ondata = function(data, client) { native.wsReceive(this, data, client); }; ServerHandle.prototype.onmessage = function(msg, client) { client.emit('message', msg); }; ServerHandle.prototype.pong = function(msg, client) { client.emit('ping', msg); this.sendFrame(native.ping(false, msg, true), client); }; ServerHandle.prototype.onError = function(err, client) { client.emit('error', err); }; ServerHandle.prototype.sendFrame = function(msg, client) { if (client._socket._socketState.writable) { client._socket.write(msg); } else { if (this.clients.indexOf(client) > -1) { this.onError('Underlying socket', client); } } }; ServerHandle.prototype.onclose = function(msg, client) { client.readyState = 'CLOSING'; if (msg) { // If there is msg we know the following: // 4 characters status code (1000-4999) // rest is msg payload var msg_str = msg.toString(); msg = { code: msg_str.substr(0, 4), reason: msg_str.substr(4, msg_str.length), }; } else { msg = {}; } client.close(msg); }; Server.prototype.close = function(reason, code) { var msg = { code: code || 1000, reason: reason || 'Connection successfully closed', }; var i = 0; while (this._netserver._serverHandle.clients.length != 0) { this._netserver._serverHandle.clients[i].readyState = 'CLOSING'; this._netserver._serverHandle.clients[i].close(msg); } this._netserver.close(); this.emit('close', msg); }; Server.prototype.broadcast = function(msg, options) { if (options) { var mask = options.mask || true; var binary = options.binary || false; var compress = options.compress; if (compress) { // Currently not supported, needs zlib this.onError('Compression is not supported'); } } var buff = native.send(msg, binary, mask, compress); var self = this; this._netserver._serverHandle.clients.forEach(function each(client) { if (client.readyState === 'OPEN') { self._netserver._serverHandle.sendFrame(buff, client); } }); }; Server.prototype.address = function() { return this._netserver.address(); }; Server.prototype.onError = function(err) { this.emit('error', err); }; WebsocketClient.prototype.send = function(message, opts) { if (opts) { var mask = opts.mask; var binary = opts.binary; var compress = opts.compress; if (compress) { // Currently not supported, needs zlib this._handle.onError('Compression is not supported'); } } var buff = native.send(message, binary, mask, compress); if (buff) { this._handle.sendFrame(buff, this); } }; WebsocketClient.prototype.close = function(msg) { msg = { reason: msg.reason || 'Connection successfully closed', code: msg.code || 1000, }; var buff = native.close(msg.reason, msg.code); this._handle.sendFrame(buff, this); this.emit('close', msg); this._socket.end(); var id = this._handle.clients.indexOf(this); this._handle.clients.splice(id, 1); }; WebsocketClient.prototype.onError = function(err) { this.emit('error', err); }; WebSocketHandle.prototype.onmessage = function(msg) { this.client.emit('message', msg); }; WebSocketHandle.prototype.ondata = function(data) { native.wsReceive(this, data, this); }; WebSocketHandle.prototype.onhandshakedone = function(remaining) { this.client.emit('open'); this.client._firstMessage = false; if (remaining) { this.ondata(remaining); } }; WebSocketHandle.prototype.onError = function(err) { this.client.emit('error', err); }; WebSocketHandle.prototype.onclose = function(msg) { if (msg) { // If there is msg we know the following: // 4 characters status code (1000-4999) // rest is msg payload var msg_str = msg.toString(); msg = { code: msg_str.substr(0, 4), reason: msg_str.substr(4, msg_str.length), }; } else { msg = {}; } this.client.emit('close', msg); for (var i = 0; i < this.pings.length; i++) { clearInterval(this.pings[i].timer); } this.client._socket.end(); }; WebSocketHandle.prototype.sendFrame = function(msg, cb) { if (this.connected) { if (typeof cb == 'function') { this.client._socket.write(msg, cb); } else { this.client._socket.write(msg); } } else { this.onError('Underlying socket connection is closed'); } }; WebSocketHandle.prototype.pong = function(msg) { this.client._socket.write(native.ping(false, msg, true)); }; WebSocketHandle.prototype.onpingresp = function(msg) { for (var i = 0; i < this.pings.length; i++) { if (this.pings[i].id == msg) { clearInterval(this.pings[i].timer); this.pings[i].callback(msg); this.pings.splice(i, 1); return; } } }; function sendHandshake(jsref, host, path) { return native.prepareHandshake(jsref, host, path); } Websocket.prototype.connect = function(url, port, path, callback) { var host = url.toString() || '127.0.0.1'; path = path || '/'; var emit_type = 'connect'; if (host.substr(0, 3) == 'wss') { this._secure = true; if (!tls) { this._handle.onError('TLS module was not found!'); } port = port || 443; host = host.substr(6); this._socket = tls.connect(port, host); emit_type = 'secureConnect'; } else if (host.substr(0, 2) == 'ws') { port = port || 80; this._socket = new net.Socket(); host = host.substr(5); } else { port = port || 80; this._socket = new net.Socket(); } if (typeof callback == 'function') { this.on('open', callback); } var self = this; this._socket.on(emit_type, function() { self._handle.connected = true; self._socket.write(sendHandshake(self._handle, host, path)); }); this._socket.on('end', function() { self._handle.connected = false; }); if (emit_type == 'connect') { this._socket.connect(port, host); } this._socket.on('data', function(data) { if (self._firstMessage) { var remaining_data = native.parseHandshakeData(data, self._handle); self._handle.onhandshakedone(remaining_data); } else { self._handle.ondata(data); } }); }; Websocket.prototype.close = function(message, code, cb) { this._handle.sendFrame(native.close(message, code), cb); }; Websocket.prototype.ping = function(message, mask, cb) { var self = this; var obj = { id: message, callback: cb, timer: setTimeout(function() { self.close('Ping timeout limit exceeded', 1002); }, 30000), }; this._handle.pings.push(obj); this._handle.sendFrame(native.ping(true, message, mask)); }; Websocket.prototype.send = function(message, opts, cb) { if (opts) { var mask = opts.mask; var binary = opts.binary; var compress = opts.compress; if (compress) { // Currently not supported, needs zlib this._handle.onError('Compression is not supported'); } } var buff = native.send(message, binary, mask, compress); if (buff) { this._handle.sendFrame(buff, cb); } }; exports.Websocket = Websocket; exports.Server = Server; iotjs-1.0+715/src/modules.json000066400000000000000000000314711371177304000161550ustar00rootroot00000000000000{ "modules": { "iotjs_basic_modules": { "require": ["assert", "dns", "http", "net", "stream"] }, "iotjs_core_modules": { "require": ["buffer", "console", "events", "fs", "module", "process", "timers"] }, "adc": { "platforms": { "linux": { "native_files": ["modules/linux/iotjs_module_adc-linux.c"] }, "nuttx": { "native_files": ["modules/nuttx/iotjs_module_adc-nuttx.c"] }, "tizenrt": { "native_files": ["modules/tizenrt/iotjs_module_adc-tizenrt.c"] }, "undefined": { "native_files": ["modules/iotjs_module_adc.c"] } }, "native_files": ["modules/iotjs_module_adc.c", "modules/iotjs_module_periph_common.c"], "init": "iotjs_init_adc", "js_file": "js/adc.js" }, "assert": { "js_file": "js/assert.js", "require": ["util"] }, "ble": { "js_file": "js/ble.js", "require": ["ble_hci_socket", "ble_characteristic", "ble_descriptor", "ble_hci_socket_acl_stream", "ble_hci_socket_bindings", "ble_hci_socket_crypto", "ble_hci_socket_gap", "ble_hci_socket_gatt", "ble_hci_socket_hci", "ble_hci_socket_hci_status", "ble_hci_socket_mgmt", "ble_hci_socket_smp", "ble_primary_service", "ble_uuid_util"] }, "ble_characteristic": { "js_file": "js/ble_characteristic.js", "require": ["events", "util"] }, "ble_descriptor": { "js_file": "js/ble_descriptor.js", "require": ["console"] }, "ble_hci_socket_acl_stream": { "js_file": "js/ble_hci_socket_acl_stream.js", "require": ["events", "util"] }, "ble_hci_socket_bindings": { "js_file": "js/ble_hci_socket_bindings.js", "require": ["console", "events", "util", "ble_hci_socket_acl_stream", "ble_hci_socket_hci", "ble_hci_socket_gap", "ble_hci_socket_gatt"] }, "ble_hci_socket_crypto": { "js_file": "js/ble_hci_socket_crypto.js" }, "ble_hci_socket_gap": { "js_file": "js/ble_hci_socket_gap.js", "require": ["console", "events", "util", "ble_hci_socket_hci", "ble_uuid_util"] }, "ble_hci_socket_gatt": { "js_file": "js/ble_hci_socket_gatt.js", "require": ["console", "events", "util", "ble_uuid_util"] }, "ble_hci_socket_hci": { "js_file": "js/ble_hci_socket_hci.js", "require": ["console", "events", "util", "ble_uuid_util", "ble_hci_socket"] }, "ble_hci_socket_hci_status": { "js_file": "js/ble_hci_socket_hci_status.js" }, "ble_hci_socket_mgmt": { "js_file": "js/ble_hci_socket_mgmt.js", "require": ["console", "events", "util", "ble_hci_socket"] }, "ble_hci_socket_smp": { "js_file": "js/ble_hci_socket_smp.js", "require": ["events", "util", "ble_hci_socket_crypto", "ble_hci_socket_mgmt"] }, "ble_primary_service": { "js_file": "js/ble_primary_service.js", "require": ["events", "util", "ble_uuid_util"] }, "ble_uuid_util": { "js_file": "js/ble_uuid_util.js" }, "ble_hci_socket": { "platforms": { "linux": { "native_files": ["modules/linux/iotjs_module_blehcisocket-linux.c"] }, "nuttx": { "native_files": ["modules/nuttx/iotjs_module_blehcisocket-nuttx.c"] } }, "native_files": ["modules/iotjs_module_blehcisocket.c"], "init": "iotjs_init_blehcisocket", "js_file": "js/ble_hci_socket.js", "require": ["events"] }, "buffer": { "native_files": ["modules/iotjs_module_buffer.c"], "init": "iotjs_init_buffer", "js_file": "js/buffer.js", "require": ["util"] }, "console": { "native_files": ["modules/iotjs_module_console.c"], "init": "iotjs_init_console", "js_file": "js/console.js", "require": ["util"] }, "constants": { "native_files": ["modules/iotjs_module_constants.c"], "init": "iotjs_init_constants" }, "crypto": { "native_files": ["modules/iotjs_module_crypto.c"], "init": "iotjs_init_crypto", "js_file": "js/crypto.js" }, "dgram": { "js_file": "js/dgram.js", "require": ["events", "udp", "util"] }, "dns": { "native_files": ["modules/iotjs_module_dns.c"], "init": "iotjs_init_dns", "js_file": "js/dns.js", "require": ["util"] }, "events": { "js_file": "js/events.js", "require": ["util"] }, "fs": { "native_files": ["modules/iotjs_module_fs.c"], "init": "iotjs_init_fs", "js_file": "js/fs.js", "require": ["constants", "util"] }, "gpio": { "platforms": { "linux": { "native_files": ["modules/linux/iotjs_module_gpio-linux.c"] }, "mocklinux": { "native_files": ["modules/mock/iotjs_module_gpio-mock.c"] }, "nuttx": { "native_files": ["modules/nuttx/iotjs_module_gpio-nuttx.c"] }, "tizen": { "native_files": ["modules/tizen/iotjs_module_gpio-tizen.c"] }, "tizenrt": { "native_files": ["modules/tizenrt/iotjs_module_gpio-tizenrt.c"] } }, "native_files": ["modules/iotjs_module_gpio.c", "modules/iotjs_module_periph_common.c"], "init": "iotjs_init_gpio", "js_file": "js/gpio.js" }, "http": { "js_file": "js/http.js", "require": ["http_client", "http_common", "http_incoming", "http_outgoing", "http_server", "http_parser"] }, "http_client": { "js_file": "js/http_client.js", "require": ["http_common", "http_outgoing", "http_parser", "net", "util"] }, "http_common": { "js_file": "js/http_common.js", "require": ["http_incoming", "http_parser"] }, "http_incoming": { "js_file": "js/http_incoming.js", "require": ["stream", "util"] }, "http_outgoing": { "js_file": "js/http_outgoing.js", "require": ["stream", "util"] }, "http_server": { "js_file": "js/http_server.js", "require": ["http_common", "http_outgoing", "net", "util"] }, "http_signature": { "js_file": "js/http_signature.js", "require": ["tls", "crypto"] }, "http_parser": { "native_files": ["modules/iotjs_module_http_parser.c"], "init": "iotjs_init_http_parser" }, "https": { "js_file": "js/https.js", "require": ["http_client", "http_parser", "http_server", "net", "tls"] }, "i2c": { "platforms": { "linux": { "native_files": ["modules/linux/iotjs_module_i2c-linux.c"] }, "mocklinux": { "native_files": ["modules/mock/iotjs_module_i2c-mock.c"] }, "nuttx": { "native_files": ["modules/nuttx/iotjs_module_i2c-nuttx.c"] }, "tizen": { "native_files": ["modules/tizen/iotjs_module_i2c-tizen.c"] }, "tizenrt": { "native_files": ["modules/tizenrt/iotjs_module_i2c-tizenrt.c"] } }, "native_files": ["modules/iotjs_module_i2c.c", "modules/iotjs_module_periph_common.c"], "init": "iotjs_init_i2c", "js_file": "js/i2c.js" }, "module": { "js_file": "js/module.js", "require": ["fs"] }, "mqtt": { "js_file": "js/mqtt.js", "require": ["events", "util", "url"], "native_files": ["modules/iotjs_module_mqtt.c"], "init": "iotjs_init_mqtt" }, "napi": { "native_files": ["modules/iotjs_module_dynamicloader.c", "napi/node_api.c", "napi/node_api_async.c", "napi/node_api_env.c", "napi/node_api_function.c", "napi/node_api_lifetime.c", "napi/node_api_module.c", "napi/node_api_object_wrap.c", "napi/node_api_property.c", "napi/node_api_value.c"], "init": "iotjs_init_dynamicloader" }, "net": { "js_file": "js/net.js", "require": ["assert", "events", "stream", "tcp", "util"] }, "process": { "native_files": ["modules/iotjs_module_process.c"], "init": "iotjs_init_process" }, "pwm": { "platforms": { "linux": { "native_files": ["modules/linux/iotjs_module_pwm-linux.c"] }, "mocklinux": { "native_files": ["modules/mock/iotjs_module_pwm-mock.c"] }, "nuttx": { "native_files": ["modules/nuttx/iotjs_module_pwm-nuttx.c"] }, "tizen": { "native_files": ["modules/tizen/iotjs_module_pwm-tizen.c"] }, "tizenrt": { "native_files": ["modules/tizenrt/iotjs_module_pwm-tizenrt.c"] } }, "native_files": ["modules/iotjs_module_pwm.c", "modules/iotjs_module_periph_common.c"], "init": "iotjs_init_pwm", "js_file": "js/pwm.js" }, "spi": { "platforms": { "linux": { "native_files": ["modules/linux/iotjs_module_spi-linux.c"] }, "nuttx": { "native_files": ["modules/nuttx/iotjs_module_spi-nuttx.c"] }, "tizen": { "native_files": ["modules/tizen/iotjs_module_spi-tizen.c"] }, "tizenrt": { "native_files": ["modules/tizenrt/iotjs_module_spi-tizenrt.c"] } }, "native_files": ["modules/iotjs_module_spi.c", "modules/iotjs_module_periph_common.c"], "init": "iotjs_init_spi", "js_file": "js/spi.js" }, "stm32f4dis": { "platforms": { "nuttx": { "native_files": ["modules/nuttx/iotjs_module_stm32f4dis-nuttx.c"] } }, "native_files": ["modules/iotjs_module_stm32f4dis.c"], "init": "iotjs_init_stm32f4dis" }, "stm32f7nucleo": { "platforms": { "nuttx": { "native_files": ["modules/nuttx/iotjs_module_stm32f7nucleo-nuttx.c"] } }, "native_files": ["modules/iotjs_module_stm32f7nucleo.c"], "init": "iotjs_init_stm32f7nucleo" }, "stream": { "js_file": "js/stream.js", "require": ["stream_duplex", "stream_internal", "stream_readable", "stream_writable", "util"] }, "stream_duplex": { "js_file": "js/stream_duplex.js", "require": ["stream_readable", "stream_writable", "util"] }, "stream_internal": { "js_file": "js/stream_internal.js", "require": ["events", "util"] }, "stream_readable": { "js_file": "js/stream_readable.js", "require": ["assert", "util"] }, "stream_writable": { "js_file": "js/stream_writable.js", "require": ["util"] }, "tcp": { "native_files": ["modules/iotjs_module_tcp.c"], "init": "iotjs_init_tcp" }, "timers": { "native_files": ["modules/iotjs_module_timer.c"], "init": "iotjs_init_timer", "js_file": "js/timers.js", "require": ["util"] }, "tls": { "native_files": ["modules/iotjs_module_tls.c"], "init": "iotjs_init_tls", "js_file": "js/tls.js", "cmakefile": "../cmake/mbedtls.cmake", "require": ["net", "util"] }, "uart": { "platforms": { "linux": { "native_files": ["modules/linux/iotjs_module_uart-linux.c"] }, "nuttx": { "native_files": ["modules/nuttx/iotjs_module_uart-nuttx.c"] }, "tizen": { "native_files": ["modules/tizen/iotjs_module_uart-tizen.c"] }, "tizenrt": { "native_files": ["modules/tizenrt/iotjs_module_uart-tizenrt.c"] } }, "native_files": ["modules/iotjs_module_uart.c", "modules/iotjs_module_periph_common.c"], "init": "iotjs_init_uart", "js_file": "js/uart.js", "require": ["events"] }, "udp": { "native_files": ["modules/iotjs_module_udp.c"], "init": "iotjs_init_udp" }, "util": { "js_file": "js/util.js" }, "websocket": { "native_files": ["modules/iotjs_module_websocket.h", "modules/iotjs_module_websocket.c"], "init": "iotjs_init_websocket", "js_file": "js/websocket.js", "require": ["crypto", "events", "net", "util"] }, "bridge": { "native_files": ["modules/iotjs_module_bridge.c"], "init": "iotjs_init_bridge", "js_file": "js/bridge.js" }, "tizen": { "platforms": { "tizen": { "native_files": ["modules/tizen/iotjs_module_tizen-tizen.c"] } }, "native_files": ["modules/iotjs_module_tizen.c"], "init": "iotjs_init_tizen", "js_file": "js/tizen.js", "require": ["bridge", "events", "util"] } } } iotjs-1.0+715/src/modules/000077500000000000000000000000001371177304000152545ustar00rootroot00000000000000iotjs-1.0+715/src/modules/iotjs_module_adc.c000066400000000000000000000103211371177304000207210ustar00rootroot00000000000000/* 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_adc.h" #include "iotjs_uv_request.h" IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(adc); IOTJS_DEFINE_PERIPH_CREATE_FUNCTION(adc); static void iotjs_adc_destroy(iotjs_adc_t* adc) { iotjs_adc_destroy_platform_data(adc->platform_data); IOTJS_RELEASE(adc); } static void adc_worker(uv_work_t* work_req) { iotjs_periph_data_t* worker_data = (iotjs_periph_data_t*)IOTJS_UV_REQUEST_EXTRA_DATA(work_req); iotjs_adc_t* adc = (iotjs_adc_t*)worker_data->data; switch (worker_data->op) { case kAdcOpOpen: worker_data->result = iotjs_adc_open(adc); break; case kAdcOpRead: worker_data->result = iotjs_adc_read(adc); break; case kAdcOpClose: worker_data->result = iotjs_adc_close(adc); break; default: IOTJS_ASSERT(!"Invalid Adc Operation"); } } JS_FUNCTION(adc_constructor) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, object); DJS_CHECK_ARG_IF_EXIST(1, function); // Create ADC object const jerry_value_t jadc = JS_GET_THIS(); iotjs_adc_t* adc = adc_create(jadc); void* adc_native = NULL; IOTJS_ASSERT(jerry_get_object_native_pointer(jadc, &adc_native, &this_module_native_info) && adc == adc_native); jerry_value_t jconfig; JS_GET_REQUIRED_ARG_VALUE(0, jconfig, IOTJS_MAGIC_STRING_CONFIG, object); jerry_value_t config_res = iotjs_adc_set_platform_config(adc, jconfig); if (jerry_value_is_error(config_res)) { return config_res; } IOTJS_ASSERT(jerry_value_is_undefined(config_res)); jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); // If the callback doesn't exist, it is completed synchronously. // Otherwise, it will be executed asynchronously. if (!jerry_value_is_null(jcallback)) { iotjs_periph_call_async(adc, jcallback, kAdcOpOpen, adc_worker); } else if (!iotjs_adc_open(adc)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kAdcOpOpen)); } return jerry_create_undefined(); } JS_FUNCTION(adc_read) { JS_DECLARE_THIS_PTR(adc, adc); DJS_CHECK_ARG_IF_EXIST(0, function); iotjs_periph_call_async(adc, JS_GET_ARG_IF_EXIST(0, function), kAdcOpRead, adc_worker); return jerry_create_undefined(); } JS_FUNCTION(adc_read_sync) { JS_DECLARE_THIS_PTR(adc, adc); if (!iotjs_adc_read(adc)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kAdcOpRead)); } return jerry_create_number(adc->value); } JS_FUNCTION(adc_close) { JS_DECLARE_THIS_PTR(adc, adc); DJS_CHECK_ARG_IF_EXIST(0, function); iotjs_periph_call_async(adc, JS_GET_ARG_IF_EXIST(0, function), kAdcOpClose, adc_worker); return jerry_create_undefined(); } JS_FUNCTION(adc_close_sync) { JS_DECLARE_THIS_PTR(adc, adc); bool ret = iotjs_adc_close(adc); if (!ret) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kAdcOpClose)); } return jerry_create_undefined(); } jerry_value_t iotjs_init_adc(void) { jerry_value_t jadc_cons = jerry_create_external_function(adc_constructor); jerry_value_t jprototype = jerry_create_object(); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_READ, adc_read); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_READSYNC, adc_read_sync); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_CLOSE, adc_close); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_CLOSESYNC, adc_close_sync); iotjs_jval_set_property_jval(jadc_cons, IOTJS_MAGIC_STRING_PROTOTYPE, jprototype); jerry_release_value(jprototype); return jadc_cons; } iotjs-1.0+715/src/modules/iotjs_module_adc.h000066400000000000000000000031201371177304000207250ustar00rootroot00000000000000/* 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_ADC_H #define IOTJS_MODULE_ADC_H #include "iotjs_def.h" #include "iotjs_module_periph_common.h" // Forward declaration of platform data. These are only used by platform code. // Generic ADC module never dereferences platform data pointer. typedef struct iotjs_adc_platform_data_s iotjs_adc_platform_data_t; typedef struct { jerry_value_t jobject; iotjs_adc_platform_data_t* platform_data; int32_t value; } iotjs_adc_t; bool iotjs_adc_read(iotjs_adc_t* adc); bool iotjs_adc_close(iotjs_adc_t* adc); bool iotjs_adc_open(iotjs_adc_t* adc); // Platform-related functions; they are implemented // by platform code (i.e.: linux, nuttx, tizen). void iotjs_adc_create_platform_data(iotjs_adc_t* adc); void iotjs_adc_destroy_platform_data(iotjs_adc_platform_data_t* platform_data); jerry_value_t iotjs_adc_set_platform_config(iotjs_adc_t* adc, const jerry_value_t jconfig); #endif /* IOTJS_MODULE_ADC_H */ iotjs-1.0+715/src/modules/iotjs_module_blehcisocket.c000066400000000000000000000136571371177304000226500ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ #include "iotjs_def.h" #include "iotjs_module_blehcisocket.h" #include "iotjs_module_buffer.h" #include #include #include #define THIS iotjs_blehcisocket_t* blehcisocket IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(blehcisocket); iotjs_blehcisocket_t* iotjs_blehcisocket_create(jerry_value_t jble) { iotjs_blehcisocket_t* blehcisocket = IOTJS_ALLOC(iotjs_blehcisocket_t); blehcisocket->jobject = jble; jerry_set_object_native_pointer(jble, blehcisocket, &this_module_native_info); iotjs_blehcisocket_initialize(blehcisocket); return blehcisocket; } static void iotjs_blehcisocket_destroy(iotjs_blehcisocket_t* blehcisocket) { iotjs_blehcisocket_close(blehcisocket); IOTJS_RELEASE(blehcisocket); } JS_FUNCTION(start) { JS_DECLARE_THIS_PTR(blehcisocket, blehcisocket); iotjs_blehcisocket_start(blehcisocket); return jerry_create_undefined(); } JS_FUNCTION(bind_raw) { JS_DECLARE_THIS_PTR(blehcisocket, blehcisocket); DJS_CHECK(jargc >= 1); int devId = 0; int* pDevId = NULL; if (jerry_value_is_number(jargv[0])) { devId = iotjs_jval_as_number(jargv[0]); pDevId = &devId; } int ret = iotjs_blehcisocket_bindRaw(blehcisocket, pDevId); return jerry_create_number(ret); } JS_FUNCTION(bind_user) { JS_DECLARE_THIS_PTR(blehcisocket, blehcisocket); DJS_CHECK_ARGS(1, number); int devId = JS_GET_ARG(0, number); int* pDevId = &devId; int ret = iotjs_blehcisocket_bindUser(blehcisocket, pDevId); return jerry_create_number(ret); } JS_FUNCTION(bind_control) { JS_DECLARE_THIS_PTR(blehcisocket, blehcisocket); iotjs_blehcisocket_bindControl(blehcisocket); return jerry_create_undefined(); } JS_FUNCTION(is_dev_up) { JS_DECLARE_THIS_PTR(blehcisocket, blehcisocket); bool ret = iotjs_blehcisocket_isDevUp(blehcisocket); return jerry_create_boolean(ret); } JS_FUNCTION(set_filter) { JS_DECLARE_THIS_PTR(blehcisocket, blehcisocket); DJS_CHECK_ARGS(1, object); iotjs_bufferwrap_t* buffer = iotjs_bufferwrap_from_jbuffer(JS_GET_ARG(0, object)); iotjs_blehcisocket_setFilter(blehcisocket, buffer->buffer, iotjs_bufferwrap_length(buffer)); return jerry_create_undefined(); } JS_FUNCTION(stop) { JS_DECLARE_THIS_PTR(blehcisocket, blehcisocket); iotjs_blehcisocket_stop(blehcisocket); return jerry_create_undefined(); } JS_FUNCTION(write) { JS_DECLARE_THIS_PTR(blehcisocket, blehcisocket); DJS_CHECK_ARGS(1, object); iotjs_bufferwrap_t* buffer = iotjs_bufferwrap_from_jbuffer(JS_GET_ARG(0, object)); iotjs_blehcisocket_write(blehcisocket, buffer->buffer, iotjs_bufferwrap_length(buffer)); return jerry_create_undefined(); } JS_FUNCTION(blehcisocket_cons) { DJS_CHECK_THIS(); // Create object jerry_value_t jblehcisocket = JS_GET_THIS(); iotjs_blehcisocket_t* blehcisocket = iotjs_blehcisocket_create(jblehcisocket); void* blehcisocket_native = NULL; IOTJS_ASSERT(jerry_get_object_native_pointer(jblehcisocket, &blehcisocket_native, &this_module_native_info) && blehcisocket == blehcisocket_native); return jerry_create_undefined(); } jerry_value_t iotjs_init_blehcisocket(void) { jerry_value_t jblehcisocketCons = jerry_create_external_function(blehcisocket_cons); jerry_value_t prototype = jerry_create_object(); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_START, start); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_BINDRAW, bind_raw); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_BINDUSER, bind_user); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_BINDCONTROL, bind_control); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_ISDEVUP, is_dev_up); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_SETFILTER, set_filter); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_STOP, stop); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_WRITE, write); iotjs_jval_set_property_jval(jblehcisocketCons, IOTJS_MAGIC_STRING_PROTOTYPE, prototype); jerry_release_value(prototype); return jblehcisocketCons; } iotjs-1.0+715/src/modules/iotjs_module_blehcisocket.h000066400000000000000000000071311371177304000226430ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ #ifndef IOTJS_MODULE_BLE_HCI_SOCKET_H #define IOTJS_MODULE_BLE_HCI_SOCKET_H #include "iotjs_def.h" typedef struct { jerry_value_t jobject; int _mode; int _socket; int _devId; uv_poll_t _pollHandle; int _l2sockets[1024]; int _l2socketCount; uint8_t _address[6]; uint8_t _addressType; } iotjs_blehcisocket_t; iotjs_blehcisocket_t* iotjs_blehcisocket_create(jerry_value_t jble); void iotjs_blehcisocket_initialize(iotjs_blehcisocket_t* iotjs_blehcisocket); void iotjs_blehcisocket_close(iotjs_blehcisocket_t* iotjs_blehcisocket); void iotjs_blehcisocket_start(iotjs_blehcisocket_t* iotjs_blehcisocket); int iotjs_blehcisocket_bindRaw(iotjs_blehcisocket_t* iotjs_blehcisocket, int* devId); int iotjs_blehcisocket_bindUser(iotjs_blehcisocket_t* iotjs_blehcisocket, int* devId); void iotjs_blehcisocket_bindControl(iotjs_blehcisocket_t* iotjs_blehcisocket); bool iotjs_blehcisocket_isDevUp(iotjs_blehcisocket_t* iotjs_blehcisocket); void iotjs_blehcisocket_setFilter(iotjs_blehcisocket_t* iotjs_blehcisocket, char* data, size_t length); void iotjs_blehcisocket_poll(iotjs_blehcisocket_t* iotjs_blehcisocket); void iotjs_blehcisocket_stop(iotjs_blehcisocket_t* iotjs_blehcisocket); void iotjs_blehcisocket_write(iotjs_blehcisocket_t* iotjs_blehcisocket, char* data, size_t length); void iotjs_blehcisocket_emitErrnoError( iotjs_blehcisocket_t* iotjs_blehcisocket); int iotjs_blehcisocket_devIdFor(iotjs_blehcisocket_t* iotjs_blehcisocket, int* pDevId, bool isUp); int iotjs_blehcisocket_kernelDisconnectWorkArounds( iotjs_blehcisocket_t* iotjs_blehcisocket, int length, char* data); void iotjs_blehcisocket_poll_cb(uv_poll_t* handle, int status, int events); #endif /* IOTJS_MODULE_BLE_HCI_SOCKET_H */ iotjs-1.0+715/src/modules/iotjs_module_bridge.c000066400000000000000000000333771371177304000214460ustar00rootroot00000000000000/* Copyright 2018-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_bridge.h" #include typedef enum { CALL_STATUS_ERROR = 0, CALL_STATUS_INIT, CALL_STATUS_CALLED, CALL_STATUS_SETMSG, } iotjs_bridge_status_t; typedef struct _iotjs_bridge_object_t iotjs_bridge_object_t; typedef struct { jerry_value_t jobject; jerry_value_t jcallback; uv_mutex_t call_lock; uv_work_t req; uv_async_t* async; iotjs_string_t module; iotjs_string_t command; iotjs_string_t message; iotjs_string_t ret_msg; iotjs_bridge_status_t status; iotjs_bridge_object_t* bridgeobj; } iotjs_bridge_call_t; struct _iotjs_bridge_object_t { jerry_value_t jobject; iotjs_bridge_call_t** calls; size_t calls_alloc; // allocated size of calls }; typedef struct { char* module_name; iotjs_bridge_func callback; } relation_info_t; static relation_info_t* g_module_list = 0; static unsigned int g_module_count = 0; IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(bridge_object); static unsigned int iotjs_bridge_init() { if (g_module_list == 0) { g_module_list = (relation_info_t*)iotjs_buffer_allocate( sizeof(relation_info_t) * iotjs_module_count); IOTJS_ASSERT(g_module_list); } return iotjs_module_count; } int iotjs_bridge_register(char* module_name, iotjs_bridge_func callback) { int empty_slot = -1; iotjs_bridge_init(); for (int i = 0; i < (int)iotjs_module_count; i++) { if (g_module_list[i].module_name == 0) { if (empty_slot == -1) empty_slot = i; } else { if (strncmp(g_module_list[i].module_name, module_name, strlen(module_name)) == 0) { return i; } } } if (empty_slot != -1) { g_module_list[empty_slot].module_name = iotjs_buffer_allocate(strlen(module_name) + 1); IOTJS_ASSERT(g_module_list[empty_slot].module_name); strncpy(g_module_list[empty_slot].module_name, module_name, strlen(module_name)); g_module_list[empty_slot].callback = callback; g_module_count++; } return empty_slot; } static int iotjs_bridge_call(const char* module_name, const char* command, const char* message, void* handle) { int ret = -1; for (int i = 0; i < (int)iotjs_module_count; i++) { if (g_module_list[i].module_name != 0) { if (strncmp(g_module_list[i].module_name, module_name, strlen(module_name) + 1) == 0) { g_module_list[i].callback(command, message, handle); ret = 0; break; } } } return ret; } void iotjs_bridge_set_err(void* handle, char* err) { iotjs_bridge_call_t* bridgecall = (iotjs_bridge_call_t*)handle; IOTJS_ASSERT(iotjs_string_is_empty(&bridgecall->ret_msg)); if (err == NULL) { err = "internal error"; } if (!jerry_value_is_undefined(bridgecall->jcallback)) { uv_mutex_lock(&bridgecall->call_lock); } bridgecall->ret_msg = iotjs_string_create_with_size(err, strlen(err) + 1); bridgecall->status = CALL_STATUS_ERROR; if (bridgecall->async != NULL) { IOTJS_ASSERT(bridgecall->async->data == bridgecall); uv_async_send(bridgecall->async); } if (!jerry_value_is_undefined(bridgecall->jcallback)) { uv_mutex_unlock(&bridgecall->call_lock); } } void iotjs_bridge_set_msg(void* handle, char* msg) { iotjs_bridge_call_t* bridgecall = (iotjs_bridge_call_t*)handle; IOTJS_ASSERT(iotjs_string_is_empty(&bridgecall->ret_msg)); size_t size = 0; if (msg == NULL) { msg = ""; } else { size = strlen(msg) + 1; } if (size > MAX_RETURN_MESSAGE) { iotjs_bridge_set_err(handle, "The message exceeds the maximum"); } else { if (!jerry_value_is_undefined(bridgecall->jcallback)) { uv_mutex_lock(&bridgecall->call_lock); } bridgecall->ret_msg = iotjs_string_create_with_size(msg, size); bridgecall->status = CALL_STATUS_SETMSG; if (bridgecall->async != NULL) { IOTJS_ASSERT(bridgecall->async->data == bridgecall); uv_async_send(bridgecall->async); } if (!jerry_value_is_undefined(bridgecall->jcallback)) { uv_mutex_unlock(&bridgecall->call_lock); } } } static iotjs_bridge_call_t* iotjs_bridge_call_init( iotjs_bridge_call_t* bridgecall, const jerry_value_t bridge, const jerry_value_t jcallback, iotjs_string_t module, iotjs_string_t command, iotjs_string_t message) { if (bridge) { bridgecall->jobject = jerry_acquire_value(bridge); } else { bridgecall->jobject = jerry_create_undefined(); } if (!jerry_value_is_null(jcallback)) { bridgecall->jcallback = jerry_acquire_value(jcallback); bridgecall->req.data = (void*)bridgecall; uv_mutex_init(&bridgecall->call_lock); } else { bridgecall->jcallback = jerry_create_undefined(); } bridgecall->async = NULL; bridgecall->module = module; bridgecall->command = command; bridgecall->message = message; bridgecall->ret_msg = iotjs_string_create(); bridgecall->status = CALL_STATUS_INIT; bridgecall->bridgeobj = NULL; return bridgecall; } static void iotjs_bridge_call_destroy(iotjs_bridge_call_t* bridgecall) { if (!jerry_value_is_undefined(bridgecall->jobject)) { jerry_release_value(bridgecall->jobject); } if (!jerry_value_is_undefined(bridgecall->jcallback)) { uv_mutex_destroy(&bridgecall->call_lock); jerry_release_value(bridgecall->jcallback); } if (bridgecall->async) { uv_close((uv_handle_t*)bridgecall->async, NULL); IOTJS_RELEASE(bridgecall->async); } iotjs_string_destroy(&bridgecall->module); iotjs_string_destroy(&bridgecall->command); iotjs_string_destroy(&bridgecall->message); iotjs_string_destroy(&bridgecall->ret_msg); bridgecall->bridgeobj = NULL; IOTJS_RELEASE(bridgecall); } static iotjs_bridge_object_t* iotjs_bridge_get_object(jerry_value_t obj_val) { iotjs_bridge_object_t* bridgeobj = NULL; if (jerry_get_object_native_pointer(obj_val, (void**)&bridgeobj, &this_module_native_info)) { bridgeobj = IOTJS_ALLOC(iotjs_bridge_object_t); bridgeobj->jobject = obj_val; bridgeobj->calls = NULL; bridgeobj->calls_alloc = 0; jerry_set_object_native_pointer(obj_val, bridgeobj, &this_module_native_info); } IOTJS_ASSERT(bridgeobj != NULL); IOTJS_ASSERT(bridgeobj->jobject == obj_val); return bridgeobj; } static void iotjs_bridge_object_destroy(iotjs_bridge_object_t* bridgeobj) { if (bridgeobj->calls_alloc == 0) { if (bridgeobj->calls != NULL) { iotjs_bridge_call_destroy((iotjs_bridge_call_t*)bridgeobj->calls); } } else { for (size_t i = 0; i < bridgeobj->calls_alloc; i++) { if (bridgeobj->calls[i] != NULL) { iotjs_bridge_call_destroy(bridgeobj->calls[i]); } } IOTJS_ASSERT(bridgeobj->calls); iotjs_buffer_release((char*)bridgeobj->calls); } IOTJS_RELEASE(bridgeobj); } static int iotjs_bridge_add_call(iotjs_bridge_object_t* bridgeobj, iotjs_bridge_call_t* callobj) { IOTJS_ASSERT(bridgeobj); IOTJS_ASSERT(callobj); callobj->bridgeobj = bridgeobj; if (bridgeobj->calls_alloc == 0) { if (bridgeobj->calls == NULL) { bridgeobj->calls = (iotjs_bridge_call_t**)callobj; } else { iotjs_bridge_call_t* prev_obj = (iotjs_bridge_call_t*)bridgeobj->calls; bridgeobj->calls = (iotjs_bridge_call_t**)iotjs_buffer_allocate( sizeof(iotjs_bridge_call_t*) * 4); bridgeobj->calls_alloc = 4; bridgeobj->calls[0] = prev_obj; bridgeobj->calls[1] = callobj; } } else { for (size_t i = 0; i < bridgeobj->calls_alloc; i++) { if (bridgeobj->calls[i] == 0) { bridgeobj->calls[i] = callobj; return bridgeobj->calls_alloc; } } size_t prev_size = sizeof(iotjs_bridge_call_t*) * bridgeobj->calls_alloc; bridgeobj->calls = (iotjs_bridge_call_t**)iotjs_buffer_reallocate((char*)bridgeobj->calls, prev_size * 2); bridgeobj->calls[bridgeobj->calls_alloc] = callobj; bridgeobj->calls_alloc *= 2; } return bridgeobj->calls_alloc; } static int iotjs_bridge_remove_call(iotjs_bridge_call_t* callobj) { iotjs_bridge_object_t* bridgeobj = callobj->bridgeobj; if (bridgeobj->calls_alloc == 0) { if (bridgeobj->calls != NULL) { iotjs_bridge_call_destroy((iotjs_bridge_call_t*)bridgeobj->calls); bridgeobj->calls = NULL; } } else { for (size_t i = 0; i < bridgeobj->calls_alloc; i++) { if (bridgeobj->calls[i] == callobj) { iotjs_bridge_call_destroy(bridgeobj->calls[i]); bridgeobj->calls[i] = NULL; } } } return 0; } static void iotjs_bridge_js_call(iotjs_bridge_call_t* bridgecall) { jerry_value_t jargs[2] = { 0 }; if (bridgecall->status == CALL_STATUS_ERROR) { // internal error jargs[0] = iotjs_jval_create_error_without_error_flag( iotjs_string_data(&bridgecall->ret_msg)); jargs[1] = jerry_create_null(); } else { jargs[0] = jerry_create_null(); jargs[1] = jerry_create_string_from_utf8( (const jerry_char_t*)iotjs_string_data(&bridgecall->ret_msg)); } jerry_value_t jcallback = bridgecall->jcallback; if (jerry_value_is_function(jcallback)) { iotjs_invoke_callback(jcallback, jerry_create_undefined(), jargs, 2); } jerry_release_value(jargs[0]); jerry_release_value(jargs[1]); } static void aysnc_callback(uv_async_t* async) { iotjs_bridge_call_t* bridgecall = (iotjs_bridge_call_t*)async->data; iotjs_bridge_js_call(bridgecall); iotjs_bridge_remove_call(bridgecall); } void after_worker(uv_work_t* req, int status) { iotjs_bridge_call_t* bridgecall = (iotjs_bridge_call_t*)req->data; uv_mutex_lock(&bridgecall->call_lock); if ((bridgecall->status == CALL_STATUS_ERROR) || (bridgecall->status == CALL_STATUS_SETMSG)) { iotjs_bridge_js_call(bridgecall); uv_mutex_unlock(&bridgecall->call_lock); iotjs_bridge_remove_call(bridgecall); } else { uv_loop_t* loop = iotjs_environment_loop(iotjs_environment_get()); uv_async_t* async = IOTJS_ALLOC(uv_async_t); bridgecall->async = async; async->data = (void*)bridgecall; uv_async_init(loop, async, aysnc_callback); uv_mutex_unlock(&bridgecall->call_lock); } } void bridge_worker(uv_work_t* req) { iotjs_bridge_call_t* bridgecall = (iotjs_bridge_call_t*)req->data; bridgecall->status = CALL_STATUS_CALLED; int ret = iotjs_bridge_call(iotjs_string_data(&bridgecall->module), iotjs_string_data(&bridgecall->command), iotjs_string_data(&bridgecall->message), (void*)bridgecall); if (ret < 0) { iotjs_bridge_set_err(bridgecall, "Can't find the module"); } } /** * send async message */ JS_FUNCTION(message_async) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(3, string, string, string); DJS_CHECK_ARG_IF_EXIST(3, function); jerry_value_t bridge_module = JS_GET_THIS(); iotjs_string_t module_name = JS_GET_ARG(0, string); iotjs_string_t module_command = JS_GET_ARG(1, string); iotjs_string_t command_message = JS_GET_ARG(2, string); jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(3, function); if (!jerry_value_is_null(jcallback)) { // async call uv_loop_t* loop = iotjs_environment_loop(iotjs_environment_get()); iotjs_bridge_object_t* bridgeobj = iotjs_bridge_get_object(bridge_module); iotjs_bridge_call_t* bridgecall = IOTJS_ALLOC(iotjs_bridge_call_t); iotjs_bridge_call_init(bridgecall, bridge_module, jcallback, module_name, module_command, command_message); iotjs_bridge_add_call(bridgeobj, bridgecall); uv_queue_work(loop, &bridgecall->req, bridge_worker, after_worker); } else { // sync call jerry_value_t jmsg; iotjs_bridge_call_t bridgecall_local; iotjs_bridge_call_t* bridgecall = &bridgecall_local; iotjs_bridge_call_init(bridgecall, 0, 0, module_name, module_command, command_message); int ret = iotjs_bridge_call(iotjs_string_data(&module_name), iotjs_string_data(&module_command), iotjs_string_data(&command_message), (void*)bridgecall); if (ret < 0) { iotjs_bridge_set_err(bridgecall, "Can't find the module"); } if (bridgecall->status == CALL_STATUS_ERROR) { // error.. if (iotjs_string_is_empty(&bridgecall->ret_msg)) { jmsg = JS_CREATE_ERROR(COMMON, (jerry_char_t*)"Unknown native error.."); } else { jmsg = JS_CREATE_ERROR(COMMON, iotjs_string_data(&bridgecall->ret_msg)); } } else { if (iotjs_string_is_empty(&bridgecall->ret_msg)) { jmsg = jerry_create_string((jerry_char_t*)""); } else { jmsg = jerry_create_string( (jerry_char_t*)iotjs_string_data(&bridgecall->ret_msg)); } } iotjs_string_destroy(&bridgecall->module); iotjs_string_destroy(&bridgecall->command); iotjs_string_destroy(&bridgecall->message); iotjs_string_destroy(&bridgecall->ret_msg); return jmsg; } return jerry_create_string((jerry_char_t*)""); } /** * Init method called by IoT.js */ jerry_value_t iotjs_init_bridge() { jerry_value_t messag_module = jerry_create_object(); iotjs_jval_set_method(messag_module, "send", message_async); iotjs_bridge_init(); return messag_module; } iotjs-1.0+715/src/modules/iotjs_module_bridge.h000066400000000000000000000020511371177304000214340ustar00rootroot00000000000000/* Copyright 2018-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_BRIDGE_H #define IOTJS_BRIDGE_H #define MAX_RETURN_MESSAGE 512 * 2 /* */ typedef void (*iotjs_bridge_func)(const char* command, const char* message, void* return_handle); int iotjs_bridge_register(char* module_name, iotjs_bridge_func callback); void iotjs_bridge_set_err(void* return_handle, char* err); void iotjs_bridge_set_msg(void* return_handle, char* msg); #endif iotjs-1.0+715/src/modules/iotjs_module_buffer.c000066400000000000000000000504051371177304000214520ustar00rootroot00000000000000/* 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 #include #include typedef enum { BUFFER_HEX_ENC = 0, BUFFER_BASE64_ENC = 1, } buffer_encoding_type_t; IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(bufferwrap); iotjs_bufferwrap_t* iotjs_bufferwrap_create(const jerry_value_t jobject, size_t length) { iotjs_bufferwrap_t* bufferwrap = (iotjs_bufferwrap_t*)iotjs_buffer_allocate( sizeof(iotjs_bufferwrap_t) + length); bufferwrap->jobject = jobject; jerry_set_object_native_pointer(jobject, bufferwrap, &this_module_native_info); bufferwrap->length = length; IOTJS_ASSERT( jerry_get_object_native_pointer(jobject, NULL, &this_module_native_info)); return bufferwrap; } static void iotjs_bufferwrap_destroy(iotjs_bufferwrap_t* bufferwrap) { if (bufferwrap->external_info && bufferwrap->external_info->free_hint) { ((void (*)(void*))bufferwrap->external_info->free_hint)( bufferwrap->external_info->free_info); } IOTJS_RELEASE(bufferwrap->external_info); IOTJS_RELEASE(bufferwrap); } void iotjs_bufferwrap_set_external_callback(iotjs_bufferwrap_t* bufferwrap, void* free_hint, void* free_info) { bufferwrap->external_info = IOTJS_ALLOC(iotjs_bufferwrap_external_info_t); bufferwrap->external_info->free_hint = free_hint; bufferwrap->external_info->free_info = free_info; } iotjs_bufferwrap_t* iotjs_bufferwrap_from_jbuffer(const jerry_value_t jbuffer) { IOTJS_ASSERT(jerry_value_is_object(jbuffer)); void* buffer = NULL; bool res = jerry_get_object_native_pointer(jbuffer, &buffer, &this_module_native_info); IOTJS_ASSERT(res && buffer != NULL); return buffer; } size_t iotjs_bufferwrap_length(iotjs_bufferwrap_t* bufferwrap) { if (bufferwrap == NULL) { IOTJS_ASSERT(0); return 0; } #ifndef NDEBUG jerry_value_t jlength = iotjs_jval_get_property(bufferwrap->jobject, IOTJS_MAGIC_STRING_LENGTH); size_t length = iotjs_jval_as_number(jlength); IOTJS_ASSERT(length == bufferwrap->length); jerry_release_value(jlength); #endif return bufferwrap->length; } iotjs_bufferwrap_t* iotjs_jbuffer_get_bufferwrap_ptr( const jerry_value_t jbuffer) { if (!jerry_value_is_object(jbuffer)) { return NULL; } void* buffer = NULL; if (jerry_get_object_native_pointer(jbuffer, &buffer, &this_module_native_info)) { return (iotjs_bufferwrap_t*)buffer; } return NULL; } 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 hex_to_bin(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 src_len) { const char* buf_start = buf; const char* buf_end = buf + len; const char* src_end = src + src_len; if ((src_len & 0x1) != 0) { return 0; } while (src < src_end) { int8_t a = hex_to_bin(src[0]); int8_t b = hex_to_bin(src[1]); if (a == -1 || b == -1) { return 0; } if (buf < buf_end) { *buf++ = (a << 4) | b; } src += 2; } return (size_t)((buf - buf_start) + 1); } static int32_t base64_to_bin(char c) { if (c >= 'A' && c <= 'Z') { return (int32_t)(c - 'A'); } if (c >= 'a' && c <= 'z') { return (int32_t)(26 + (c - 'a')); } if (c >= '0' && c <= '9') { return (int32_t)(52 + (c - '0')); } if (c == '+') { return 62; } if (c == '/') { return 63; } return (int32_t)(-1); } static size_t base64_decode(char* dst, size_t len, const char* src, const size_t srcLen) { if (srcLen == 0) { return 1; } char* decoded_base64 = NULL; size_t decoded_len = iotjs_base64_decode(&decoded_base64, src, srcLen); size_t ret_val = 0; if (decoded_len) { char* buf = dst; char* bufEnd = len > decoded_len ? dst + decoded_len : dst + len; char* pos = decoded_base64; while (buf < bufEnd) { *buf++ = *pos++; } ret_val = (size_t)(buf - dst) + 1; } IOTJS_RELEASE(decoded_base64); return ret_val; } size_t iotjs_base64_decode(char** out_buff, const char* src, const size_t srcLen) { if ((srcLen & 0x3) != 0 || srcLen == 0) { return 0; } size_t len = (3 * (srcLen / 4)); const char* src_end = src + srcLen; if (src_end[-1] == '=') { src_end--; len--; if (src_end[-1] == '=') { src_end--; len--; } } if (*out_buff == NULL) { *out_buff = IOTJS_CALLOC(len, char); } char* buf = *out_buff; const char* bufStart = buf; const char* bufEnd = buf + len; int32_t current_bits = 0; int32_t shift = 8; while (src < src_end) { int32_t value = base64_to_bin(*src++); if (value == -1) { return 0; } current_bits = (current_bits << 6) | value; shift -= 2; if (shift == 6) { continue; } int32_t byte = (current_bits >> shift); current_bits &= (1 << shift) - 1; if (shift == 0) { shift = 8; } if (buf <= bufEnd) { *buf++ = byte; } } return (size_t)((buf - bufStart)); } 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 char* other_buffer = other->buffer; size_t other_length = other->length; size_t i = 0; size_t j = 0; while (i < bufferwrap->length && j < other_length) { if (bufferwrap->buffer[i] < other_buffer[j]) { return -1; } else if (bufferwrap->buffer[i] > other_buffer[j]) { return 1; } ++i; ++j; } if (j < other_length) { return -1; } else if (i < bufferwrap->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) { size_t copied = 0; size_t dst_length = bufferwrap->length; for (size_t i = src_from, j = dst_from; i < src_to && j < dst_length; ++i, ++j) { *(bufferwrap->buffer + j) = *(src + i); ++copied; } return copied; } size_t iotjs_bufferwrap_copy(iotjs_bufferwrap_t* bufferwrap, const char* src, size_t len) { return iotjs_bufferwrap_copy_internal(bufferwrap, src, 0, len, 0); } static size_t index_normalizer(int64_t index, size_t max_length) { size_t idx; if (index < 0) { if ((size_t)(-index) > max_length) { idx = SIZE_MAX; } else { idx = (size_t)index + max_length; } } else { idx = (size_t)index; } return bound_range(idx, 0, max_length); } jerry_value_t iotjs_bufferwrap_create_buffer(size_t len) { jerry_value_t jres_buffer = jerry_create_object(); iotjs_bufferwrap_create(jres_buffer, len); iotjs_jval_set_property_number(jres_buffer, IOTJS_MAGIC_STRING_LENGTH, len); // Support for 'instanceof' operator jerry_value_t native_buffer = iotjs_module_get("buffer"); jerry_value_t jbuffer = iotjs_jval_get_property(native_buffer, IOTJS_MAGIC_STRING_BUFFER); if (!jerry_value_is_error(jbuffer) && jerry_value_is_object(jbuffer)) { jerry_value_t jbuffer_proto = iotjs_jval_get_property(jbuffer, IOTJS_MAGIC_STRING_PROTOTYPE); if (!jerry_value_is_error(jbuffer_proto) && jerry_value_is_object(jbuffer_proto)) { jerry_set_prototype(jres_buffer, jbuffer_proto); } jerry_release_value(jbuffer_proto); } jerry_release_value(jbuffer); return jres_buffer; } JS_FUNCTION(buffer_constructor) { DJS_CHECK_ARGS(2, object, number); const jerry_value_t jobject = JS_GET_ARG(0, object); size_t length = JS_GET_ARG(1, number); iotjs_bufferwrap_create(jobject, length); return jerry_create_undefined(); } JS_FUNCTION(buffer_compare) { JS_DECLARE_OBJECT_PTR(0, bufferwrap, src_buffer_wrap); JS_DECLARE_OBJECT_PTR(1, bufferwrap, dst_buffer_wrap); int compare = iotjs_bufferwrap_compare(src_buffer_wrap, dst_buffer_wrap); return jerry_create_number(compare); } JS_FUNCTION(buffer_copy) { DJS_CHECK_ARGS(5, object, object, number, number, number); JS_DECLARE_OBJECT_PTR(0, bufferwrap, src_buffer_wrap); const jerry_value_t jdst_buffer = JS_GET_ARG(1, 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); size_t dst_start = iotjs_convert_double_to_sizet(JS_GET_ARG(2, number)); dst_start = bound_range(dst_start, 0, dst_length); size_t src_start = iotjs_convert_double_to_sizet(JS_GET_ARG(3, number)); src_start = bound_range(src_start, 0, src_length); size_t src_end = iotjs_convert_double_to_sizet(JS_GET_ARG(4, number)); src_end = bound_range(src_end, 0, src_length); if (src_end < src_start) { src_end = src_start; } const char* src_data = src_buffer_wrap->buffer; size_t copied = iotjs_bufferwrap_copy_internal(dst_buffer_wrap, src_data, src_start, src_end, dst_start); return jerry_create_number(copied); } JS_FUNCTION(buffer_write) { DJS_CHECK_ARGS(4, object, string, number, number); JS_DECLARE_OBJECT_PTR(0, bufferwrap, buffer_wrap); iotjs_string_t src = JS_GET_ARG(1, string); size_t buffer_length = iotjs_bufferwrap_length(buffer_wrap); size_t offset = iotjs_convert_double_to_sizet(JS_GET_ARG(2, number)); offset = bound_range(offset, 0, buffer_length); size_t length = iotjs_convert_double_to_sizet(JS_GET_ARG(3, 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_string_destroy(&src); return jerry_create_number(copied); } JS_FUNCTION(buffer_write_uint8) { DJS_CHECK_ARGS(3, object, number, number); JS_DECLARE_OBJECT_PTR(0, bufferwrap, buffer_wrap); const char src[] = { (char)JS_GET_ARG(1, number) }; size_t length = 1; size_t buffer_length = iotjs_bufferwrap_length(buffer_wrap); size_t offset = iotjs_convert_double_to_sizet(JS_GET_ARG(2, 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); return jerry_create_number(copied); } JS_FUNCTION(buffer_write_decode) { DJS_CHECK_ARGS(5, object, number, string, number, number); JS_DECLARE_OBJECT_PTR(0, bufferwrap, buffer_wrap); double type = JS_GET_ARG(1, number); iotjs_string_t src = JS_GET_ARG(2, string); size_t buffer_length = iotjs_bufferwrap_length(buffer_wrap); size_t offset = iotjs_convert_double_to_sizet(JS_GET_ARG(3, number)); offset = bound_range(offset, 0, buffer_length); size_t length = iotjs_convert_double_to_sizet(JS_GET_ARG(4, number)); length = bound_range(length, 0, buffer_length - offset); const char* src_data = iotjs_string_data(&src); unsigned src_length = iotjs_string_size(&src); size_t nbytes; char* dst_data = buffer_wrap->buffer + offset; const char* error_msg; if (type == BUFFER_HEX_ENC) { nbytes = hex_decode(dst_data, length, src_data, src_length); error_msg = "Invalid hex string"; } else { nbytes = base64_decode(dst_data, length, src_data, src_length); error_msg = "Invalid base64 string"; } iotjs_string_destroy(&src); if (nbytes == 0) return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t*)error_msg); return jerry_create_number(nbytes - 1); } JS_FUNCTION(buffer_read_uint8) { DJS_CHECK_ARGS(2, object, number); JS_DECLARE_OBJECT_PTR(0, bufferwrap, buffer_wrap); size_t buffer_length = iotjs_bufferwrap_length(buffer_wrap); if (buffer_length == 0) { return jerry_create_number(0); } size_t offset = iotjs_convert_double_to_sizet(JS_GET_ARG(1, number)); offset = bound_range(offset, 0, buffer_length - 1); char* buffer = buffer_wrap->buffer; return jerry_create_number((uint8_t)buffer[offset]); } JS_FUNCTION(buffer_slice) { DJS_CHECK_ARGS(3, object, number, number); JS_DECLARE_OBJECT_PTR(0, bufferwrap, buffer_wrap); int64_t start = JS_GET_ARG(1, number); int64_t end = JS_GET_ARG(2, number); size_t len = iotjs_bufferwrap_length(buffer_wrap); size_t start_idx = index_normalizer(start, len); size_t end_idx = index_normalizer(end, len); if (end_idx < start_idx) { end_idx = start_idx; } size_t length = (size_t)(end_idx - start_idx); jerry_value_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, buffer_wrap->buffer, start_idx, end_idx, 0); return jnew_buffer; } static char to_hex_char(uint8_t digit) { return (char)((digit < 10) ? (digit + '0') : (digit + 'a' - 10)); } static jerry_value_t to_hex_string(const uint8_t* data, size_t length) { if (length == 0) { return jerry_create_string_sz(NULL, 0); } const uint8_t* end = data + length; size_t buffer_length = length * 2; char* buffer = iotjs_buffer_allocate(buffer_length); const jerry_char_t* str = (const jerry_char_t*)buffer; while (data < end) { *buffer++ = to_hex_char(*data >> 4); *buffer++ = to_hex_char(*data & 0xf); data++; } jerry_value_t ret_value = jerry_create_string_sz(str, buffer_length); IOTJS_RELEASE(str); return ret_value; } static jerry_value_t to_base64_string(const uint8_t* data, size_t length) { unsigned char* buffer = NULL; size_t buffer_length = iotjs_base64_encode(&buffer, data, length); jerry_value_t ret_value = jerry_create_string_sz(buffer, buffer_length); IOTJS_RELEASE(buffer); return ret_value; } static const unsigned char base64_enc_map[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; size_t iotjs_base64_encode(unsigned char** out_buff, const unsigned char* data, size_t buff_len) { size_t i, n; int C1, C2, C3; unsigned char* p; if (buff_len == 0) { return 0; } n = buff_len / 3 + (buff_len % 3 != 0); if (n > ((size_t)-2) / 4) { return 0; } if (*out_buff == NULL) { *out_buff = IOTJS_CALLOC(n * 4 + 1, unsigned char); } n = (buff_len / 3) * 3; for (i = 0, p = *out_buff; i < n; i += 3) { C1 = *data++; C2 = *data++; C3 = *data++; *p++ = base64_enc_map[(C1 >> 2) & 0x3F]; *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F]; *p++ = base64_enc_map[(((C2 & 15) << 2) + (C3 >> 6)) & 0x3F]; *p++ = base64_enc_map[C3 & 0x3F]; } if (i < buff_len) { C1 = *data++; C2 = ((i + 1) < buff_len) ? *data++ : 0; *p++ = base64_enc_map[(C1 >> 2) & 0x3F]; *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F]; if ((i + 1) < buff_len) { *p++ = base64_enc_map[((C2 & 15) << 2) & 0x3F]; } else { *p++ = '='; } *p++ = '='; } size_t ret_len = (size_t)(p - *out_buff); *p = 0; return ret_len; } JS_FUNCTION(buffer_to_string) { DJS_CHECK_ARGS(4, object, number, number, number); JS_DECLARE_OBJECT_PTR(0, bufferwrap, buffer_wrap); double type = JS_GET_ARG(1, number); size_t start = iotjs_convert_double_to_sizet(JS_GET_ARG(2, number)); start = bound_range(start, 0, iotjs_bufferwrap_length(buffer_wrap)); size_t end = iotjs_convert_double_to_sizet(JS_GET_ARG(3, number)); end = bound_range(end, 0, iotjs_bufferwrap_length(buffer_wrap)); if (end < start) { end = start; } if (start > buffer_wrap->length) { start = buffer_wrap->length; } if (end > buffer_wrap->length) { end = buffer_wrap->length; } size_t length = end - start; const char* data = buffer_wrap->buffer + start; if (type == BUFFER_HEX_ENC) { return to_hex_string((const uint8_t*)data, length); } if (type == BUFFER_BASE64_ENC) { return to_base64_string((const uint8_t*)data, length); } /* Stops at first zero. */ length = strnlen(data, length); if (!jerry_is_valid_utf8_string((const jerry_char_t*)data, length)) { return JS_CREATE_ERROR(TYPE, "Invalid UTF-8 string"); } return jerry_create_string_sz_from_utf8((const jerry_char_t*)data, length); } JS_FUNCTION(buffer_byte_length) { DJS_CHECK_ARGS(1, string); jerry_size_t size = jerry_get_string_size(jargv[0]); return jerry_create_number(size); } JS_FUNCTION(buffer_from_array_buffer) { if (jargc < 1 || !jerry_value_is_arraybuffer(jargv[0])) { return jerry_create_undefined(); } jerry_length_t offset = 0; jerry_length_t length = jerry_get_arraybuffer_byte_length(jargv[0]); if (jargc >= 2) { jerry_value_t offset_num = jerry_value_to_number(jargv[1]); if (jerry_value_is_error(offset_num)) { return offset_num; } double offset_value = jerry_get_number_value(offset_num); if (isnan(offset_value)) { offset_value = 0; } jerry_release_value(offset_num); if (offset_value < 0 || offset_value > length) { return JS_CREATE_ERROR(RANGE, "'offset' is out of bounds"); } offset = (jerry_length_t)offset_value; } length -= offset; if (jargc >= 3) { if (jerry_value_is_error(jargv[2])) { return length; } if (jerry_value_is_number(jargv[2])) { double length_value = (double)length; length_value = jerry_get_number_value(jargv[2]); if (isnan(length_value) || length_value < 0) { length = 0; } else if (length_value < length) { length = (jerry_length_t)length_value; } else if (length_value > length) { return JS_CREATE_ERROR(RANGE, "'length' is out of bounds"); } } } if (length < 1) { return iotjs_bufferwrap_create_buffer(0); } jerry_value_t jres_bufferwrap = iotjs_bufferwrap_create_buffer(length); iotjs_bufferwrap_t* jsres_buffer = iotjs_jbuffer_get_bufferwrap_ptr(jres_bufferwrap); jerry_arraybuffer_read(jargv[0], offset, (uint8_t*)jsres_buffer->buffer, length); return jres_bufferwrap; } jerry_value_t iotjs_init_buffer(void) { jerry_value_t buffer = jerry_create_external_function(buffer_constructor); iotjs_jval_set_method(buffer, IOTJS_MAGIC_STRING_BYTELENGTH, buffer_byte_length); iotjs_jval_set_method(buffer, IOTJS_MAGIC_STRING_COMPARE, buffer_compare); iotjs_jval_set_method(buffer, IOTJS_MAGIC_STRING_COPY, buffer_copy); iotjs_jval_set_method(buffer, IOTJS_MAGIC_STRING_WRITE, buffer_write); iotjs_jval_set_method(buffer, IOTJS_MAGIC_STRING_WRITEDECODE, buffer_write_decode); iotjs_jval_set_method(buffer, IOTJS_MAGIC_STRING_WRITEUINT8, buffer_write_uint8); iotjs_jval_set_method(buffer, IOTJS_MAGIC_STRING_READUINT8, buffer_read_uint8); iotjs_jval_set_method(buffer, IOTJS_MAGIC_STRING_SLICE, buffer_slice); iotjs_jval_set_method(buffer, IOTJS_MAGIC_STRING_TOSTRING, buffer_to_string); iotjs_jval_set_method(buffer, IOTJS_MAGIC_STRING_FROM_ARRAYBUFFER, buffer_from_array_buffer); return buffer; } iotjs-1.0+715/src/modules/iotjs_module_buffer.h000066400000000000000000000041261371177304000214560ustar00rootroot00000000000000/* 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_MODULE_BUFFER_H #define IOTJS_MODULE_BUFFER_H typedef struct { void* free_hint; void* free_info; } iotjs_bufferwrap_external_info_t; typedef struct { jerry_value_t jobject; size_t length; iotjs_bufferwrap_external_info_t* external_info; char buffer[]; } iotjs_bufferwrap_t; size_t iotjs_base64_decode(char** out_buff, const char* src, const size_t srcLen); size_t iotjs_base64_encode(unsigned char** out_buff, const uint8_t* data, size_t length); iotjs_bufferwrap_t* iotjs_bufferwrap_create(const jerry_value_t jbuiltin, size_t length); void iotjs_bufferwrap_set_external_callback(iotjs_bufferwrap_t* bufferwrap, void* free_hint, void* free_info); iotjs_bufferwrap_t* iotjs_bufferwrap_from_jbuffer(const jerry_value_t jbuffer); size_t iotjs_bufferwrap_length(iotjs_bufferwrap_t* bufferwrap); int iotjs_bufferwrap_compare(const iotjs_bufferwrap_t* bufferwrap, const iotjs_bufferwrap_t* other); char* iotjs_bufferwrap_buffer(iotjs_bufferwrap_t* bufferwrap); size_t iotjs_bufferwrap_copy(iotjs_bufferwrap_t* bufferwrap, const char* src, size_t len); iotjs_bufferwrap_t* iotjs_jbuffer_get_bufferwrap_ptr(const jerry_value_t); // Fail-safe creation of Buffer object. jerry_value_t iotjs_bufferwrap_create_buffer(size_t len); #endif /* IOTJS_MODULE_BUFFER_H */ iotjs-1.0+715/src/modules/iotjs_module_console.c000066400000000000000000000036501371177304000216430ustar00rootroot00000000000000/* 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_debuglog.h" // This function should be able to print utf8 encoded string // as utf8 is internal string representation in Jerryscript static jerry_value_t console_print(const jerry_value_t* jargv, const jerry_length_t jargc, FILE* out_fd) { DJS_CHECK_ARGS(1, string); iotjs_string_t msg = JS_GET_ARG(0, string); const char* str = iotjs_string_data(&msg); unsigned str_len = iotjs_string_size(&msg); unsigned idx = 0; if (iotjs_console_out) { int level = (out_fd == stdout) ? DBGLEV_INFO : DBGLEV_ERR; iotjs_console_out(level, "%s", str); } else { for (idx = 0; idx < str_len; idx++) { if (str[idx] != 0) { fprintf(out_fd, "%c", str[idx]); } else { fprintf(out_fd, "\\u0000"); } } } iotjs_string_destroy(&msg); return jerry_create_undefined(); } JS_FUNCTION(console_stdout) { return console_print(jargv, jargc, stdout); } JS_FUNCTION(console_stderr) { return console_print(jargv, jargc, stderr); } jerry_value_t iotjs_init_console(void) { jerry_value_t console = jerry_create_object(); iotjs_jval_set_method(console, IOTJS_MAGIC_STRING_STDOUT, console_stdout); iotjs_jval_set_method(console, IOTJS_MAGIC_STRING_STDERR, console_stderr); return console; } iotjs-1.0+715/src/modules/iotjs_module_constants.c000066400000000000000000000026551371177304000222210ustar00rootroot00000000000000/* 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_compatibility.h" #include "iotjs_module.h" #define SET_CONSTANT(object, constant) \ do { \ iotjs_jval_set_property_number(object, #constant, constant); \ } while (0) jerry_value_t iotjs_init_constants(void) { jerry_value_t constants = jerry_create_object(); SET_CONSTANT(constants, O_APPEND); SET_CONSTANT(constants, O_CREAT); SET_CONSTANT(constants, O_EXCL); SET_CONSTANT(constants, O_RDONLY); SET_CONSTANT(constants, O_RDWR); SET_CONSTANT(constants, O_SYNC); SET_CONSTANT(constants, O_TRUNC); SET_CONSTANT(constants, O_WRONLY); SET_CONSTANT(constants, S_IFMT); SET_CONSTANT(constants, S_IFDIR); SET_CONSTANT(constants, S_IFREG); return constants; } iotjs-1.0+715/src/modules/iotjs_module_crypto.c000066400000000000000000000353421371177304000215240ustar00rootroot00000000000000/* Copyright 2018-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. */ /* * FIPS-180-1 compliant SHA-1 implementation * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ /* * The SHA-1 standard was published by NIST in 1993. * * http://www.itl.nist.gov/fipspubs/fip180-1.htm */ #include "iotjs_def.h" #include "iotjs_module_crypto.h" #include "iotjs_module_buffer.h" /* These enum values are the same as the ones in crypto.js as well as the corresponding ones in sha.h in mbedTLS.*/ typedef enum { IOTJS_CRYPTO_SHA1 = 4, IOTJS_CRYPTO_SHA256 = 6, } iotjs_crypto_sha_t; #if !ENABLE_MODULE_TLS const char no_tls_err_str[] = "TLS module must be enabled to use this feature"; /* * 32-bit integer manipulation macros (big endian) */ #ifndef GET_UINT32_BE #define GET_UINT32_BE(n, b, i) \ { \ (n) = ((uint32_t)(b)[(i)] << 24) | ((uint32_t)(b)[(i) + 1] << 16) | \ ((uint32_t)(b)[(i) + 2] << 8) | ((uint32_t)(b)[(i) + 3]); \ } #endif #ifndef PUT_UINT32_BE #define PUT_UINT32_BE(n, b, i) \ { \ (b)[(i)] = (unsigned char)((n) >> 24); \ (b)[(i) + 1] = (unsigned char)((n) >> 16); \ (b)[(i) + 2] = (unsigned char)((n) >> 8); \ (b)[(i) + 3] = (unsigned char)((n)); \ } #endif static int iotjs_sha1_process(uint32_t state[5], const unsigned char data[64]) { uint32_t temp, W[16], A, B, C, D, E; GET_UINT32_BE(W[0], data, 0); GET_UINT32_BE(W[1], data, 4); GET_UINT32_BE(W[2], data, 8); GET_UINT32_BE(W[3], data, 12); GET_UINT32_BE(W[4], data, 16); GET_UINT32_BE(W[5], data, 20); GET_UINT32_BE(W[6], data, 24); GET_UINT32_BE(W[7], data, 28); GET_UINT32_BE(W[8], data, 32); GET_UINT32_BE(W[9], data, 36); GET_UINT32_BE(W[10], data, 40); GET_UINT32_BE(W[11], data, 44); GET_UINT32_BE(W[12], data, 48); GET_UINT32_BE(W[13], data, 52); GET_UINT32_BE(W[14], data, 56); GET_UINT32_BE(W[15], data, 60); #define S(x, n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) #define R(t) \ (temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ W[(t - 14) & 0x0F] ^ \ W[t & 0x0F], \ (W[t & 0x0F] = S(temp, 1))) #define P(a, b, c, d, e, x) \ { \ e += S(a, 5) + F(b, c, d) + K + x; \ b = S(b, 30); \ } A = state[0]; B = state[1]; C = state[2]; D = state[3]; E = state[4]; #define F(x, y, z) (z ^ (x & (y ^ z))) #define K 0x5A827999 P(A, B, C, D, E, W[0]); P(E, A, B, C, D, W[1]); P(D, E, A, B, C, W[2]); P(C, D, E, A, B, W[3]); P(B, C, D, E, A, W[4]); P(A, B, C, D, E, W[5]); P(E, A, B, C, D, W[6]); P(D, E, A, B, C, W[7]); P(C, D, E, A, B, W[8]); P(B, C, D, E, A, W[9]); P(A, B, C, D, E, W[10]); P(E, A, B, C, D, W[11]); P(D, E, A, B, C, W[12]); P(C, D, E, A, B, W[13]); P(B, C, D, E, A, W[14]); P(A, B, C, D, E, W[15]); P(E, A, B, C, D, R(16)); P(D, E, A, B, C, R(17)); P(C, D, E, A, B, R(18)); P(B, C, D, E, A, R(19)); #undef K #undef F #define F(x, y, z) (x ^ y ^ z) #define K 0x6ED9EBA1 P(A, B, C, D, E, R(20)); P(E, A, B, C, D, R(21)); P(D, E, A, B, C, R(22)); P(C, D, E, A, B, R(23)); P(B, C, D, E, A, R(24)); P(A, B, C, D, E, R(25)); P(E, A, B, C, D, R(26)); P(D, E, A, B, C, R(27)); P(C, D, E, A, B, R(28)); P(B, C, D, E, A, R(29)); P(A, B, C, D, E, R(30)); P(E, A, B, C, D, R(31)); P(D, E, A, B, C, R(32)); P(C, D, E, A, B, R(33)); P(B, C, D, E, A, R(34)); P(A, B, C, D, E, R(35)); P(E, A, B, C, D, R(36)); P(D, E, A, B, C, R(37)); P(C, D, E, A, B, R(38)); P(B, C, D, E, A, R(39)); #undef K #undef F #define F(x, y, z) ((x & y) | (z & (x | y))) #define K 0x8F1BBCDC P(A, B, C, D, E, R(40)); P(E, A, B, C, D, R(41)); P(D, E, A, B, C, R(42)); P(C, D, E, A, B, R(43)); P(B, C, D, E, A, R(44)); P(A, B, C, D, E, R(45)); P(E, A, B, C, D, R(46)); P(D, E, A, B, C, R(47)); P(C, D, E, A, B, R(48)); P(B, C, D, E, A, R(49)); P(A, B, C, D, E, R(50)); P(E, A, B, C, D, R(51)); P(D, E, A, B, C, R(52)); P(C, D, E, A, B, R(53)); P(B, C, D, E, A, R(54)); P(A, B, C, D, E, R(55)); P(E, A, B, C, D, R(56)); P(D, E, A, B, C, R(57)); P(C, D, E, A, B, R(58)); P(B, C, D, E, A, R(59)); #undef K #undef F #define F(x, y, z) (x ^ y ^ z) #define K 0xCA62C1D6 P(A, B, C, D, E, R(60)); P(E, A, B, C, D, R(61)); P(D, E, A, B, C, R(62)); P(C, D, E, A, B, R(63)); P(B, C, D, E, A, R(64)); P(A, B, C, D, E, R(65)); P(E, A, B, C, D, R(66)); P(D, E, A, B, C, R(67)); P(C, D, E, A, B, R(68)); P(B, C, D, E, A, R(69)); P(A, B, C, D, E, R(70)); P(E, A, B, C, D, R(71)); P(D, E, A, B, C, R(72)); P(C, D, E, A, B, R(73)); P(B, C, D, E, A, R(74)); P(A, B, C, D, E, R(75)); P(E, A, B, C, D, R(76)); P(D, E, A, B, C, R(77)); P(C, D, E, A, B, R(78)); P(B, C, D, E, A, R(79)); #undef K #undef F state[0] += A; state[1] += B; state[2] += C; state[3] += D; state[4] += E; return (0); } static const unsigned char sha1_padding[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static int iotjs_sha1_update(uint32_t total[2], uint32_t state[5], unsigned char buffer[64], const unsigned char *in_buff, size_t buff_len) { int ret; size_t fill; uint32_t left; if (buff_len == 0) { return 0; } left = total[0] & 0x3F; fill = 64 - left; total[0] += (uint32_t)buff_len; total[0] &= 0xFFFFFFFF; if (total[0] < (uint32_t)buff_len) { total[1]++; } if (left && buff_len >= fill) { memcpy((void *)(buffer + left), in_buff, fill); if ((ret = iotjs_sha1_process(state, buffer)) != 0) { return ret; } in_buff += fill; buff_len -= fill; left = 0; } while (buff_len >= 64) { if ((ret = iotjs_sha1_process(state, buffer)) != 0) { return ret; } } if (buff_len > 0) { memcpy((void *)(buffer + left), in_buff, buff_len); } return 0; } static int iotjs_sha1_finish(uint32_t total[2], uint32_t state[5], unsigned char buffer[64], unsigned char *out_buff) { int ret; uint32_t last, padn; uint32_t high, low; unsigned char msglen[8]; high = (total[0] >> 29) | (total[1] << 3); low = (total[0] << 3); PUT_UINT32_BE(high, msglen, 0); PUT_UINT32_BE(low, msglen, 4); last = total[0] & 0x3F; padn = (last < 56) ? (56 - last) : (120 - last); if ((ret = iotjs_sha1_update(total, state, buffer, sha1_padding, padn)) != 0) { return ret; } if ((ret = iotjs_sha1_update(total, state, buffer, msglen, 8)) != 0) { return ret; } PUT_UINT32_BE(state[0], out_buff, 0); PUT_UINT32_BE(state[1], out_buff, 4); PUT_UINT32_BE(state[2], out_buff, 8); PUT_UINT32_BE(state[3], out_buff, 12); PUT_UINT32_BE(state[4], out_buff, 16); return 0; } #else /* ENABLE_MODULE_TLS */ #include "mbedtls/pk.h" #include "mbedtls/sha1.h" #include "mbedtls/sha256.h" #endif /* !ENABLE_MODULE_TLS */ size_t iotjs_sha1_encode(unsigned char **out_buff, const unsigned char *in_buff, size_t buff_len) { size_t sha1_size = 20; // 160 bytes *out_buff = IOTJS_CALLOC(sha1_size, unsigned char); #if !ENABLE_MODULE_TLS uint32_t total[2] = { 0 }; uint32_t state[5] = { 0 }; unsigned char buffer[64] = { 0 }; total[0] = 0; total[1] = 0; state[0] = 0x67452301; state[1] = 0xEFCDAB89; state[2] = 0x98BADCFE; state[3] = 0x10325476; state[4] = 0xC3D2E1F0; iotjs_sha1_update(total, state, buffer, in_buff, buff_len); iotjs_sha1_finish(total, state, buffer, *out_buff); #else /* ENABLE_MODULE_TLS */ mbedtls_sha1_context sha_ctx; mbedtls_sha1_init(&sha_ctx); #if defined(__TIZENRT__) mbedtls_sha1_starts(&sha_ctx); mbedtls_sha1_update(&sha_ctx, in_buff, buff_len); mbedtls_sha1_finish(&sha_ctx, *out_buff); #else /* !__TIZENRT__ */ mbedtls_sha1_starts_ret(&sha_ctx); mbedtls_sha1_update_ret(&sha_ctx, in_buff, buff_len); mbedtls_sha1_finish_ret(&sha_ctx, *out_buff); #endif /* __TIZENRT__ */ mbedtls_sha1_free(&sha_ctx); #endif /* ENABLE_MODULE_TLS */ return sha1_size; } #if ENABLE_MODULE_TLS size_t iotjs_sha256_encode(unsigned char **out_buff, const unsigned char *in_buff, size_t buff_len) { size_t sha256_size = 32; *out_buff = IOTJS_CALLOC(sha256_size, unsigned char); mbedtls_sha256_context sha_ctx; mbedtls_sha256_init(&sha_ctx); #if defined(__TIZENRT__) mbedtls_sha256_starts(&sha_ctx, 0); mbedtls_sha256_update(&sha_ctx, in_buff, buff_len); mbedtls_sha256_finish(&sha_ctx, *out_buff); #else /* !__TIZENRT__ */ mbedtls_sha256_starts_ret(&sha_ctx, 0); mbedtls_sha256_update_ret(&sha_ctx, in_buff, buff_len); mbedtls_sha256_finish_ret(&sha_ctx, *out_buff); #endif /* __TIZENRT__ */ mbedtls_sha256_free(&sha_ctx); return sha256_size; } #endif /* ENABLE_MODULE_TLS */ JS_FUNCTION(sha_encode) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(2, any, number); uint8_t type = JS_GET_ARG(1, number); jerry_value_t jstring = JS_GET_ARG(0, any); iotjs_string_t user_str = iotjs_string_create(); if (!iotjs_jbuffer_as_string(jstring, &user_str)) { return jerry_create_undefined(); } const unsigned char *user_str_data = (const unsigned char *)iotjs_string_data(&user_str); size_t user_str_sz = iotjs_string_size(&user_str); size_t sha_sz = 0; unsigned char *sha_ret = NULL; switch (type) { case IOTJS_CRYPTO_SHA1: { sha_sz = iotjs_sha1_encode(&sha_ret, user_str_data, user_str_sz); break; } case IOTJS_CRYPTO_SHA256: { #if !ENABLE_MODULE_TLS iotjs_string_destroy(&user_str); return JS_CREATE_ERROR(COMMON, no_tls_err_str); #else /* ENABLE_MODULE_TLS */ sha_sz = iotjs_sha256_encode(&sha_ret, user_str_data, user_str_sz); break; #endif /* !ENABLE_MODULE_TLS */ } default: { iotjs_string_destroy(&user_str); return JS_CREATE_ERROR(COMMON, "Unknown SHA hashing algorithm"); } } iotjs_string_destroy(&user_str); jerry_value_t ret_val; ret_val = iotjs_bufferwrap_create_buffer(sha_sz); iotjs_bufferwrap_t *ret_wrap = iotjs_bufferwrap_from_jbuffer(ret_val); memcpy(ret_wrap->buffer, sha_ret, sha_sz); ret_wrap->length = sha_sz; IOTJS_RELEASE(sha_ret); return ret_val; } JS_FUNCTION(rsa_verify) { #if !ENABLE_MODULE_TLS return JS_CREATE_ERROR(COMMON, no_tls_err_str); #else /* ENABLE_MODULE_TLS */ DJS_CHECK_THIS(); DJS_CHECK_ARGS(2, any, any); uint8_t type = JS_GET_ARG(0, number); jerry_value_t jdata = JS_GET_ARG(1, any); jerry_value_t jkey = JS_GET_ARG(2, any); jerry_value_t jsignature = JS_GET_ARG(3, any); iotjs_string_t key = iotjs_string_create(); iotjs_string_t data = iotjs_string_create(); iotjs_string_t signature = iotjs_string_create(); if ((!iotjs_jbuffer_as_string(jkey, &key)) || (!iotjs_jbuffer_as_string(jdata, &data)) || (!iotjs_jbuffer_as_string(jsignature, &signature))) { iotjs_string_destroy(&key); iotjs_string_destroy(&data); iotjs_string_destroy(&signature); return jerry_create_boolean(false); } mbedtls_pk_context pk; char *raw_signature = NULL; size_t raw_signature_sz = iotjs_base64_decode(&raw_signature, iotjs_string_data(&signature), iotjs_string_size(&signature)); mbedtls_pk_init(&pk); int ret_val = mbedtls_pk_parse_public_key(&pk, (const unsigned char *)iotjs_string_data( &key), iotjs_string_size(&key) + 1); jerry_value_t js_ret_val = jerry_create_boolean(true); if ((ret_val = mbedtls_pk_verify(&pk, type, (const unsigned char *)iotjs_string_data(&data), 0, (const unsigned char *)raw_signature, raw_signature_sz))) { js_ret_val = jerry_create_boolean(false); } iotjs_string_destroy(&key); iotjs_string_destroy(&data); iotjs_string_destroy(&signature); mbedtls_pk_free(&pk); IOTJS_RELEASE(raw_signature); return js_ret_val; #endif /* !ENABLE_MODULE_TLS */ } JS_FUNCTION(base64_encode) { DJS_CHECK_THIS(); jerry_value_t jstring = JS_GET_ARG(0, any); iotjs_string_t user_str = iotjs_string_create(); if (!iotjs_jbuffer_as_string(jstring, &user_str)) { return jerry_create_undefined(); } unsigned char *out_buff = NULL; size_t out_size = iotjs_base64_encode(&out_buff, (const unsigned char *)iotjs_string_data(&user_str), iotjs_string_size(&user_str)); iotjs_string_destroy(&user_str); jerry_value_t ret_val = jerry_create_string_sz(out_buff, out_size); IOTJS_RELEASE(out_buff); return ret_val; } jerry_value_t iotjs_init_crypto(void) { jerry_value_t jcrypto = jerry_create_object(); iotjs_jval_set_method(jcrypto, IOTJS_MAGIC_STRING_SHAENCODE, sha_encode); iotjs_jval_set_method(jcrypto, IOTJS_MAGIC_STRING_BASE64ENCODE, base64_encode); iotjs_jval_set_method(jcrypto, IOTJS_MAGIC_STRING_RSAVERIFY, rsa_verify); return jcrypto; } iotjs-1.0+715/src/modules/iotjs_module_crypto.h000066400000000000000000000017341371177304000215270ustar00rootroot00000000000000/* Copyright 2018-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_CRYPTO_H #define IOTJS_MODULE_CRYPTO_H size_t iotjs_sha1_encode(unsigned char **out_buff, const unsigned char *in_buff, size_t buff_len); size_t iotjs_sha256_encode(unsigned char **out_buff, const unsigned char *in_buff, size_t buff_len); #endif /* IOTJS_MODULE_CRYPTO_H */ iotjs-1.0+715/src/modules/iotjs_module_dns.c000066400000000000000000000145031371177304000207640ustar00rootroot00000000000000/* 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_uv_request.h" #if !defined(__NUTTX__) char* getaddrinfo_error_str(int status) { switch (status) { case UV__EAI_ADDRFAMILY: return "EAI_ADDRFAMILY, address family for hostname not supported"; case UV__EAI_AGAIN: return "EAI_AGAIN, temporary failure in name resolution"; case UV__EAI_BADFLAGS: return "EAI_BADFLAGS, bad flags"; case UV__EAI_FAIL: return "EAI_FAIL, Non-recoverable failure in name resolution"; case UV__EAI_FAMILY: return "EAI_FAMILY, family not supported"; case UV__EAI_CANCELED: return "EAI_CANCELED, request canceled"; case UV__EAI_MEMORY: return "EAI_MEMORY, memory allocation failure"; case UV__EAI_NODATA: return "EAI_NODATA, no address association with hostname"; case UV__EAI_NONAME: return "EAI_NONAME, name or service not known"; case UV__EAI_OVERFLOW: return "EAI_OVERFLOW, argument buffer overflow"; case UV__EAI_SERVICE: return "EAI_SERVICE, service not supported"; case UV__EAI_SOCKTYPE: return "EAI_SOCKTYPE, socktype not supported"; case UV__EAI_PROTOCOL: return "EAI_PROTOCOL, unknown error"; default: return "unknown error"; } } static void after_get_addr_info(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { size_t argc = 0; jerry_value_t args[3] = { 0 }; if (status == 0 && res != NULL) { char ip[INET6_ADDRSTRLEN]; int family; const char* addr; struct addrinfo* info; /* search for the first AF_INET entry */ for (info = res; info != NULL; info = info->ai_next) { if (info->ai_family == AF_INET) { break; } } if (info == NULL) { /* Did not find an AF_INET addr, using the first one */ info = res; } IOTJS_ASSERT(info != NULL); if (info->ai_family == AF_INET) { struct sockaddr_in* sockaddr = (struct sockaddr_in*)(info->ai_addr); addr = (char*)(&(sockaddr->sin_addr)); family = 4; } else { struct sockaddr_in6* sockaddr = (struct sockaddr_in6*)(info->ai_addr); addr = (char*)(&(sockaddr->sin6_addr)); family = 6; } int err = uv_inet_ntop(info->ai_family, addr, ip, INET6_ADDRSTRLEN); if (err) { ip[0] = 0; args[argc++] = iotjs_jval_create_error_without_error_flag( "EAFNOSUPPORT, DNS could not resolve hostname"); } else { args[argc++] = jerry_create_null(); } args[argc++] = jerry_create_string_from_utf8((const jerry_char_t*)ip); args[argc++] = jerry_create_number(family); } else { args[argc++] = iotjs_jval_create_error_without_error_flag( getaddrinfo_error_str(status)); } uv_freeaddrinfo(res); // Make the callback into JavaScript jerry_value_t jcallback = *IOTJS_UV_REQUEST_JSCALLBACK(req); iotjs_invoke_callback(jcallback, jerry_create_undefined(), args, argc); for (size_t i = 0; i < argc; i++) { jerry_release_value(args[i]); } iotjs_uv_request_destroy((uv_req_t*)req); } #endif JS_FUNCTION(get_address_info) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(4, string, number, number, function); iotjs_string_t hostname = JS_GET_ARG(0, string); int option = JS_GET_ARG(1, number); int flags = JS_GET_ARG(2, number); int error = 0; const jerry_value_t jcallback = JS_GET_ARG(3, function); int family; if (option == 0) { #if defined(__NUTTX__) || defined(__TIZENRT__) family = AF_INET; #else family = AF_UNSPEC; #endif } else if (option == 4) { family = AF_INET; } else if (option == 6) { family = AF_INET6; } else { iotjs_string_destroy(&hostname); return JS_CREATE_ERROR(TYPE, "bad address family"); } #if defined(__NUTTX__) char ip[INET6_ADDRSTRLEN] = ""; const char* hostname_data = iotjs_string_data(&hostname); if (strcmp(hostname_data, "localhost") == 0) { strncpy(ip, "127.0.0.1", strlen("127.0.0.1") + 1); } else { struct sockaddr_in addr; if (inet_pton(family, hostname_data, &(addr.sin_addr)) == 1) { inet_ntop(family, &(addr.sin_addr), ip, INET6_ADDRSTRLEN); } else { error = EAFNOSUPPORT; } } size_t argc = 0; jerry_value_t args[3] = { 0 }; if (error) { args[argc++] = iotjs_jval_create_error_without_error_flag( "EAFNOSUPPORT, could not resolve hostname"); } else { args[argc++] = jerry_create_null(); } args[argc++] = jerry_create_string_from_utf8((const jerry_char_t*)ip); args[argc++] = jerry_create_number(option); iotjs_invoke_callback(jcallback, jerry_create_undefined(), args, argc); for (size_t i = 0; i < argc; i++) { jerry_release_value(args[i]); } IOTJS_UNUSED(flags); #else uv_req_t* req_addr = iotjs_uv_request_create(sizeof(uv_getaddrinfo_t), jcallback, 0); static const struct addrinfo empty_hints; struct addrinfo hints = empty_hints; hints.ai_family = family; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = flags; error = uv_getaddrinfo(iotjs_environment_loop(iotjs_environment_get()), (uv_getaddrinfo_t*)req_addr, after_get_addr_info, iotjs_string_data(&hostname), NULL, &hints); if (error) { iotjs_uv_request_destroy(req_addr); } #endif iotjs_string_destroy(&hostname); return jerry_create_number(error); } #define SET_CONSTANT(object, constant) \ do { \ iotjs_jval_set_property_number(object, #constant, constant); \ } while (0) jerry_value_t iotjs_init_dns(void) { jerry_value_t dns = jerry_create_object(); iotjs_jval_set_method(dns, IOTJS_MAGIC_STRING_GETADDRINFO, get_address_info); SET_CONSTANT(dns, AI_ADDRCONFIG); SET_CONSTANT(dns, AI_V4MAPPED); return dns; } iotjs-1.0+715/src/modules/iotjs_module_dynamicloader.c000066400000000000000000000046061371177304000230160ustar00rootroot00000000000000/* Copyright 2018-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 "internal/node_api_internal.h" #include "iotjs_def.h" #if _WIN32 #include #else #include #endif #include JS_FUNCTION(open_native_module) { iotjs_string_t location = JS_GET_ARG(0, string); #if _WIN32 // Get a handle to the node module. HINSTANCE handle = LoadLibrary(iotjs_string_data(&location)); #else void* handle = dlopen(iotjs_string_data(&location), RTLD_LAZY); #endif iotjs_string_destroy(&location); // If the handle is valid, try to get the function address. if (handle == NULL) { #if _WIN32 char* err_msg = ""; DWORD dw = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_msg, 0, NULL); #else char* err_msg = dlerror(); #endif jerry_value_t jval_error = jerry_create_error(JERRY_ERROR_COMMON, (jerry_char_t*)err_msg); return jval_error; } jerry_value_t exports = jerry_create_undefined(); int status = napi_module_init_pending(&exports); if (status == napi_module_load_ok) { return exports; } if (status == napi_pending_exception) { /* exports is an error reference */ #if _WIN32 FreeLibrary(handle); #else dlclose(handle); #endif return exports; } if (status == napi_module_no_nm_register_func) { #if _WIN32 FreeLibrary(handle); #else dlclose(handle); #endif jerry_value_t jval_error = jerry_create_error( JERRY_ERROR_COMMON, (jerry_char_t*)"Module has no declared entry point."); return jval_error; } return exports; } jerry_value_t iotjs_init_dynamicloader(void) { return jerry_create_external_function(open_native_module); } iotjs-1.0+715/src/modules/iotjs_module_fs.c000066400000000000000000000346501371177304000206150ustar00rootroot00000000000000/* 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 "iotjs_uv_request.h" jerry_value_t make_stat_object(uv_stat_t* statbuf); static jerry_value_t iotjs_create_uv_exception(int errorno, const char* syscall) { static char msg[256]; snprintf(msg, sizeof(msg), "'%s' %s", syscall, uv_strerror(errorno)); return iotjs_jval_create_error_without_error_flag(msg); } static void fs_after_async(uv_fs_t* req) { const jerry_value_t cb = *IOTJS_UV_REQUEST_JSCALLBACK(req); IOTJS_ASSERT(jerry_value_is_function(cb)); jerry_value_t jargs[2] = { 0 }; size_t jargc = 0; if (req->result < 0) { jerry_value_t jerror = iotjs_create_uv_exception(req->result, "open"); jargs[jargc++] = jerror; } else { jargs[jargc++] = jerry_create_null(); switch (req->fs_type) { case UV_FS_CLOSE: { break; } case UV_FS_OPEN: case UV_FS_READ: case UV_FS_WRITE: { jargs[jargc++] = jerry_create_number((double)req->result); break; } case UV_FS_SCANDIR: { int r; uv_dirent_t ent; uint32_t idx = 0; jargs[jargc++] = jerry_create_array(0); while ((r = uv_fs_scandir_next(req, &ent)) != UV_EOF) { jerry_value_t name = jerry_create_string((const jerry_char_t*)ent.name); iotjs_jval_set_property_by_index(jargs[1], idx, name); jerry_release_value(name); idx++; } break; } case UV_FS_FSTAT: case UV_FS_STAT: { uv_stat_t s = (req->statbuf); jargs[jargc++] = make_stat_object(&s); break; } default: { break; } } } iotjs_invoke_callback(cb, jerry_create_undefined(), jargs, jargc); jerry_release_value(jargs[0]); jerry_release_value(jargs[1]); uv_fs_req_cleanup(req); iotjs_uv_request_destroy((uv_req_t*)req); } static jerry_value_t fs_after_sync(uv_fs_t* req, int err, const char* syscall_name) { if (err < 0) { jerry_value_t jvalue = iotjs_create_uv_exception(err, syscall_name); jerry_value_t jerror = jerry_create_error_from_value(jvalue, true); return jerror; } switch (req->fs_type) { case UV_FS_CLOSE: break; case UV_FS_OPEN: case UV_FS_READ: case UV_FS_WRITE: return jerry_create_number(err); case UV_FS_FSTAT: case UV_FS_STAT: { uv_stat_t* s = &(req->statbuf); return make_stat_object(s); } case UV_FS_MKDIR: case UV_FS_RMDIR: case UV_FS_UNLINK: case UV_FS_RENAME: return jerry_create_undefined(); case UV_FS_SCANDIR: { int r; uv_dirent_t ent; uint32_t idx = 0; jerry_value_t ret = jerry_create_array(0); while ((r = uv_fs_scandir_next(req, &ent)) != UV_EOF) { jerry_value_t name = jerry_create_string((const jerry_char_t*)ent.name); iotjs_jval_set_property_by_index(ret, idx, name); jerry_release_value(name); idx++; } return ret; } default: { IOTJS_ASSERT(false); break; } } return jerry_create_undefined(); } static inline bool is_within_bounds(size_t off, size_t len, size_t max) { if (off >= max || max - off < len) return false; return true; } #define FS_ASYNC(env, syscall, pcallback, ...) \ uv_fs_t* fs_req = \ (uv_fs_t*)iotjs_uv_request_create(sizeof(uv_fs_t), pcallback, 0); \ int err = uv_fs_##syscall(iotjs_environment_loop(env), fs_req, __VA_ARGS__, \ fs_after_async); \ if (err < 0) { \ fs_req->result = err; \ fs_after_async(fs_req); \ } \ ret_value = jerry_create_null(); #define FS_SYNC(env, syscall, ...) \ uv_fs_t fs_req; \ int err = uv_fs_##syscall(iotjs_environment_loop(env), &fs_req, __VA_ARGS__, \ NULL); \ ret_value = fs_after_sync(&fs_req, err, #syscall); \ uv_fs_req_cleanup(&fs_req); JS_FUNCTION(fs_close) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, number); DJS_CHECK_ARG_IF_EXIST(1, function); const iotjs_environment_t* env = iotjs_environment_get(); int fd = JS_GET_ARG(0, number); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); jerry_value_t ret_value; if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, close, jcallback, fd); } else { FS_SYNC(env, close, fd); } return ret_value; } JS_FUNCTION(fs_open) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(3, string, number, number); DJS_CHECK_ARG_IF_EXIST(3, function); const iotjs_environment_t* env = iotjs_environment_get(); iotjs_string_t path = JS_GET_ARG(0, string); int flags = JS_GET_ARG(1, number); int mode = JS_GET_ARG(2, number); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(3, function); jerry_value_t ret_value; if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, open, jcallback, iotjs_string_data(&path), flags, mode); } else { FS_SYNC(env, open, iotjs_string_data(&path), flags, mode); } iotjs_string_destroy(&path); return ret_value; } typedef enum { IOTJS_FS_READ, IOTJS_FS_WRITE } iotjs_fs_op_t; jerry_value_t fs_do_read_or_write(const jerry_value_t jfunc, const jerry_value_t jthis, const jerry_value_t jargv[], const jerry_length_t jargc, const iotjs_fs_op_t fs_op) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(5, number, object, number, number, number); DJS_CHECK_ARG_IF_EXIST(5, function); const iotjs_environment_t* env = iotjs_environment_get(); int fd = JS_GET_ARG(0, number); const jerry_value_t jbuffer = JS_GET_ARG(1, object); size_t offset = JS_GET_ARG(2, number); size_t length = JS_GET_ARG(3, number); int position = JS_GET_ARG(4, number); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(5, function); iotjs_bufferwrap_t* buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuffer); char* data = buffer_wrap->buffer; size_t data_length = iotjs_bufferwrap_length(buffer_wrap); DJS_CHECK(data != NULL && data_length > 0); if (!is_within_bounds(offset, length, data_length)) { return JS_CREATE_ERROR(RANGE, "length out of bound"); } uv_buf_t uvbuf = uv_buf_init(data + offset, length); jerry_value_t ret_value; if (fs_op == IOTJS_FS_READ) { if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, read, jcallback, fd, &uvbuf, 1, position); } else { FS_SYNC(env, read, fd, &uvbuf, 1, position); } } else { if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, write, jcallback, fd, &uvbuf, 1, position); } else { FS_SYNC(env, write, fd, &uvbuf, 1, position); } } return ret_value; } JS_FUNCTION(fs_read) { return fs_do_read_or_write(jfunc, jthis, jargv, jargc, IOTJS_FS_READ); } JS_FUNCTION(fs_write) { return fs_do_read_or_write(jfunc, jthis, jargv, jargc, IOTJS_FS_WRITE); } jerry_value_t make_stat_object(uv_stat_t* statbuf) { const jerry_value_t fs = iotjs_module_get("fs"); jerry_value_t stat_prototype = iotjs_jval_get_property(fs, IOTJS_MAGIC_STRING_STATS); IOTJS_ASSERT(jerry_value_is_object(stat_prototype)); jerry_value_t jstat = jerry_create_object(); iotjs_jval_set_prototype(jstat, stat_prototype); jerry_release_value(stat_prototype); #define X(statobj, name) \ iotjs_jval_set_property_number(statobj, #name, statbuf->st_##name); X(jstat, dev) X(jstat, mode) X(jstat, nlink) X(jstat, uid) X(jstat, gid) X(jstat, rdev) X(jstat, blksize) X(jstat, ino) X(jstat, size) X(jstat, blocks) #undef X return jstat; } JS_FUNCTION(fs_stat) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, string); DJS_CHECK_ARG_IF_EXIST(1, function); const iotjs_environment_t* env = iotjs_environment_get(); iotjs_string_t path = JS_GET_ARG(0, string); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); jerry_value_t ret_value; if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, stat, jcallback, iotjs_string_data(&path)); } else { FS_SYNC(env, stat, iotjs_string_data(&path)); } iotjs_string_destroy(&path); return ret_value; } JS_FUNCTION(fs_fstat) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, number); DJS_CHECK_ARG_IF_EXIST(1, function); const iotjs_environment_t* env = iotjs_environment_get(); int fd = JS_GET_ARG(0, number); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); jerry_value_t ret_value; if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, fstat, jcallback, fd); } else { FS_SYNC(env, fstat, fd); } return ret_value; } JS_FUNCTION(fs_mkdir) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(2, string, number); DJS_CHECK_ARG_IF_EXIST(2, function); const iotjs_environment_t* env = iotjs_environment_get(); iotjs_string_t path = JS_GET_ARG(0, string); int mode = JS_GET_ARG(1, number); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(2, function); jerry_value_t ret_value; if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, mkdir, jcallback, iotjs_string_data(&path), mode); } else { FS_SYNC(env, mkdir, iotjs_string_data(&path), mode); } iotjs_string_destroy(&path); return ret_value; } JS_FUNCTION(fs_rmdir) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, string); DJS_CHECK_ARG_IF_EXIST(1, function); const iotjs_environment_t* env = iotjs_environment_get(); iotjs_string_t path = JS_GET_ARG(0, string); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); jerry_value_t ret_value; if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, rmdir, jcallback, iotjs_string_data(&path)); } else { FS_SYNC(env, rmdir, iotjs_string_data(&path)); } iotjs_string_destroy(&path); return ret_value; } JS_FUNCTION(fs_unlink) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, string); DJS_CHECK_ARG_IF_EXIST(1, function); const iotjs_environment_t* env = iotjs_environment_get(); iotjs_string_t path = JS_GET_ARG(0, string); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); jerry_value_t ret_value; if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, unlink, jcallback, iotjs_string_data(&path)); } else { FS_SYNC(env, unlink, iotjs_string_data(&path)); } iotjs_string_destroy(&path); return ret_value; } JS_FUNCTION(fs_rename) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(2, string, string); DJS_CHECK_ARG_IF_EXIST(2, function); const iotjs_environment_t* env = iotjs_environment_get(); iotjs_string_t old_path = JS_GET_ARG(0, string); iotjs_string_t new_path = JS_GET_ARG(1, string); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(2, function); jerry_value_t ret_value; if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, rename, jcallback, iotjs_string_data(&old_path), iotjs_string_data(&new_path)); } else { FS_SYNC(env, rename, iotjs_string_data(&old_path), iotjs_string_data(&new_path)); } iotjs_string_destroy(&old_path); iotjs_string_destroy(&new_path); return ret_value; } JS_FUNCTION(fs_read_dir) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, string); DJS_CHECK_ARG_IF_EXIST(1, function); const iotjs_environment_t* env = iotjs_environment_get(); iotjs_string_t path = JS_GET_ARG(0, string); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); jerry_value_t ret_value; if (!jerry_value_is_null(jcallback)) { FS_ASYNC(env, scandir, jcallback, iotjs_string_data(&path), 0); } else { FS_SYNC(env, scandir, iotjs_string_data(&path), 0); } iotjs_string_destroy(&path); return ret_value; } static jerry_value_t stats_is_typeof(jerry_value_t stats, int type) { jerry_value_t mode = iotjs_jval_get_property(stats, IOTJS_MAGIC_STRING_MODE); if (!jerry_value_is_number(mode)) { jerry_release_value(mode); return JS_CREATE_ERROR(TYPE, "fstat: file mode should be a number"); } int mode_number = (int)iotjs_jval_as_number(mode); jerry_release_value(mode); return jerry_create_boolean((mode_number & S_IFMT) == type); } JS_FUNCTION(fs_stats_is_directory) { DJS_CHECK_THIS(); jerry_value_t stats = JS_GET_THIS(); return stats_is_typeof(stats, S_IFDIR); } JS_FUNCTION(fs_stats_is_file) { DJS_CHECK_THIS(); jerry_value_t stats = JS_GET_THIS(); return stats_is_typeof(stats, S_IFREG); } jerry_value_t iotjs_init_fs(void) { jerry_value_t fs = jerry_create_object(); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_CLOSE, fs_close); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_OPEN, fs_open); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_READ, fs_read); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_WRITE, fs_write); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_STAT, fs_stat); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_FSTAT, fs_fstat); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_MKDIR, fs_mkdir); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_RMDIR, fs_rmdir); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_UNLINK, fs_unlink); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_RENAME, fs_rename); iotjs_jval_set_method(fs, IOTJS_MAGIC_STRING_READDIR, fs_read_dir); jerry_value_t stats_prototype = jerry_create_object(); iotjs_jval_set_method(stats_prototype, IOTJS_MAGIC_STRING_ISDIRECTORY, fs_stats_is_directory); iotjs_jval_set_method(stats_prototype, IOTJS_MAGIC_STRING_ISFILE, fs_stats_is_file); iotjs_jval_set_property_jval(fs, IOTJS_MAGIC_STRING_STATS, stats_prototype); jerry_release_value(stats_prototype); return fs; } iotjs-1.0+715/src/modules/iotjs_module_gpio.c000066400000000000000000000277311371177304000211450ustar00rootroot00000000000000/* 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_gpio.h" #include "iotjs_uv_request.h" IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(gpio); IOTJS_DEFINE_PERIPH_CREATE_FUNCTION(gpio); static void iotjs_gpio_destroy(iotjs_gpio_t* gpio) { iotjs_gpio_destroy_platform_data(gpio->platform_data); IOTJS_RELEASE(gpio); } static void gpio_worker(uv_work_t* work_req) { iotjs_periph_data_t* worker_data = (iotjs_periph_data_t*)IOTJS_UV_REQUEST_EXTRA_DATA(work_req); iotjs_gpio_t* gpio = (iotjs_gpio_t*)worker_data->data; switch (worker_data->op) { case kGpioOpOpen: worker_data->result = iotjs_gpio_open(gpio); break; case kGpioOpWrite: worker_data->result = iotjs_gpio_write(gpio); break; case kGpioOpRead: worker_data->result = iotjs_gpio_read(gpio); break; case kGpioOpClose: worker_data->result = iotjs_gpio_close(gpio); break; default: IOTJS_ASSERT(!"Invalid Operation"); } } static jerry_value_t gpio_set_configuration(iotjs_gpio_t* gpio, jerry_value_t jconfigurable) { jerry_value_t jpin = iotjs_jval_get_property(jconfigurable, IOTJS_MAGIC_STRING_PIN); double pin = -1.0; if (!jerry_value_is_number(jpin) || (pin = iotjs_jval_as_number(jpin)) < 0) { jerry_release_value(jpin); return JS_CREATE_ERROR(TYPE, "Bad arguments gpio.pin should be a number"); } gpio->pin = (uint32_t)pin; jerry_release_value(jpin); // Direction jerry_value_t jdirection = iotjs_jval_get_property(jconfigurable, IOTJS_MAGIC_STRING_DIRECTION); if (jerry_value_is_undefined(jdirection)) { gpio->direction = kGpioDirectionOut; } else { if (jerry_value_is_number(jdirection)) { gpio->direction = (GpioDirection)iotjs_jval_as_number(jdirection); } else { gpio->direction = __kGpioDirectionMax; } if (gpio->direction >= __kGpioDirectionMax) { jerry_release_value(jdirection); return JS_CREATE_ERROR( TYPE, "Bad arguments - gpio.direction should be DIRECTION.IN or OUT"); } } jerry_release_value(jdirection); // Mode jerry_value_t jmode = iotjs_jval_get_property(jconfigurable, IOTJS_MAGIC_STRING_MODE); if (jerry_value_is_undefined(jmode)) { gpio->mode = kGpioModeNone; } else { if (jerry_value_is_number(jmode)) { gpio->mode = (GpioMode)iotjs_jval_as_number(jmode); } else { gpio->mode = __kGpioModeMax; } if (gpio->mode >= __kGpioModeMax) { return JS_CREATE_ERROR(TYPE, "Bad arguments - gpio.mode should be MODE.NONE, " "PULLUP, PULLDOWN, FLOAT, PUSHPULL or OPENDRAIN"); } else if (gpio->direction == kGpioDirectionIn && gpio->mode != kGpioModeNone && gpio->mode != kGpioModePullup && gpio->mode != kGpioModePulldown) { return JS_CREATE_ERROR(TYPE, "Bad arguments - DIRECTION.IN only supports " "MODE.NONE, PULLUP and PULLDOWN"); } else if (gpio->direction == kGpioDirectionOut && gpio->mode != kGpioModeNone && gpio->mode != kGpioModeFloat && gpio->mode != kGpioModePushpull && gpio->mode != kGpioModeOpendrain) { return JS_CREATE_ERROR(TYPE, "Bad arguments - DIRECTION.OUT only supports " "MODE.NONE, FLOAT, PUSHPULL and OPENDRAIN"); } } jerry_release_value(jmode); // Edge jerry_value_t jedge = iotjs_jval_get_property(jconfigurable, IOTJS_MAGIC_STRING_EDGE); if (jerry_value_is_undefined(jedge)) { gpio->edge = kGpioEdgeNone; } else { if (jerry_value_is_number(jedge)) { gpio->edge = (GpioEdge)iotjs_jval_as_number(jedge); } else { gpio->edge = __kGpioEdgeMax; } if (gpio->edge >= __kGpioEdgeMax) { jerry_release_value(jedge); return JS_CREATE_ERROR(TYPE, "Bad arguments - gpio.edge should be EDGE.NONE, " "RISING, FALLING or BOTH"); } } jerry_release_value(jedge); return jerry_create_undefined(); } JS_FUNCTION(gpio_constructor) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, object); DJS_CHECK_ARG_IF_EXIST(1, function); // Create GPIO object const jerry_value_t jgpio = JS_GET_THIS(); iotjs_gpio_t* gpio = gpio_create(jgpio); jerry_value_t config_res = gpio_set_configuration(gpio, JS_GET_ARG(0, object)); if (jerry_value_is_error(config_res)) { return config_res; } IOTJS_ASSERT(jerry_value_is_undefined(config_res)); const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); // If the callback doesn't exist, it is completed synchronously. // Otherwise, it will be executed asynchronously. if (!jerry_value_is_null(jcallback)) { iotjs_periph_call_async(gpio, jcallback, kGpioOpOpen, gpio_worker); } else if (!iotjs_gpio_open(gpio)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kGpioOpOpen)); } return jerry_create_undefined(); } JS_FUNCTION(gpio_close) { JS_DECLARE_THIS_PTR(gpio, gpio); DJS_CHECK_ARG_IF_EXIST(0, function); iotjs_periph_call_async(gpio, JS_GET_ARG_IF_EXIST(0, function), kGpioOpClose, gpio_worker); return jerry_create_undefined(); } JS_FUNCTION(gpio_close_sync) { JS_DECLARE_THIS_PTR(gpio, gpio); if (!iotjs_gpio_close(gpio)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kGpioOpClose)); } return jerry_create_undefined(); } typedef enum { IOTJS_GPIO_WRITE, IOTJS_GPIO_WRITESYNC } iotjs_gpio_op_t; jerry_value_t gpio_do_write_or_writesync(const jerry_value_t jfunc, const jerry_value_t jthis, const jerry_value_t jargv[], const jerry_length_t jargc, const iotjs_gpio_op_t gpio_op) { JS_DECLARE_THIS_PTR(gpio, gpio); bool value; if (jerry_value_is_number(jargv[0])) { value = (bool)jerry_get_number_value(jargv[0]); } else if (jerry_value_is_boolean(jargv[0])) { value = jerry_get_boolean_value(jargv[0]); } else { const jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); if (gpio_op == IOTJS_GPIO_WRITE && !jerry_value_is_null(jcallback)) { const char* error_msg = iotjs_periph_error_str(kGpioOpWrite); jerry_value_t error_str = jerry_create_string((jerry_char_t*)error_msg); iotjs_invoke_callback(jcallback, jthis, &error_str, 1); jerry_release_value(error_str); return jerry_create_undefined(); } return JS_CREATE_ERROR(TYPE, "GPIO WriteSync Error - Wrong argument type"); } gpio->value = value; if (gpio_op == IOTJS_GPIO_WRITE) { DJS_CHECK_ARG_IF_EXIST(1, function); iotjs_periph_call_async(gpio, JS_GET_ARG_IF_EXIST(1, function), kGpioOpWrite, gpio_worker); } else { if (!iotjs_gpio_write(gpio)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kGpioOpWrite)); } } return jerry_create_undefined(); } JS_FUNCTION(gpio_write) { return gpio_do_write_or_writesync(jfunc, jthis, jargv, jargc, IOTJS_GPIO_WRITE); } JS_FUNCTION(gpio_write_sync) { return gpio_do_write_or_writesync(jfunc, jthis, jargv, jargc, IOTJS_GPIO_WRITESYNC); } JS_FUNCTION(gpio_read) { JS_DECLARE_THIS_PTR(gpio, gpio); DJS_CHECK_ARG_IF_EXIST(0, function); iotjs_periph_call_async(gpio, JS_GET_ARG_IF_EXIST(0, function), kGpioOpRead, gpio_worker); return jerry_create_undefined(); } JS_FUNCTION(gpio_read_sync) { JS_DECLARE_THIS_PTR(gpio, gpio); if (!iotjs_gpio_read(gpio)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kGpioOpRead)); } return jerry_create_boolean(gpio->value); } JS_FUNCTION(gpio_set_direction_sync) { DJS_CHECK_ARGS(1, number); JS_DECLARE_THIS_PTR(gpio, gpio); int direction; JS_GET_REQUIRED_ARG_VALUE(0, direction, IOTJS_MAGIC_STRING_DIRECTION, number); if (direction >= __kGpioDirectionMax) { return JS_CREATE_ERROR( TYPE, "Bad arguments - gpio.direction should be DIRECTION.IN or OUT"); } gpio->direction = direction; if (!iotjs_gpio_set_direction(gpio)) { return JS_CREATE_ERROR( COMMON, "GPIO SetDirectionSync Error - Cannot set direction"); } return jerry_create_undefined(); } jerry_value_t iotjs_init_gpio(void) { jerry_value_t jgpio_const = jerry_create_external_function(gpio_constructor); jerry_value_t jprototype = jerry_create_object(); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_CLOSE, gpio_close); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_CLOSESYNC, gpio_close_sync); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_WRITE, gpio_write); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_WRITESYNC, gpio_write_sync); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_READ, gpio_read); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_READSYNC, gpio_read_sync); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_SETDIRECTIONSYNC, gpio_set_direction_sync); iotjs_jval_set_property_jval(jgpio_const, IOTJS_MAGIC_STRING_PROTOTYPE, jprototype); jerry_release_value(jprototype); // GPIO direction properties jerry_value_t jdirection = jerry_create_object(); iotjs_jval_set_property_number(jdirection, IOTJS_MAGIC_STRING_IN, kGpioDirectionIn); iotjs_jval_set_property_number(jdirection, IOTJS_MAGIC_STRING_OUT_U, kGpioDirectionOut); iotjs_jval_set_property_jval(jgpio_const, IOTJS_MAGIC_STRING_DIRECTION_U, jdirection); jerry_release_value(jdirection); // GPIO mode properties jerry_value_t jmode = jerry_create_object(); iotjs_jval_set_property_number(jmode, IOTJS_MAGIC_STRING_NONE_U, kGpioModeNone); #if defined(__NUTTX__) iotjs_jval_set_property_number(jmode, IOTJS_MAGIC_STRING_PULLUP_U, kGpioModePullup); iotjs_jval_set_property_number(jmode, IOTJS_MAGIC_STRING_PULLDOWN_U, kGpioModePulldown); iotjs_jval_set_property_number(jmode, IOTJS_MAGIC_STRING_FLOAT_U, kGpioModeFloat); iotjs_jval_set_property_number(jmode, IOTJS_MAGIC_STRING_PUSHPULL_U, kGpioModePushpull); iotjs_jval_set_property_number(jmode, IOTJS_MAGIC_STRING_OPENDRAIN_U, kGpioModeOpendrain); #endif iotjs_jval_set_property_jval(jgpio_const, IOTJS_MAGIC_STRING_MODE_U, jmode); jerry_release_value(jmode); // GPIO edge properties jerry_value_t jedge = jerry_create_object(); iotjs_jval_set_property_number(jedge, IOTJS_MAGIC_STRING_NONE_U, kGpioEdgeNone); iotjs_jval_set_property_number(jedge, IOTJS_MAGIC_STRING_RISING_U, kGpioEdgeRising); iotjs_jval_set_property_number(jedge, IOTJS_MAGIC_STRING_FALLING_U, kGpioEdgeFalling); iotjs_jval_set_property_number(jedge, IOTJS_MAGIC_STRING_BOTH_U, kGpioEdgeBoth); iotjs_jval_set_property_jval(jgpio_const, IOTJS_MAGIC_STRING_EDGE_U, jedge); jerry_release_value(jedge); return jgpio_const; } iotjs-1.0+715/src/modules/iotjs_module_gpio.h000066400000000000000000000036761371177304000211540ustar00rootroot00000000000000/* 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_MODULE_GPIO_H #define IOTJS_MODULE_GPIO_H #include "iotjs_def.h" #include "iotjs_module_periph_common.h" typedef enum { kGpioDirectionIn = 0, kGpioDirectionOut, __kGpioDirectionMax } GpioDirection; typedef enum { kGpioModeNone = 0, kGpioModePullup, kGpioModePulldown, kGpioModeFloat, kGpioModePushpull, kGpioModeOpendrain, __kGpioModeMax } GpioMode; typedef enum { kGpioEdgeNone = 0, kGpioEdgeRising, kGpioEdgeFalling, kGpioEdgeBoth, __kGpioEdgeMax } GpioEdge; typedef struct iotjs_gpio_platform_data_s iotjs_gpio_platform_data_t; // This Gpio class provides interfaces for GPIO operation. typedef struct { jerry_value_t jobject; iotjs_gpio_platform_data_t* platform_data; bool value; uint32_t pin; GpioDirection direction; GpioMode mode; GpioEdge edge; } iotjs_gpio_t; bool iotjs_gpio_open(iotjs_gpio_t* gpio); bool iotjs_gpio_write(iotjs_gpio_t* gpio); bool iotjs_gpio_read(iotjs_gpio_t* gpio); bool iotjs_gpio_close(iotjs_gpio_t* gpio); bool iotjs_gpio_set_direction(iotjs_gpio_t* gpio); // Platform-related functions; they are implemented // by platform code (i.e.: linux, nuttx, tizen). void iotjs_gpio_create_platform_data(iotjs_gpio_t* gpio); void iotjs_gpio_destroy_platform_data( iotjs_gpio_platform_data_t* platform_data); #endif /* IOTJS_MODULE_GPIO_H */ iotjs-1.0+715/src/modules/iotjs_module_http_parser.c000066400000000000000000000402231371177304000225310ustar00rootroot00000000000000/* 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 #include #include #include "http_parser.h" // If # of header fields == HEADER_MAX, flush header to JS side. // This is weired : # of maximum headers in C equals to HEADER_MAX-1. // This is because , OnHeaders cb, we increase n_fields first, // and check whether field == HEADER_MAX. // ex) HEADER_MAX 2 means that we can keep at most 1 header field/value // during http parsing. // Increase this to minimize inter JS-C call #define HEADER_MAX 10 typedef struct { jerry_value_t jobject; http_parser parser; iotjs_string_t url; iotjs_string_t status_msg; iotjs_string_t fields[HEADER_MAX]; iotjs_string_t values[HEADER_MAX]; size_t n_fields; size_t n_values; jerry_value_t cur_jbuf; char* cur_buf; size_t cur_buf_len; bool flushed; } iotjs_http_parserwrap_t; typedef enum http_parser_type http_parser_type; static void iotjs_http_parserwrap_initialize( iotjs_http_parserwrap_t* http_parserwrap, http_parser_type type) { http_parser_init(&http_parserwrap->parser, type); iotjs_string_destroy(&http_parserwrap->url); iotjs_string_destroy(&http_parserwrap->status_msg); http_parserwrap->n_fields = 0; http_parserwrap->n_values = 0; http_parserwrap->flushed = false; http_parserwrap->cur_jbuf = jerry_create_null(); http_parserwrap->cur_buf = NULL; http_parserwrap->cur_buf_len = 0; } IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(http_parserwrap); static void iotjs_http_parserwrap_create(const jerry_value_t jparser, http_parser_type type) { iotjs_http_parserwrap_t* http_parserwrap = IOTJS_ALLOC(iotjs_http_parserwrap_t); http_parserwrap->jobject = jparser; jerry_set_object_native_pointer(jparser, http_parserwrap, &this_module_native_info); http_parserwrap->url = iotjs_string_create(); http_parserwrap->status_msg = iotjs_string_create(); for (size_t i = 0; i < HEADER_MAX; i++) { http_parserwrap->fields[i] = iotjs_string_create(); http_parserwrap->values[i] = iotjs_string_create(); } iotjs_http_parserwrap_initialize(http_parserwrap, type); http_parserwrap->parser.data = http_parserwrap; IOTJS_ASSERT(jerry_value_is_object(http_parserwrap->jobject)); } static void iotjs_http_parserwrap_destroy( iotjs_http_parserwrap_t* http_parserwrap) { iotjs_string_destroy(&http_parserwrap->url); iotjs_string_destroy(&http_parserwrap->status_msg); for (size_t i = 0; i < HEADER_MAX; i++) { iotjs_string_destroy(&http_parserwrap->fields[i]); iotjs_string_destroy(&http_parserwrap->values[i]); } IOTJS_RELEASE(http_parserwrap); } static jerry_value_t iotjs_http_parserwrap_make_header( iotjs_http_parserwrap_t* http_parserwrap) { jerry_value_t jheader = jerry_create_array(http_parserwrap->n_values * 2); for (size_t i = 0; i < http_parserwrap->n_values; i++) { jerry_value_t f = iotjs_jval_create_string(&http_parserwrap->fields[i]); jerry_value_t v = iotjs_jval_create_string(&http_parserwrap->values[i]); iotjs_jval_set_property_by_index(jheader, i * 2, f); iotjs_jval_set_property_by_index(jheader, i * 2 + 1, v); jerry_release_value(f); jerry_release_value(v); } return jheader; } static void iotjs_http_parserwrap_flush( iotjs_http_parserwrap_t* http_parserwrap) { const jerry_value_t jobj = http_parserwrap->jobject; jerry_value_t func = iotjs_jval_get_property(jobj, IOTJS_MAGIC_STRING_ONHEADERS); IOTJS_ASSERT(jerry_value_is_function(func)); jerry_value_t jheader = iotjs_http_parserwrap_make_header(http_parserwrap); size_t argc = 1; jerry_value_t argv[2] = { jheader, 0 }; if (http_parserwrap->parser.type == HTTP_REQUEST && !iotjs_string_is_empty(&http_parserwrap->url)) { argv[argc++] = iotjs_jval_create_string(&http_parserwrap->url); } iotjs_invoke_callback(func, jobj, argv, argc); iotjs_string_destroy(&http_parserwrap->url); for (size_t i = 0; i < argc; i++) { jerry_release_value(argv[i]); } jerry_release_value(func); http_parserwrap->flushed = true; } static void iotjs_http_parserwrap_set_buf( iotjs_http_parserwrap_t* http_parserwrap, jerry_value_t jbuf, char* buf, size_t sz) { http_parserwrap->cur_jbuf = jbuf; http_parserwrap->cur_buf = buf; http_parserwrap->cur_buf_len = sz; } // http-parser callbacks static int iotjs_http_parserwrap_on_message_begin(http_parser* parser) { iotjs_http_parserwrap_t* http_parserwrap = (iotjs_http_parserwrap_t*)(parser->data); iotjs_string_destroy(&http_parserwrap->url); iotjs_string_destroy(&http_parserwrap->status_msg); return 0; } static int iotjs_http_parserwrap_on_url(http_parser* parser, const char* at, size_t length) { iotjs_http_parserwrap_t* http_parserwrap = (iotjs_http_parserwrap_t*)(parser->data); iotjs_string_append(&http_parserwrap->url, at, length); return 0; } static int iotjs_http_parserwrap_on_status(http_parser* parser, const char* at, size_t length) { iotjs_http_parserwrap_t* http_parserwrap = (iotjs_http_parserwrap_t*)(parser->data); iotjs_string_append(&http_parserwrap->status_msg, at, length); return 0; } static int iotjs_http_parserwrap_on_header_field(http_parser* parser, const char* at, size_t length) { iotjs_http_parserwrap_t* http_parserwrap = (iotjs_http_parserwrap_t*)(parser->data); if (http_parserwrap->n_fields == http_parserwrap->n_values) { http_parserwrap->n_fields++; // values and fields are flushed to JS // before corresponding OnHeaderValue is called. if (http_parserwrap->n_fields == HEADER_MAX) { iotjs_http_parserwrap_flush(http_parserwrap); // to JS world http_parserwrap->n_fields = 1; http_parserwrap->n_values = 0; } iotjs_string_destroy( &http_parserwrap->fields[http_parserwrap->n_fields - 1]); } IOTJS_ASSERT(http_parserwrap->n_fields == http_parserwrap->n_values + 1); iotjs_string_append(&http_parserwrap->fields[http_parserwrap->n_fields - 1], at, length); return 0; } static int iotjs_http_parserwrap_on_header_value(http_parser* parser, const char* at, size_t length) { iotjs_http_parserwrap_t* http_parserwrap = (iotjs_http_parserwrap_t*)(parser->data); if (http_parserwrap->n_fields != http_parserwrap->n_values) { http_parserwrap->n_values++; iotjs_string_destroy( &http_parserwrap->values[http_parserwrap->n_values - 1]); } IOTJS_ASSERT(http_parserwrap->n_fields == http_parserwrap->n_values); iotjs_string_append(&http_parserwrap->values[http_parserwrap->n_values - 1], at, length); return 0; } static int iotjs_http_parserwrap_on_headers_complete(http_parser* parser) { iotjs_http_parserwrap_t* http_parserwrap = (iotjs_http_parserwrap_t*)(parser->data); const jerry_value_t jobj = http_parserwrap->jobject; jerry_value_t func = iotjs_jval_get_property(jobj, IOTJS_MAGIC_STRING_ONHEADERSCOMPLETE); IOTJS_ASSERT(jerry_value_is_function(func)); // URL jerry_value_t info = jerry_create_object(); if (http_parserwrap->flushed) { // If some headers already are flushed, // flush the remaining headers. // In Flush function, url is already flushed to JS. iotjs_http_parserwrap_flush(http_parserwrap); } else { // Here, there was no flushed header. // We need to make a new header object with all header fields jerry_value_t jheader = iotjs_http_parserwrap_make_header(http_parserwrap); iotjs_jval_set_property_jval(info, IOTJS_MAGIC_STRING_HEADERS, jheader); jerry_release_value(jheader); if (http_parserwrap->parser.type == HTTP_REQUEST) { IOTJS_ASSERT(!iotjs_string_is_empty(&http_parserwrap->url)); iotjs_jval_set_property_string(info, IOTJS_MAGIC_STRING_URL, &http_parserwrap->url); } } http_parserwrap->n_fields = http_parserwrap->n_values = 0; // Method if (http_parserwrap->parser.type == HTTP_REQUEST) { iotjs_jval_set_property_number(info, IOTJS_MAGIC_STRING_METHOD, http_parserwrap->parser.method); } // Status else if (http_parserwrap->parser.type == HTTP_RESPONSE) { iotjs_jval_set_property_number(info, IOTJS_MAGIC_STRING_STATUS, http_parserwrap->parser.status_code); iotjs_jval_set_property_string(info, IOTJS_MAGIC_STRING_STATUS_MSG, &http_parserwrap->status_msg); } // For future support, current http_server module does not support // upgrade and keepalive. // upgrade iotjs_jval_set_property_boolean(info, IOTJS_MAGIC_STRING_UPGRADE, http_parserwrap->parser.upgrade); // shouldkeepalive iotjs_jval_set_property_boolean(info, IOTJS_MAGIC_STRING_SHOULDKEEPALIVE, http_should_keep_alive( &http_parserwrap->parser)); // http version number iotjs_jval_set_property_number(info, IOTJS_MAGIC_STRING_HTTP_VERSION_MAJOR, parser->http_major); iotjs_jval_set_property_number(info, IOTJS_MAGIC_STRING_HTTP_VERSION_MINOR, parser->http_minor); jerry_value_t res = iotjs_invoke_callback_with_result(func, jobj, &info, 1); int ret = 1; if (jerry_value_is_boolean(res)) { ret = iotjs_jval_as_boolean(res); } else if (jerry_value_is_error(res)) { ret = 0; } jerry_release_value(func); jerry_release_value(res); jerry_release_value(info); return ret; } static int iotjs_http_parserwrap_on_body(http_parser* parser, const char* at, size_t length) { iotjs_http_parserwrap_t* http_parserwrap = (iotjs_http_parserwrap_t*)(parser->data); const jerry_value_t jobj = http_parserwrap->jobject; jerry_value_t func = iotjs_jval_get_property(jobj, IOTJS_MAGIC_STRING_ONBODY); IOTJS_ASSERT(jerry_value_is_function(func)); jerry_value_t argv[3] = { http_parserwrap->cur_jbuf, jerry_create_number(at - http_parserwrap->cur_buf), jerry_create_number(length) }; iotjs_invoke_callback(func, jobj, argv, 3); jerry_release_value(argv[1]); jerry_release_value(argv[2]); jerry_release_value(func); return 0; } static int iotjs_http_parserwrap_on_message_complete(http_parser* parser) { iotjs_http_parserwrap_t* http_parserwrap = (iotjs_http_parserwrap_t*)(parser->data); const jerry_value_t jobj = http_parserwrap->jobject; jerry_value_t func = iotjs_jval_get_property(jobj, IOTJS_MAGIC_STRING_ONMESSAGECOMPLETE); IOTJS_ASSERT(jerry_value_is_function(func)); iotjs_invoke_callback(func, jobj, NULL, 0); jerry_release_value(func); return 0; } const struct http_parser_settings settings = { iotjs_http_parserwrap_on_message_begin, iotjs_http_parserwrap_on_url, iotjs_http_parserwrap_on_status, iotjs_http_parserwrap_on_header_field, iotjs_http_parserwrap_on_header_value, iotjs_http_parserwrap_on_headers_complete, iotjs_http_parserwrap_on_body, iotjs_http_parserwrap_on_message_complete, NULL, /* on_chunk_header */ NULL, /* on_chunk_complete */ }; static jerry_value_t iotjs_http_parser_return_parserrror( http_parser* nativeparser) { enum http_errno err = HTTP_PARSER_ERRNO(nativeparser); jerry_value_t eobj = iotjs_jval_create_error_without_error_flag("Parse Error"); iotjs_jval_set_property_number(eobj, IOTJS_MAGIC_STRING_BYTEPARSED, 0); iotjs_jval_set_property_string_raw(eobj, IOTJS_MAGIC_STRING_CODE, http_errno_name(err)); return eobj; } JS_FUNCTION(js_func_finish) { JS_DECLARE_THIS_PTR(http_parserwrap, parser); http_parser* nativeparser = &parser->parser; size_t rv = http_parser_execute(nativeparser, &settings, NULL, 0); if (rv != 0) { return iotjs_http_parser_return_parserrror(nativeparser); } return jerry_create_undefined(); } JS_FUNCTION(js_func_execute) { JS_DECLARE_THIS_PTR(http_parserwrap, parser); DJS_CHECK_ARGS(1, object); jerry_value_t jbuffer = JS_GET_ARG(0, object); iotjs_bufferwrap_t* buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuffer); char* buf_data = buffer_wrap->buffer; size_t buf_len = iotjs_bufferwrap_length(buffer_wrap); DJS_CHECK(buf_data != NULL && buf_len > 0); iotjs_http_parserwrap_set_buf(parser, jbuffer, buf_data, buf_len); http_parser* nativeparser = &parser->parser; size_t nparsed = http_parser_execute(nativeparser, &settings, buf_data, buf_len); iotjs_http_parserwrap_set_buf(parser, jerry_create_null(), NULL, 0); if (!nativeparser->upgrade && nparsed != buf_len) { // nparsed should equal to buf_len except UPGRADE protocol return iotjs_http_parser_return_parserrror(nativeparser); } else { return jerry_create_number(nparsed); } } static jerry_value_t iotjs_http_parser_pause(jerry_value_t jthis, int paused) { JS_DECLARE_THIS_PTR(http_parserwrap, parser); http_parser* nativeparser = &parser->parser; http_parser_pause(nativeparser, paused); return jerry_create_undefined(); } JS_FUNCTION(js_func_pause) { return iotjs_http_parser_pause(jthis, 1); } JS_FUNCTION(js_func_resume) { return iotjs_http_parser_pause(jthis, 0); } JS_FUNCTION(http_parser_cons) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, number); const jerry_value_t jparser = JS_GET_THIS(); http_parser_type httpparser_type = (http_parser_type)(JS_GET_ARG(0, number)); if (httpparser_type != HTTP_REQUEST && httpparser_type != HTTP_RESPONSE) { return JS_CREATE_ERROR(TYPE, "Invalid type of HTTP."); } iotjs_http_parserwrap_create(jparser, httpparser_type); return jerry_create_undefined(); } static void http_parser_register_methods_object(jerry_value_t target) { jerry_value_t methods = jerry_create_array(26); jerry_value_t method_name; uint32_t idx = 0; #define V(num, name, string) \ method_name = jerry_create_string((const jerry_char_t*)#string); \ jerry_set_property_by_index(methods, idx++, method_name); \ jerry_release_value(method_name); HTTP_METHOD_MAP(V); #undef V iotjs_jval_set_property_jval(target, IOTJS_MAGIC_STRING_METHODS, methods); jerry_release_value(methods); } jerry_value_t iotjs_init_http_parser(void) { jerry_value_t http_parser = jerry_create_object(); jerry_value_t jparser_cons = jerry_create_external_function(http_parser_cons); iotjs_jval_set_property_jval(http_parser, IOTJS_MAGIC_STRING_HTTPPARSER, jparser_cons); iotjs_jval_set_property_number(jparser_cons, IOTJS_MAGIC_STRING_REQUEST_U, HTTP_REQUEST); iotjs_jval_set_property_number(jparser_cons, IOTJS_MAGIC_STRING_RESPONSE_U, HTTP_RESPONSE); http_parser_register_methods_object(jparser_cons); jerry_value_t prototype = jerry_create_object(); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_EXECUTE, js_func_execute); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_FINISH, js_func_finish); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_PAUSE, js_func_pause); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_RESUME, js_func_resume); iotjs_jval_set_property_jval(jparser_cons, IOTJS_MAGIC_STRING_PROTOTYPE, prototype); jerry_release_value(jparser_cons); jerry_release_value(prototype); return http_parser; } iotjs-1.0+715/src/modules/iotjs_module_i2c.c000066400000000000000000000143611371177304000206570ustar00rootroot00000000000000/* 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_i2c.h" #include "iotjs_uv_request.h" IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(i2c); IOTJS_DEFINE_PERIPH_CREATE_FUNCTION(i2c); static void iotjs_i2c_destroy(iotjs_i2c_t* i2c) { iotjs_i2c_destroy_platform_data(i2c->platform_data); IOTJS_RELEASE(i2c); } static void i2c_worker(uv_work_t* work_req) { iotjs_periph_data_t* worker_data = (iotjs_periph_data_t*)IOTJS_UV_REQUEST_EXTRA_DATA(work_req); iotjs_i2c_t* i2c = (iotjs_i2c_t*)worker_data->data; switch (worker_data->op) { case kI2cOpOpen: worker_data->result = iotjs_i2c_open(i2c); break; case kI2cOpWrite: worker_data->result = iotjs_i2c_write(i2c); break; case kI2cOpRead: worker_data->result = iotjs_i2c_read(i2c); break; case kI2cOpClose: worker_data->result = iotjs_i2c_close(i2c); break; default: IOTJS_ASSERT(!"Invalid Operation"); } } JS_FUNCTION(i2c_constructor) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, object); DJS_CHECK_ARG_IF_EXIST(1, function); // Create I2C object const jerry_value_t ji2c = JS_GET_THIS(); iotjs_i2c_t* i2c = i2c_create(ji2c); jerry_value_t jconfig; JS_GET_REQUIRED_ARG_VALUE(0, jconfig, IOTJS_MAGIC_STRING_CONFIG, object); jerry_value_t res = iotjs_i2c_set_platform_config(i2c, jconfig); if (jerry_value_is_error(res)) { return res; } JS_GET_REQUIRED_CONF_VALUE(jconfig, i2c->address, IOTJS_MAGIC_STRING_ADDRESS, number); jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); // If the callback doesn't exist, it is completed synchronously. // Otherwise, it will be executed asynchronously. if (!jerry_value_is_null(jcallback)) { iotjs_periph_call_async(i2c, jcallback, kI2cOpOpen, i2c_worker); } else if (!iotjs_i2c_open(i2c)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kI2cOpOpen)); } return jerry_create_undefined(); } JS_FUNCTION(i2c_close) { JS_DECLARE_THIS_PTR(i2c, i2c); DJS_CHECK_ARG_IF_EXIST(1, function); iotjs_periph_call_async(i2c, JS_GET_ARG_IF_EXIST(0, function), kI2cOpClose, i2c_worker); return jerry_create_undefined(); } JS_FUNCTION(i2c_close_sync) { JS_DECLARE_THIS_PTR(i2c, i2c); if (!iotjs_i2c_close(i2c)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kI2cOpClose)); } return jerry_create_undefined(); } static jerry_value_t i2c_write_helper(iotjs_i2c_t* i2c, const jerry_value_t jargv[], const jerry_length_t jargc, bool async) { jerry_value_t jarray; JS_GET_REQUIRED_ARG_VALUE(0, jarray, IOTJS_MAGIC_STRING_DATA, array); // Set buffer length and data from jarray i2c->buf_len = jerry_get_array_length(jarray); i2c->buf_data = iotjs_buffer_allocate_from_number_array(i2c->buf_len, jarray); if (async) { DJS_CHECK_ARG_IF_EXIST(1, function); iotjs_periph_call_async(i2c, JS_GET_ARG_IF_EXIST(1, function), kI2cOpWrite, i2c_worker); } else { if (!iotjs_i2c_write(i2c)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kI2cOpWrite)); } } return jerry_create_undefined(); } typedef enum { IOTJS_I2C_WRITE, IOTJS_I2C_WRITESYNC } iotjs_i2c_op_t; static jerry_value_t i2c_do_write_or_writesync(const jerry_value_t jfunc, const jerry_value_t jthis, const jerry_value_t jargv[], const jerry_length_t jargc, const iotjs_i2c_op_t i2c_op) { JS_DECLARE_THIS_PTR(i2c, i2c); DJS_CHECK_ARGS(1, array); return i2c_write_helper(i2c, jargv, jargc, i2c_op == IOTJS_I2C_WRITE); } JS_FUNCTION(i2c_write) { return i2c_do_write_or_writesync(jfunc, jthis, jargv, jargc, IOTJS_I2C_WRITE); } JS_FUNCTION(i2c_write_sync) { return i2c_do_write_or_writesync(jfunc, jthis, jargv, jargc, IOTJS_I2C_WRITESYNC); } JS_FUNCTION(i2c_read) { JS_DECLARE_THIS_PTR(i2c, i2c); DJS_CHECK_ARGS(1, number); DJS_CHECK_ARG_IF_EXIST(1, function); JS_GET_REQUIRED_ARG_VALUE(0, i2c->buf_len, IOTJS_MAGIC_STRING_LENGTH, number); iotjs_periph_call_async(i2c, JS_GET_ARG_IF_EXIST(1, function), kI2cOpRead, i2c_worker); return jerry_create_undefined(); } JS_FUNCTION(i2c_read_sync) { JS_DECLARE_THIS_PTR(i2c, i2c); DJS_CHECK_ARGS(1, number); JS_GET_REQUIRED_ARG_VALUE(0, i2c->buf_len, IOTJS_MAGIC_STRING_LENGTH, number); jerry_value_t result; if (iotjs_i2c_read(i2c)) { result = iotjs_jval_create_byte_array(i2c->buf_len, i2c->buf_data); } else { result = JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kI2cOpRead)); } IOTJS_RELEASE(i2c->buf_data); return result; } jerry_value_t iotjs_init_i2c(void) { jerry_value_t ji2c_cons = jerry_create_external_function(i2c_constructor); jerry_value_t prototype = jerry_create_object(); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_CLOSE, i2c_close); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_CLOSESYNC, i2c_close_sync); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_WRITE, i2c_write); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_WRITESYNC, i2c_write_sync); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_READ, i2c_read); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_READSYNC, i2c_read_sync); iotjs_jval_set_property_jval(ji2c_cons, IOTJS_MAGIC_STRING_PROTOTYPE, prototype); jerry_release_value(prototype); return ji2c_cons; } iotjs-1.0+715/src/modules/iotjs_module_i2c.h000066400000000000000000000033301371177304000206560ustar00rootroot00000000000000/* 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_I2C_H #define IOTJS_MODULE_I2C_H #include "iotjs_def.h" #include "iotjs_module_periph_common.h" // Forward declaration of platform data. These are only used by platform code. // Generic I2C module never dereferences platform data pointer. typedef struct iotjs_i2c_platform_data_s iotjs_i2c_platform_data_t; // This I2c class provides interfaces for I2C operation. typedef struct { jerry_value_t jobject; iotjs_i2c_platform_data_t* platform_data; char* buf_data; uint8_t buf_len; uint8_t address; } iotjs_i2c_t; jerry_value_t iotjs_i2c_set_platform_config(iotjs_i2c_t* i2c, const jerry_value_t jconfig); bool iotjs_i2c_open(iotjs_i2c_t* i2c); bool iotjs_i2c_write(iotjs_i2c_t* i2c); bool iotjs_i2c_read(iotjs_i2c_t* i2c); bool iotjs_i2c_close(iotjs_i2c_t* i2c); // Platform-related functions; they are implemented // by platform code (i.e.: linux, nuttx, tizen). void iotjs_i2c_create_platform_data(iotjs_i2c_t* i2c); void iotjs_i2c_destroy_platform_data(iotjs_i2c_platform_data_t* platform_data); #endif /* IOTJS_MODULE_I2C_H */ iotjs-1.0+715/src/modules/iotjs_module_mqtt.c000066400000000000000000000625541371177304000211760ustar00rootroot00000000000000/* Copyright 2018-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 #include #include "iotjs_def.h" #include "iotjs_module_buffer.h" #include "iotjs_module_mqtt.h" IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(mqttclient); static void iotjs_mqttclient_destroy(iotjs_mqttclient_t *mqttclient) { IOTJS_RELEASE(mqttclient->buffer); IOTJS_RELEASE(mqttclient); } iotjs_mqttclient_t *iotjs_mqttclient_create(const jerry_value_t jobject) { iotjs_mqttclient_t *mqttclient = IOTJS_ALLOC(iotjs_mqttclient_t); jerry_set_object_native_pointer(jobject, mqttclient, &this_module_native_info); return mqttclient; } static uint8_t *iotjs_encode_remaining_length(unsigned char *buffer, uint32_t len) { size_t rc = 0; do { unsigned char d = len & 0x7F; len >>= 7; if (len > 0) { d |= 0x80; } buffer[rc++] = d; } while (len > 0); return (buffer + rc); } static size_t get_remaining_length_size(uint32_t len) { uint8_t n = 0; while (len != 0) { len >>= 7; n++; } return n; } static uint32_t iotjs_decode_remaining_length(char *buffer, uint32_t *out_length) { // There must be at least 2 bytes to decode uint32_t c = (uint32_t)(*buffer); uint32_t decoded_length = (c & 0x7F); uint32_t length = 1; uint32_t shift = 7; buffer++; do { if (++length > IOTJS_MODULE_MQTT_MAX_REMAINING_LENGTH_BYTES) { return 0; } c = (uint32_t)(*buffer); decoded_length += (c & 0x7F) << shift; shift += 7; buffer++; } while ((c & 0x80) != 0); if (c == 0) { // The length must be encoded with the least amount of bytes. // This rule is not fulfilled if the last byte is zero. return 0; } *out_length = length; return decoded_length; } static uint16_t iotjs_mqtt_calculate_length(uint8_t msb, uint8_t lsb) { return (msb << 8) | lsb; } static uint8_t *iotjs_mqtt_string_serialize(uint8_t *dst_buffer, iotjs_tmp_buffer_t *src_buffer) { uint16_t len = src_buffer->length; dst_buffer[0] = (uint8_t)(len >> 8); dst_buffer[1] = (uint8_t)(len & 0x00FF); memcpy(dst_buffer + 2, src_buffer->buffer, src_buffer->length); return (dst_buffer + 2 + src_buffer->length); } void iotjs_mqtt_ack(char *buffer, char *name, jerry_value_t jsref, char *error) { uint16_t package_id = iotjs_mqtt_calculate_length((uint8_t)buffer[0], (uint8_t)buffer[1]); // The callback takes the packet identifier as parameter. jerry_value_t args[2] = { jerry_create_number(package_id), jerry_create_undefined() }; if (error) { args[1] = iotjs_jval_create_error_without_error_flag(error); } jerry_value_t fn = iotjs_jval_get_property(jsref, name); iotjs_invoke_callback(fn, jsref, args, 2); jerry_release_value(fn); jerry_release_value(args[0]); jerry_release_value(args[1]); } JS_FUNCTION(mqtt_init) { DJS_CHECK_THIS(); const jerry_value_t jmqtt = JS_GET_ARG(0, object); iotjs_mqttclient_t *mqttclient = iotjs_mqttclient_create(jmqtt); mqttclient->buffer = NULL; mqttclient->buffer_length = 0; return jerry_create_undefined(); } JS_FUNCTION(mqtt_connect) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, object); jerry_value_t joptions = JS_GET_ARG(0, object); iotjs_tmp_buffer_t client_id; iotjs_jval_get_jproperty_as_tmp_buffer(joptions, IOTJS_MAGIC_STRING_CLIENTID, &client_id); iotjs_tmp_buffer_t username; iotjs_jval_get_jproperty_as_tmp_buffer(joptions, IOTJS_MAGIC_STRING_USERNAME, &username); iotjs_tmp_buffer_t password; iotjs_jval_get_jproperty_as_tmp_buffer(joptions, IOTJS_MAGIC_STRING_PASSWORD, &password); iotjs_tmp_buffer_t message; iotjs_jval_get_jproperty_as_tmp_buffer(joptions, IOTJS_MAGIC_STRING_MESSAGE, &message); iotjs_tmp_buffer_t topic; iotjs_jval_get_jproperty_as_tmp_buffer(joptions, IOTJS_MAGIC_STRING_TOPIC, &topic); if (client_id.buffer == NULL || client_id.length >= UINT16_MAX || username.length >= UINT16_MAX || password.length >= UINT16_MAX || message.length >= UINT16_MAX || topic.length >= UINT16_MAX) { iotjs_free_tmp_buffer(&client_id); iotjs_free_tmp_buffer(&username); iotjs_free_tmp_buffer(&password); iotjs_free_tmp_buffer(&message); iotjs_free_tmp_buffer(&topic); return JS_CREATE_ERROR(COMMON, "mqtt id too long (max: 65535)"); } jerry_value_t jkeepalive = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_KEEPALIVE); jerry_value_t jwill = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_WILL); jerry_value_t jqos = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_QOS); jerry_value_t jretain = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_RETAIN); uint8_t connect_flags = 0; connect_flags |= MQTT_FLAG_CLEANSESSION; uint8_t header_byte = 0; header_byte |= (CONNECT << 4); if (!jerry_value_is_undefined(jwill) && jerry_get_boolean_value(jwill)) { connect_flags |= MQTT_FLAG_WILL; if (jerry_value_is_number(jqos)) { double qos = jerry_get_number_value(jqos); if (qos == 1.0) { connect_flags |= MQTT_FLAG_WILLQOS_1; } else if (qos == 2.0) { connect_flags |= MQTT_FLAG_WILLQOS_2; } } if (!jerry_value_is_undefined(jretain) && jerry_get_boolean_value(jretain)) { connect_flags |= MQTT_FLAG_WILLRETAIN; } } if (username.buffer != NULL) { connect_flags |= MQTT_FLAG_USERNAME; } if (password.buffer != NULL) { connect_flags |= MQTT_FLAG_PASSWORD; } uint16_t keepalive = 0; if (jerry_value_is_number(jkeepalive)) { keepalive = (uint16_t)jerry_get_number_value(jkeepalive); } if (keepalive < 30) { keepalive = 30; } unsigned char variable_header_protocol[7]; variable_header_protocol[0] = 0; variable_header_protocol[1] = 4; variable_header_protocol[2] = 'M'; variable_header_protocol[3] = 'Q'; variable_header_protocol[4] = 'T'; variable_header_protocol[5] = 'T'; variable_header_protocol[6] = 4; size_t variable_header_len = sizeof(variable_header_protocol) + sizeof(connect_flags) + IOTJS_MQTT_LSB_MSB_SIZE; size_t payload_len = IOTJS_MQTT_LSB_MSB_SIZE + client_id.length; if (connect_flags & MQTT_FLAG_USERNAME) { payload_len += IOTJS_MQTT_LSB_MSB_SIZE + username.length; } if (connect_flags & MQTT_FLAG_PASSWORD) { payload_len += IOTJS_MQTT_LSB_MSB_SIZE + password.length; } if (connect_flags & MQTT_FLAG_WILL) { payload_len += IOTJS_MQTT_LSB_MSB_SIZE + topic.length; payload_len += IOTJS_MQTT_LSB_MSB_SIZE + message.length; } uint32_t remaining_length = payload_len + variable_header_len; size_t full_len = sizeof(header_byte) + get_remaining_length_size(remaining_length) + variable_header_len + payload_len; jerry_value_t jbuff = iotjs_bufferwrap_create_buffer(full_len); iotjs_bufferwrap_t *buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuff); uint8_t *buff_ptr = (uint8_t *)buffer_wrap->buffer; *buff_ptr++ = header_byte; buff_ptr = iotjs_encode_remaining_length(buff_ptr, remaining_length); memcpy(buff_ptr, variable_header_protocol, sizeof(variable_header_protocol)); buff_ptr += sizeof(variable_header_protocol); *buff_ptr++ = connect_flags; *buff_ptr++ = (uint8_t)(keepalive >> 8); *buff_ptr++ = (uint8_t)(keepalive & 0x00FF); buff_ptr = iotjs_mqtt_string_serialize(buff_ptr, &client_id); if (connect_flags & MQTT_FLAG_WILL) { buff_ptr = iotjs_mqtt_string_serialize(buff_ptr, &topic); buff_ptr = iotjs_mqtt_string_serialize(buff_ptr, &message); } if (connect_flags & MQTT_FLAG_USERNAME) { buff_ptr = iotjs_mqtt_string_serialize(buff_ptr, &username); } if (connect_flags & MQTT_FLAG_PASSWORD) { buff_ptr = iotjs_mqtt_string_serialize(buff_ptr, &password); } iotjs_free_tmp_buffer(&client_id); iotjs_free_tmp_buffer(&username); iotjs_free_tmp_buffer(&password); iotjs_free_tmp_buffer(&message); iotjs_free_tmp_buffer(&topic); jerry_release_value(jkeepalive); jerry_release_value(jwill); jerry_release_value(jqos); jerry_release_value(jretain); return jbuff; } JS_FUNCTION(mqtt_publish) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(3, any, any, number); iotjs_tmp_buffer_t topic; iotjs_jval_as_tmp_buffer(JS_GET_ARG(0, any), &topic); if (jerry_value_is_error(topic.jval)) { return topic.jval; } if (topic.buffer == NULL || topic.length >= UINT16_MAX) { iotjs_free_tmp_buffer(&topic); return JS_CREATE_ERROR(COMMON, "Topic for PUBLISH is empty or too long."); } iotjs_tmp_buffer_t message; iotjs_jval_as_tmp_buffer(JS_GET_ARG(1, any), &message); if (jerry_value_is_error(message.jval)) { iotjs_free_tmp_buffer(&topic); return message.jval; } // header bits: | 16 bit packet id | 4 bit PUBLISH header | uint32_t header = (uint32_t)JS_GET_ARG(2, number); uint32_t packet_identifier = (header >> 4); uint8_t header_byte = 0; header_byte |= (PUBLISH << 4) | (header & 0xf); const uint8_t qos_mask = (0x3 << 1); size_t payload_len = message.length + IOTJS_MQTT_LSB_MSB_SIZE; size_t variable_header_len = topic.length + IOTJS_MQTT_LSB_MSB_SIZE; if (header_byte & qos_mask) { variable_header_len += IOTJS_MQTT_LSB_MSB_SIZE; } uint32_t remaining_length = payload_len + variable_header_len; size_t full_len = sizeof(header_byte) + get_remaining_length_size(remaining_length) + variable_header_len + payload_len; jerry_value_t jbuff = iotjs_bufferwrap_create_buffer(full_len); iotjs_bufferwrap_t *buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuff); uint8_t *buff_ptr = (uint8_t *)buffer_wrap->buffer; *buff_ptr++ = header_byte; buff_ptr = iotjs_encode_remaining_length(buff_ptr, remaining_length); buff_ptr = iotjs_mqtt_string_serialize(buff_ptr, &topic); if (header_byte & qos_mask) { // Packet id format is MSB / LSB. *buff_ptr++ = (uint8_t)(packet_identifier >> 8); *buff_ptr++ = (uint8_t)(packet_identifier & 0x00FF); } // Don't need to put length before the payload, so we can't use the // iotjs_mqtt_string_serialize. The broker and the other clients calculate // the payload length from remaining length and the topic length. memcpy(buff_ptr, message.buffer, message.length); iotjs_free_tmp_buffer(&message); iotjs_free_tmp_buffer(&topic); return jbuff; } static int iotjs_mqtt_handle(jerry_value_t jsref, char first_byte, char *buffer, uint32_t packet_size) { char packet_type = (first_byte >> 4) & 0x0F; switch (packet_type) { case CONNACK: { if (packet_size != 2) { return MQTT_ERR_CORRUPTED_PACKET; } uint8_t return_code = (uint8_t)buffer[1]; if (return_code != 0) { return return_code; } jerry_value_t fn = iotjs_jval_get_property(jsref, IOTJS_MAGIC_STRING_ONCONNECTION); iotjs_invoke_callback(fn, jsref, NULL, 0); jerry_release_value(fn); break; } case PUBLISH: { mqtt_header_t header = { 0 }; header.bits.type = PUBLISH; header.bits.dup = first_byte & 0x08; header.bits.qos = (first_byte & 0x06) >> 1; header.bits.retain = first_byte & 0x01; uint8_t topic_length_msb = (uint8_t)buffer[0]; uint8_t topic_length_lsb = (uint8_t)buffer[1]; buffer += 2; uint16_t topic_length = iotjs_mqtt_calculate_length(topic_length_msb, topic_length_lsb); if (!jerry_is_valid_utf8_string((const uint8_t *)buffer, topic_length)) { return MQTT_ERR_CORRUPTED_PACKET; } const jerry_char_t *topic = (const jerry_char_t *)buffer; jerry_value_t jtopic = jerry_create_string_sz(topic, topic_length); buffer += topic_length; // The Packet Identifier field is only present in PUBLISH packets // where the QoS level is 1 or 2. uint16_t packet_identifier = 0; if (header.bits.qos > 0) { uint8_t packet_identifier_msb = (uint8_t)buffer[0]; uint8_t packet_identifier_lsb = (uint8_t)buffer[1]; buffer += 2; packet_identifier = iotjs_mqtt_calculate_length(packet_identifier_msb, packet_identifier_lsb); } size_t payload_length = (size_t)packet_size - topic_length - sizeof(topic_length); if (header.bits.qos > 0) { payload_length -= sizeof(packet_identifier); } jerry_value_t jmessage = iotjs_bufferwrap_create_buffer(payload_length); iotjs_bufferwrap_t *msg_wrap = iotjs_bufferwrap_from_jbuffer(jmessage); memcpy(msg_wrap->buffer, buffer, payload_length); jerry_value_t args[4] = { jmessage, jtopic, jerry_create_number(header.bits.qos), jerry_create_number(packet_identifier) }; jerry_value_t fn = iotjs_jval_get_property(jsref, IOTJS_MAGIC_STRING_ONMESSAGE); iotjs_invoke_callback(fn, jsref, args, 4); jerry_release_value(fn); for (uint8_t i = 0; i < 4; i++) { jerry_release_value(args[i]); } break; } case PUBACK: { if (packet_size != 2 || (first_byte & 0x0F) != 0x0) { return MQTT_ERR_CORRUPTED_PACKET; } iotjs_mqtt_ack(buffer, IOTJS_MAGIC_STRING_ONACK, jsref, NULL); break; } case PUBREC: { if (packet_size != 2 || (first_byte & 0x0F) != 0x0) { return MQTT_ERR_CORRUPTED_PACKET; } iotjs_mqtt_ack(buffer, IOTJS_MAGIC_STRING_ONPUBREC, jsref, NULL); break; } case PUBREL: { if (packet_size != 2 || (first_byte & 0x0F) != 0x2) { return MQTT_ERR_CORRUPTED_PACKET; } iotjs_mqtt_ack(buffer, IOTJS_MAGIC_STRING_ONPUBREL, jsref, NULL); break; } case PUBCOMP: { if (packet_size != 2 || (first_byte & 0x0F) != 0x0) { return MQTT_ERR_CORRUPTED_PACKET; } iotjs_mqtt_ack(buffer, IOTJS_MAGIC_STRING_ONACK, jsref, NULL); break; } case SUBACK: { // We assume that only one topic was in the SUBSCRIBE packet. if (packet_size != 3 || (first_byte & 0x0F) != 0x0) { return MQTT_ERR_CORRUPTED_PACKET; } char *error = NULL; if ((uint8_t)buffer[2] == 0x80) { error = "Subscribe failed"; } iotjs_mqtt_ack(buffer, IOTJS_MAGIC_STRING_ONACK, jsref, error); break; } case UNSUBACK: { if (packet_size != 2 || (first_byte & 0x0F) != 0x0) { return MQTT_ERR_CORRUPTED_PACKET; } iotjs_mqtt_ack(buffer, IOTJS_MAGIC_STRING_ONACK, jsref, NULL); break; } case PINGRESP: { if (packet_size != 0 || (first_byte & 0x0F) != 0x0) { return MQTT_ERR_CORRUPTED_PACKET; } jerry_value_t fn = iotjs_jval_get_property(jsref, IOTJS_MAGIC_STRING_ONPINGRESP); iotjs_invoke_callback(fn, jsref, NULL, 0); jerry_release_value(fn); break; } case DISCONNECT: { if (packet_size != 0 || (first_byte & 0x0F) != 0x0) { return MQTT_ERR_CORRUPTED_PACKET; } jerry_value_t fn = iotjs_jval_get_property(jsref, IOTJS_MAGIC_STRING_ONEND); iotjs_invoke_callback(fn, jsref, NULL, 0); jerry_release_value(fn); break; } case CONNECT: case SUBSCRIBE: case UNSUBSCRIBE: case PINGREQ: return MQTT_ERR_UNALLOWED_PACKET; } return 0; } static void iotjs_mqtt_concat_buffers(iotjs_mqttclient_t *mqttclient, iotjs_bufferwrap_t *buff_recv) { char *tmp_buf = mqttclient->buffer; mqttclient->buffer = IOTJS_CALLOC(mqttclient->buffer_length + buff_recv->length, char); memcpy(mqttclient->buffer, tmp_buf, mqttclient->buffer_length); memcpy(mqttclient->buffer + mqttclient->buffer_length, buff_recv->buffer, buff_recv->length); mqttclient->buffer_length += buff_recv->length; IOTJS_RELEASE(tmp_buf); } static jerry_value_t iotjs_mqtt_handle_error( iotjs_mqtt_packet_error_t error_code) { switch (error_code) { case MQTT_ERR_UNACCEPTABLE_PROTOCOL: return JS_CREATE_ERROR(COMMON, "MQTT: Connection refused: unacceptable protocol"); case MQTT_ERR_BAD_IDENTIFIER: return JS_CREATE_ERROR(COMMON, "MQTT: Connection refused: bad client identifier"); case MQTT_ERR_SERVER_UNAVIABLE: return JS_CREATE_ERROR(COMMON, "MQTT: Connection refused: server unavailable"); case MQTT_ERR_BAD_CREDENTIALS: return JS_CREATE_ERROR( COMMON, "MQTT: Connection refused: bad username or password"); case MQTT_ERR_UNAUTHORISED: return JS_CREATE_ERROR(COMMON, "MQTT: Connection refused: unauthorised"); case MQTT_ERR_CORRUPTED_PACKET: return JS_CREATE_ERROR(COMMON, "MQTT: Corrupted packet"); case MQTT_ERR_UNALLOWED_PACKET: return JS_CREATE_ERROR(COMMON, "MQTT: Broker sent an unallowed packet"); case MQTT_ERR_SUBSCRIPTION_FAILED: return JS_CREATE_ERROR(COMMON, "MQTT: Subscription failed"); default: return JS_CREATE_ERROR(COMMON, "MQTT: Unknown error"); } } JS_FUNCTION(mqtt_receive) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(2, object, object); jerry_value_t jnat = JS_GET_ARG(0, object); iotjs_mqttclient_t *mqttclient = NULL; if (!jerry_get_object_native_pointer(jnat, (void **)&mqttclient, &this_module_native_info)) { return JS_CREATE_ERROR(COMMON, "MQTT native pointer not available"); } jerry_value_t jbuffer = JS_GET_ARG(1, object); iotjs_bufferwrap_t *buff_recv = iotjs_bufferwrap_from_jbuffer(jbuffer); if (buff_recv->length == 0) { return jerry_create_undefined(); } char *current_buffer = buff_recv->buffer; char *current_buffer_end = current_buffer + buff_recv->length; // Concat the buffers if we previously needed to if (mqttclient->buffer_length > 0) { iotjs_mqtt_concat_buffers(mqttclient, buff_recv); current_buffer = mqttclient->buffer; current_buffer_end = current_buffer + mqttclient->buffer_length; } // Keep on going, if data remains just continue looping while (true) { if (current_buffer >= current_buffer_end) { if (mqttclient->buffer_length > 0) { IOTJS_RELEASE(mqttclient->buffer); mqttclient->buffer_length = 0; } return jerry_create_undefined(); } if (current_buffer + 2 > current_buffer_end) { break; } uint32_t packet_size; uint32_t packet_size_length; if ((uint8_t)current_buffer[1] <= 0x7f) { packet_size = (uint32_t)current_buffer[1]; packet_size_length = 1; if (current_buffer + 2 + packet_size > current_buffer_end) { break; } } else { // At least 128 bytes arrived if (current_buffer + 5 >= current_buffer_end) { break; } packet_size = iotjs_decode_remaining_length(current_buffer + 1, &packet_size_length); if (packet_size == 0) { return iotjs_mqtt_handle_error(MQTT_ERR_CORRUPTED_PACKET); } if (current_buffer + 1 + packet_size_length + packet_size > current_buffer_end) { break; } } char first_byte = current_buffer[0]; current_buffer += 1 + packet_size_length; int ret_val = iotjs_mqtt_handle(jnat, first_byte, current_buffer, packet_size); if (ret_val != 0) { return iotjs_mqtt_handle_error(ret_val); } current_buffer += packet_size; } if (current_buffer == mqttclient->buffer) { return jerry_create_undefined(); } uint32_t remaining_size = (uint32_t)(current_buffer_end - current_buffer); char *buffer = IOTJS_CALLOC(remaining_size, char); memcpy(buffer, current_buffer, remaining_size); if (mqttclient->buffer != NULL) { IOTJS_RELEASE(mqttclient->buffer); } mqttclient->buffer = buffer; mqttclient->buffer_length = remaining_size; return jerry_create_undefined(); } static jerry_value_t iotjs_mqtt_subscribe_handler( const jerry_value_t jthis, const jerry_value_t jargv[], const jerry_value_t jargc, const iotjs_mqtt_control_packet_type packet_type) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(2, any, number); DJS_CHECK(packet_type == SUBSCRIBE || packet_type == UNSUBSCRIBE); iotjs_tmp_buffer_t topic; iotjs_jval_as_tmp_buffer(JS_GET_ARG(0, any), &topic); if (jerry_value_is_error(topic.jval)) { return topic.jval; } if (topic.buffer == NULL || topic.length >= UINT16_MAX) { iotjs_free_tmp_buffer(&topic); return JS_CREATE_ERROR(COMMON, "Topic for SUBSCRIBE is empty or too long."); } // header bits: |2 bit qos | 16 bit packet id | // qos is only available in case of subscribe uint32_t header = (uint32_t)JS_GET_ARG(1, number); uint32_t packet_identifier = (header & 0xFFFF); // Low 4 bits must be 0,0,1,0 uint8_t header_byte = (packet_type << 4) | (1 << 1); size_t payload_len = topic.length + IOTJS_MQTT_LSB_MSB_SIZE; if (packet_type == SUBSCRIBE) { // Add place for the SUBSCRIBE QoS data. payload_len += sizeof(uint8_t); } size_t variable_header_len = IOTJS_MQTT_LSB_MSB_SIZE; uint32_t remaining_length = payload_len + variable_header_len; size_t full_len = sizeof(header_byte) + get_remaining_length_size(remaining_length) + remaining_length; jerry_value_t jbuff = iotjs_bufferwrap_create_buffer(full_len); iotjs_bufferwrap_t *buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuff); uint8_t *buff_ptr = (uint8_t *)buffer_wrap->buffer; *buff_ptr++ = header_byte; buff_ptr = iotjs_encode_remaining_length(buff_ptr, remaining_length); // Packet id format is MSB / LSB. *buff_ptr++ = (uint8_t)(packet_identifier >> 8); *buff_ptr++ = (uint8_t)(packet_identifier & 0x00FF); buff_ptr = iotjs_mqtt_string_serialize(buff_ptr, &topic); if (packet_type == SUBSCRIBE) { uint8_t qos = ((header >> 16) & 0x3); buff_ptr[0] = qos; } iotjs_free_tmp_buffer(&topic); return jbuff; } JS_FUNCTION(mqtt_unsubscribe) { return iotjs_mqtt_subscribe_handler(jthis, jargv, jargc, UNSUBSCRIBE); } JS_FUNCTION(mqtt_subscribe) { return iotjs_mqtt_subscribe_handler(jthis, jargv, jargc, SUBSCRIBE); } JS_FUNCTION(mqtt_ping) { DJS_CHECK_THIS(); uint8_t header_byte = 0; header_byte |= (PINGREQ << 4); uint8_t remaining_length = 0; size_t full_len = sizeof(header_byte) + sizeof(remaining_length); jerry_value_t jbuff = iotjs_bufferwrap_create_buffer(full_len); iotjs_bufferwrap_t *buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuff); uint8_t *buff_ptr = (uint8_t *)buffer_wrap->buffer; buff_ptr[0] = header_byte; buff_ptr[1] = remaining_length; return jbuff; } JS_FUNCTION(mqtt_disconnect) { DJS_CHECK_THIS(); uint8_t header_byte = 0; uint8_t remaining_length = 0; header_byte |= (DISCONNECT << 4); size_t full_len = sizeof(header_byte) + sizeof(remaining_length); jerry_value_t jbuff = iotjs_bufferwrap_create_buffer(full_len); iotjs_bufferwrap_t *buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuff); uint8_t *buff_ptr = (uint8_t *)buffer_wrap->buffer; buff_ptr[0] = header_byte; buff_ptr[1] = remaining_length; return jbuff; } JS_FUNCTION(mqtt_send_ack) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(2, number, number); uint8_t ack_type = (uint8_t)JS_GET_ARG(0, number); uint16_t packet_id = (uint16_t)JS_GET_ARG(1, number); uint8_t header_byte = (ack_type << 4); if (ack_type == PUBREL) { header_byte |= 0x2; } uint8_t packet_identifier_msb = (uint8_t)(packet_id >> 8); uint8_t packet_identifier_lsb = (uint8_t)(packet_id & 0x00FF); size_t full_len = sizeof(uint8_t) * 2 + sizeof(packet_id); jerry_value_t jbuff = iotjs_bufferwrap_create_buffer(full_len); iotjs_bufferwrap_t *buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuff); uint8_t *buff_ptr = (uint8_t *)buffer_wrap->buffer; buff_ptr[0] = header_byte; buff_ptr[1] = 2; /* length */ buff_ptr[2] = packet_identifier_msb; buff_ptr[3] = packet_identifier_lsb; return jbuff; } jerry_value_t iotjs_init_mqtt(void) { jerry_value_t jmqtt = jerry_create_object(); iotjs_jval_set_method(jmqtt, IOTJS_MAGIC_STRING_CONNECT, mqtt_connect); iotjs_jval_set_method(jmqtt, IOTJS_MAGIC_STRING_DISCONNECT, mqtt_disconnect); iotjs_jval_set_method(jmqtt, IOTJS_MAGIC_STRING_PING, mqtt_ping); iotjs_jval_set_method(jmqtt, IOTJS_MAGIC_STRING_PUBLISH, mqtt_publish); iotjs_jval_set_method(jmqtt, IOTJS_MAGIC_STRING_MQTTINIT, mqtt_init); iotjs_jval_set_method(jmqtt, IOTJS_MAGIC_STRING_MQTTRECEIVE, mqtt_receive); iotjs_jval_set_method(jmqtt, IOTJS_MAGIC_STRING_SENDACK, mqtt_send_ack); iotjs_jval_set_method(jmqtt, IOTJS_MAGIC_STRING_SUBSCRIBE, mqtt_subscribe); iotjs_jval_set_method(jmqtt, IOTJS_MAGIC_STRING_UNSUBSCRIBE, mqtt_unsubscribe); return jmqtt; } iotjs-1.0+715/src/modules/iotjs_module_mqtt.h000066400000000000000000000071701371177304000211740ustar00rootroot00000000000000/* Copyright 2018-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_MQTT_H #define IOTJS_MODULE_MQTT_H #include "iotjs_def.h" #define IOTJS_MODULE_MQTT_MAX_REMAINING_LENGTH_BYTES 4 #define IOTJS_MQTT_LSB_MSB_SIZE 2 /* * The types of the control packet. * These values determine the aim of the message. */ typedef enum { CONNECT = 0x1, CONNACK = 0x2, PUBLISH = 0x3, PUBACK = 0x4, PUBREC = 0x5, PUBREL = 0x6, PUBCOMP = 0x7, SUBSCRIBE = 0x8, SUBACK = 0x9, UNSUBSCRIBE = 0xA, UNSUBACK = 0xB, PINGREQ = 0xC, PINGRESP = 0xD, DISCONNECT = 0xE } iotjs_mqtt_control_packet_type; // Packet error types typedef enum { MQTT_ERR_UNACCEPTABLE_PROTOCOL = 1, MQTT_ERR_BAD_IDENTIFIER = 2, MQTT_ERR_SERVER_UNAVIABLE = 3, MQTT_ERR_BAD_CREDENTIALS = 4, MQTT_ERR_UNAUTHORISED = 5, MQTT_ERR_CORRUPTED_PACKET = 6, MQTT_ERR_UNALLOWED_PACKET = 7, MQTT_ERR_SUBSCRIPTION_FAILED = 8, } iotjs_mqtt_packet_error_t; /* * The values of the Quality of Service. */ enum { QoS0 = 0, // At most once delivery. QoS1 = 1, // At least once delivery. QoS2 = 2 // Exactly once delivery. } iotjs_mqtt_quality_of_service; /* * First byte of the message's fixed header. * Contains: * - MQTT Control Packet type, * - Specific flags to each MQTT Control Packet. */ typedef struct { uint8_t RETAIN : 1; // PUBLISH Retain flag. unsigned char QoS : 2; // PUBLISH Quality of Service. uint8_t DUP : 1; // Duplicate delivery of PUBLISH Control Packet. unsigned char packet_type : 4; } iotjs_mqtt_control_packet_t; /* * The fixed header of the MQTT message structure. */ typedef struct { iotjs_mqtt_control_packet_t packet; uint8_t remaining_length; } iotjs_mqtt_fixed_header_t; /* * Type of the MQTT CONNECT message. */ typedef union { unsigned char byte; struct { uint8_t retain : 1; uint8_t qos : 2; uint8_t dup : 1; uint8_t type : 4; } bits; } mqtt_header_t; enum { // Reserved bit, must be 0 MQTT_FLAG_RESERVED = 1 << 0, // Clean session bit MQTT_FLAG_CLEANSESSION = 1 << 1, /** * If the will flag is set to 1 Will QoS and Will Retain flags must be * also set to 1, and be present in the payload. Otherwise, both must be set * to 0. */ MQTT_FLAG_WILL = 1 << 2, /** * QoS can only be set, if the Will flag is set to 1. Otherwise it's 0x00. * QoS types are as follows: * Type 0: Both QoS bits are set to 0 (0x00) * Type 1: WILLQOS_1 is set to 1, WILLQOS_2 is set to 0 (0x01) * Type 2: WILLQOS_2 is set to 1, WILLQOS_1 is set to 0 (0x02) */ MQTT_FLAG_WILLQOS_1 = 1 << 3, MQTT_FLAG_WILLQOS_2 = 1 << 4, /** * Will retain flag can only be set to 1 if Will flag is set to 1 as well. * If retain is set to 1, the server must publish will message as a retained * message. */ MQTT_FLAG_WILLRETAIN = 1 << 5, // Whether password is sent by the user MQTT_FLAG_PASSWORD = 1 << 6, // Whether username is sent MQTT_FLAG_USERNAME = 1 << 7 } iotjs_mqtt_connect_flag_t; typedef struct { char *buffer; uint32_t buffer_length; } iotjs_mqttclient_t; #endif /* IOTJS_MODULE_MQTT_H */ iotjs-1.0+715/src/modules/iotjs_module_periph_common.c000066400000000000000000000150021371177304000230320ustar00rootroot00000000000000/* Copyright 2018-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_module_periph_common.h" #include "iotjs_module_adc.h" #include "iotjs_module_gpio.h" #include "iotjs_module_i2c.h" #include "iotjs_module_pwm.h" #include "iotjs_module_spi.h" #include "iotjs_module_uart.h" #include "iotjs_uv_request.h" const char* iotjs_periph_error_str(uint8_t op) { switch (op) { #if ENABLE_MODULE_ADC case kAdcOpClose: return "Close error, cannot close ADC"; case kAdcOpOpen: return "Open error, cannot open ADC"; case kAdcOpRead: return "Read error, cannot read ADC"; #endif /* ENABLE_MODULE_ADC */ #if ENABLE_MODULE_GPIO case kGpioOpOpen: return "Open error, cannot open GPIO"; case kGpioOpWrite: return "Write error, cannot write GPIO"; case kGpioOpRead: return "Read error, cannot read GPIO"; case kGpioOpClose: return "Close error, cannot close GPIO"; #endif /* ENABLE_MODULE_GPIO */ #if ENABLE_MODULE_I2C case kI2cOpOpen: return "Open error, cannot open I2C"; case kI2cOpWrite: return "Write error, cannot write I2C"; case kI2cOpRead: return "Read error, cannot read I2C"; case kI2cOpClose: return "Close error, cannot close I2C"; #endif /* ENABLE_MODULE_I2C */ #if ENABLE_MODULE_PWM case kPwmOpClose: return "Cannot close PWM device"; case kPwmOpOpen: return "Failed to open PWM device"; case kPwmOpSetDutyCycle: return "Failed to set duty-cycle"; case kPwmOpSetEnable: return "Failed to set enable"; case kPwmOpSetFrequency: return "Failed to set frequency"; case kPwmOpSetPeriod: return "Failed to set period"; #endif /* ENABLE_MODULE_PWM */ #if ENABLE_MODULE_SPI case kSpiOpClose: return "Close error, cannot close SPI"; case kSpiOpOpen: return "Open error, cannot open SPI"; case kSpiOpTransferArray: case kSpiOpTransferBuffer: return "Transfer error, cannot transfer from SPI device"; #endif /* ENABLE_MODULE_SPI */ #if ENABLE_MODULE_UART case kUartOpClose: return "Close error, failed to close UART device"; case kUartOpOpen: return "Open error, failed to open UART device"; case kUartOpWrite: return "Write error, cannot write to UART device"; #endif /* ENABLE_MODULE_UART */ default: return "Unknown error"; } } static void after_worker(uv_work_t* work_req, int status) { iotjs_periph_data_t* worker_data = (iotjs_periph_data_t*)IOTJS_UV_REQUEST_EXTRA_DATA(work_req); size_t jargc = 0; jerry_value_t jargs[2] = { 0 }; if (status) { jargs[jargc++] = iotjs_jval_create_error_without_error_flag("System error"); } else { if (!worker_data->result) { jargs[jargc++] = iotjs_jval_create_error_without_error_flag( iotjs_periph_error_str(worker_data->op)); } else { jargs[jargc++] = jerry_create_null(); switch (worker_data->op) { case kAdcOpClose: case kAdcOpOpen: case kGpioOpClose: case kGpioOpOpen: case kGpioOpWrite: case kI2cOpClose: case kI2cOpOpen: case kI2cOpWrite: case kSpiOpClose: case kSpiOpOpen: case kPwmOpClose: case kPwmOpOpen: case kPwmOpSetDutyCycle: case kPwmOpSetEnable: case kPwmOpSetFrequency: case kPwmOpSetPeriod: case kUartOpClose: case kUartOpOpen: case kUartOpWrite: { break; } case kAdcOpRead: { #if ENABLE_MODULE_ADC iotjs_adc_t* adc = (iotjs_adc_t*)worker_data->data; jargs[jargc++] = jerry_create_number(adc->value); #endif /* ENABLE_MODULE_ADC */ break; } case kGpioOpRead: { #if ENABLE_MODULE_GPIO iotjs_gpio_t* gpio = (iotjs_gpio_t*)worker_data->data; jargs[jargc++] = jerry_create_boolean(gpio->value); #endif /* ENABLE_MODULE_GPIO */ break; } case kI2cOpRead: { #if ENABLE_MODULE_I2C iotjs_i2c_t* i2c = (iotjs_i2c_t*)worker_data->data; jargs[jargc++] = iotjs_jval_create_byte_array(i2c->buf_len, i2c->buf_data); IOTJS_RELEASE(i2c->buf_data); #endif /* ENABLE_MODULE_I2C */ break; } case kSpiOpTransferArray: case kSpiOpTransferBuffer: { #if ENABLE_MODULE_SPI iotjs_spi_t* spi = (iotjs_spi_t*)worker_data->data; // Append read data jargs[jargc++] = iotjs_jval_create_byte_array(spi->buf_len, spi->rx_buf_data); IOTJS_RELEASE(spi->rx_buf_data); #endif /* ENABLE_MODULE_SPI */ break; } default: { IOTJS_ASSERT(!"Unreachable"); break; } } } #if ENABLE_MODULE_SPI if (worker_data->op == kSpiOpTransferArray) { iotjs_spi_t* spi = (iotjs_spi_t*)worker_data->data; IOTJS_RELEASE(spi->tx_buf_data); } #endif /* ENABLE_MODULE_SPI */ #if ENABLE_MODULE_UART if (worker_data->op == kUartOpWrite) { iotjs_uart_t* uart = (iotjs_uart_t*)worker_data->data; iotjs_string_destroy(&uart->buf_data); } #endif /* ENABLE_MODULE_UART */ } jerry_value_t jcallback = *IOTJS_UV_REQUEST_JSCALLBACK(work_req); if (jerry_value_is_function(jcallback)) { iotjs_invoke_callback(jcallback, jerry_create_undefined(), jargs, jargc); } for (size_t i = 0; i < jargc; i++) { jerry_release_value(jargs[i]); } iotjs_uv_request_destroy((uv_req_t*)work_req); } void iotjs_periph_call_async(void* data, jerry_value_t jcallback, uint8_t op, uv_work_cb worker) { uv_loop_t* loop = iotjs_environment_loop(iotjs_environment_get()); uv_req_t* work_req = iotjs_uv_request_create(sizeof(uv_work_t), jcallback, sizeof(iotjs_periph_data_t)); iotjs_periph_data_t* worker_data = (iotjs_periph_data_t*)IOTJS_UV_REQUEST_EXTRA_DATA(work_req); worker_data->op = op; worker_data->data = data; uv_queue_work(loop, (uv_work_t*)work_req, worker, after_worker); } iotjs-1.0+715/src/modules/iotjs_module_periph_common.h000066400000000000000000000037721371177304000230520ustar00rootroot00000000000000/* Copyright 2018-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_PERIPH_COMMON_H #define IOTJS_MODULE_PERIPH_COMMON_H #include "iotjs_def.h" typedef enum { kAdcOpOpen, kAdcOpRead, kAdcOpClose, kGpioOpOpen, kGpioOpWrite, kGpioOpRead, kGpioOpClose, kI2cOpOpen, kI2cOpClose, kI2cOpWrite, kI2cOpRead, kPwmOpClose, kPwmOpOpen, kPwmOpSetDutyCycle, kPwmOpSetEnable, kPwmOpSetFrequency, kPwmOpSetPeriod, kSpiOpClose, kSpiOpOpen, kSpiOpTransferArray, kSpiOpTransferBuffer, kUartOpClose, kUartOpOpen, kUartOpWrite } iotjs_periph_op_t; typedef struct { uint8_t op; bool result; void* data; } iotjs_periph_data_t; const char* iotjs_periph_error_str(uint8_t op); void iotjs_periph_call_async(void* type_p, jerry_value_t jcallback, uint8_t op, uv_work_cb worker); #define IOTJS_DEFINE_PERIPH_CREATE_FUNCTION(name) \ static iotjs_##name##_t* name##_create(const jerry_value_t jobject) { \ iotjs_##name##_t* data = IOTJS_ALLOC(iotjs_##name##_t); \ iotjs_##name##_create_platform_data(data); \ data->jobject = jobject; \ jerry_set_object_native_pointer(jobject, data, &this_module_native_info); \ return data; \ } #endif /* IOTJS_MODULE_PERIPH_COMMON_H */ iotjs-1.0+715/src/modules/iotjs_module_process.c000066400000000000000000000325011371177304000216540ustar00rootroot00000000000000/* 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_compatibility.h" #include "iotjs_js.h" #include "jerryscript-debugger.h" #include #ifndef WIN32 #include #endif /* !WIN32 */ static jerry_value_t wrap_eval(const char* name, size_t name_len, const char* source, size_t length) { static const char* args = "exports, require, module, native"; jerry_value_t res = jerry_parse_function((const jerry_char_t*)name, name_len, (const jerry_char_t*)args, strlen(args), (const jerry_char_t*)source, length, JERRY_PARSE_NO_OPTS); return res; } JS_FUNCTION(proc_compile) { DJS_CHECK_ARGS(2, string, string); iotjs_string_t file = JS_GET_ARG(0, string); iotjs_string_t source = JS_GET_ARG(1, string); const char* filename = iotjs_string_data(&file); #ifdef JERRY_DEBUGGER const iotjs_environment_t* env = iotjs_environment_get(); if (iotjs_environment_config(env)->debugger != NULL) { jerry_debugger_stop(); } #endif jerry_value_t jres = wrap_eval(filename, strlen(filename), iotjs_string_data(&source), iotjs_string_size(&source)); iotjs_string_destroy(&file); iotjs_string_destroy(&source); return jres; } #ifdef JERRY_DEBUGGER // Callback function for debugger_get_source static jerry_value_t wait_for_source_callback( const jerry_char_t* resource_name_p, size_t resource_name_size, const jerry_char_t* source_p, size_t size, void* data) { IOTJS_UNUSED(data); jerry_value_t ret_val = jerry_create_array(2); jerry_value_t jname = jerry_create_string_sz(resource_name_p, resource_name_size); jerry_value_t jsource = jerry_create_string_sz(source_p, size); jerry_set_property_by_index(ret_val, 0, jname); jerry_set_property_by_index(ret_val, 1, jsource); jerry_release_value(jname); jerry_release_value(jsource); return ret_val; } // Export JS module received from the debugger client JS_FUNCTION(debugger_get_source) { jerry_debugger_wait_for_source_status_t receive_status; jerry_value_t ret_val = jerry_create_array(0); uint8_t counter = 0; do { jerry_value_t res; receive_status = jerry_debugger_wait_for_client_source(wait_for_source_callback, NULL, &res); if (receive_status == JERRY_DEBUGGER_SOURCE_RECEIVED) { jerry_set_property_by_index(ret_val, counter++, res); jerry_release_value(res); } if (receive_status == JERRY_DEBUGGER_CONTEXT_RESET_RECEIVED) { iotjs_environment_config(iotjs_environment_get()) ->debugger->context_reset = true; break; } } while (receive_status != JERRY_DEBUGGER_SOURCE_END); return ret_val; } #endif JS_FUNCTION(proc_compile_module) { DJS_CHECK_ARGS(2, object, function); jerry_value_t jmodule = JS_GET_ARG(0, object); jerry_value_t jrequire = JS_GET_ARG(1, function); jerry_value_t jid = iotjs_jval_get_property(jmodule, "id"); if (!jerry_value_is_string(jid)) { return JS_CREATE_ERROR(COMMON, "Unknown native module"); } iotjs_string_t id = iotjs_jval_as_string(jid); jerry_release_value(jid); const char* name = iotjs_string_data(&id); int i = 0; while (js_modules[i].name != NULL) { if (!strcmp(js_modules[i].name, name)) { break; } i++; } jerry_value_t native_module_jval = iotjs_module_get(name); if (jerry_value_is_error(native_module_jval)) { iotjs_string_destroy(&id); return native_module_jval; } jerry_value_t jres = jerry_create_undefined(); if (js_modules[i].name != NULL) { #ifdef ENABLE_SNAPSHOT jres = jerry_exec_snapshot((const uint32_t*)iotjs_js_modules_s, iotjs_js_modules_l, js_modules[i].idx, JERRY_SNAPSHOT_EXEC_ALLOW_STATIC); #else jres = wrap_eval(name, iotjs_string_size(&id), (const char*)js_modules[i].code, js_modules[i].length); #endif if (!jerry_value_is_error(jres)) { jerry_value_t jexports = iotjs_jval_get_property(jmodule, "exports"); jerry_value_t args[] = { jexports, jrequire, jmodule, native_module_jval }; jerry_value_t jfunc = jres; jres = jerry_call_function(jfunc, jerry_create_undefined(), args, sizeof(args) / sizeof(jerry_value_t)); jerry_release_value(jfunc); jerry_release_value(jexports); } } else if (!jerry_value_is_undefined(native_module_jval)) { iotjs_jval_set_property_jval(jmodule, "exports", native_module_jval); } else { jres = JS_CREATE_ERROR(COMMON, "Unknown native module"); } iotjs_string_destroy(&id); return jres; } JS_FUNCTION(proc_read_source) { DJS_CHECK_ARGS(1, string); iotjs_string_t path = JS_GET_ARG(0, string); const iotjs_environment_t* env = iotjs_environment_get(); int err; uv_fs_t fs_req; err = uv_fs_stat(iotjs_environment_loop(env), &fs_req, iotjs_string_data(&path), NULL); uv_fs_req_cleanup(&fs_req); if (err || !S_ISREG(fs_req.statbuf.st_mode)) { iotjs_string_destroy(&path); return JS_CREATE_ERROR(COMMON, "ReadSource error, not a regular file"); } iotjs_string_t code = iotjs_file_read(iotjs_string_data(&path)); jerry_value_t ret_val = iotjs_jval_create_string(&code); iotjs_string_destroy(&path); iotjs_string_destroy(&code); return ret_val; } JS_FUNCTION(proc_cwd) { char path[IOTJS_MAX_PATH_SIZE]; size_t size_path = sizeof(path); int err = uv_cwd(path, &size_path); if (err) { return JS_CREATE_ERROR(COMMON, "cwd error"); } return jerry_create_string_from_utf8((const jerry_char_t*)path); } JS_FUNCTION(proc_chdir) { DJS_CHECK_ARGS(1, string); iotjs_string_t path = JS_GET_ARG(0, string); int err = uv_chdir(iotjs_string_data(&path)); if (err) { iotjs_string_destroy(&path); return JS_CREATE_ERROR(COMMON, "chdir error"); } iotjs_string_destroy(&path); return jerry_create_undefined(); } #ifdef EXPOSE_GC JS_FUNCTION(garbage_collector) { jerry_gc(JERRY_GC_PRESSURE_LOW); return jerry_create_undefined(); } #endif JS_FUNCTION(proc_do_exit) { iotjs_environment_t* env = iotjs_environment_get(); if (!iotjs_environment_is_exiting(env)) { DJS_CHECK_ARGS(1, number); int exit_code = JS_GET_ARG(0, number); iotjs_set_process_exitcode(exit_code); iotjs_environment_set_state(env, kExiting); } return jerry_create_undefined(); } static void set_process_env(jerry_value_t process) { const char *homedir, *iotjspath, *iotjsenv, *extra_module_path, *working_dir_path; homedir = getenv(IOTJS_MAGIC_STRING_HOME_U); if (homedir == NULL) { homedir = ""; } iotjspath = getenv(IOTJS_MAGIC_STRING_IOTJS_PATH_U); if (iotjspath == NULL) { #if defined(__NUTTX__) iotjspath = "/mnt/sdcard"; #elif defined(__TIZENRT__) iotjspath = "/rom"; #else iotjspath = ""; #endif } #if defined(EXPERIMENTAL) iotjsenv = "experimental"; #else iotjsenv = ""; #endif extra_module_path = getenv(IOTJS_MAGIC_STRING_IOTJS_EXTRA_MODULE_PATH_U); working_dir_path = getenv(IOTJS_MAGIC_STRING_IOTJS_WORKING_DIR_PATH_U); jerry_value_t env = jerry_create_object(); iotjs_jval_set_property_string_raw(env, IOTJS_MAGIC_STRING_HOME_U, homedir); iotjs_jval_set_property_string_raw(env, IOTJS_MAGIC_STRING_IOTJS_PATH_U, iotjspath); iotjs_jval_set_property_string_raw(env, IOTJS_MAGIC_STRING_IOTJS_ENV_U, iotjsenv); iotjs_jval_set_property_string_raw( env, IOTJS_MAGIC_STRING_IOTJS_EXTRA_MODULE_PATH_U, extra_module_path ? extra_module_path : ""); iotjs_jval_set_property_string_raw( env, IOTJS_MAGIC_STRING_IOTJS_WORKING_DIR_PATH_U, working_dir_path ? working_dir_path : ""); iotjs_jval_set_property_jval(process, IOTJS_MAGIC_STRING_ENV, env); jerry_release_value(env); } static void set_process_iotjs(jerry_value_t process) { // IoT.js specific jerry_value_t iotjs = jerry_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)); jerry_release_value(iotjs); } static void set_process_argv(jerry_value_t process) { const iotjs_environment_t* env = iotjs_environment_get(); uint32_t argc = iotjs_environment_argc(env); jerry_value_t argv = jerry_create_array(argc); for (uint32_t i = 0; i < argc; ++i) { const char* argvi = iotjs_environment_argv(env, i); jerry_value_t arg = jerry_create_string((const jerry_char_t*)argvi); iotjs_jval_set_property_by_index(argv, i, arg); jerry_release_value(arg); } iotjs_jval_set_property_jval(process, IOTJS_MAGIC_STRING_ARGV, argv); jerry_release_value(argv); } static void set_builtin_modules(jerry_value_t builtin_modules) { for (unsigned i = 0; js_modules[i].name; i++) { iotjs_jval_set_property_jval(builtin_modules, js_modules[i].name, jerry_create_boolean(true)); } for (unsigned i = 0; i < iotjs_module_count; i++) { iotjs_jval_set_property_jval(builtin_modules, iotjs_module_ro_data[i].name, jerry_create_boolean(true)); } } static void set_process_private(jerry_value_t process, bool wait_source) { jerry_value_t private = jerry_create_object(); iotjs_jval_set_property_jval(process, IOTJS_MAGIC_STRING_PRIVATE, private); iotjs_jval_set_method(private, IOTJS_MAGIC_STRING_COMPILE, proc_compile); iotjs_jval_set_method(private, IOTJS_MAGIC_STRING_COMPILEMODULE, proc_compile_module); iotjs_jval_set_method(private, IOTJS_MAGIC_STRING_READSOURCE, proc_read_source); #ifdef JERRY_DEBUGGER // debugger iotjs_jval_set_method(private, IOTJS_MAGIC_STRING_DEBUGGERGETSOURCE, debugger_get_source); jerry_value_t wait_source_val = jerry_create_boolean(wait_source); iotjs_jval_set_property_jval(private, IOTJS_MAGIC_STRING_DEBUGGERWAITSOURCE, wait_source_val); jerry_release_value(wait_source_val); #endif jerry_release_value(private); } jerry_value_t iotjs_init_process(void) { jerry_value_t process = jerry_create_object(); iotjs_jval_set_method(process, IOTJS_MAGIC_STRING_CWD, proc_cwd); iotjs_jval_set_method(process, IOTJS_MAGIC_STRING_CHDIR, proc_chdir); iotjs_jval_set_method(process, IOTJS_MAGIC_STRING_DOEXIT, proc_do_exit); #ifdef EXPOSE_GC iotjs_jval_set_method(process, IOTJS_MAGIC_STRING_GC, garbage_collector); #endif #ifdef DEBUG jerry_property_descriptor_t prop_desc; jerry_init_property_descriptor_fields(&prop_desc); prop_desc.is_value_defined = true; prop_desc.is_writable_defined = true; prop_desc.is_configurable_defined = true; prop_desc.value = jerry_create_boolean(true); jerry_value_t property_name = jerry_create_string((jerry_char_t*)IOTJS_MAGIC_STRING_DEBUG); jerry_value_t prop_ret_val = jerry_define_own_property(process, property_name, &prop_desc); jerry_release_value(prop_ret_val); jerry_release_value(property_name); jerry_free_property_descriptor_fields(&prop_desc); #endif /* FIXME: Move this platform dependent code path to libtuv * * See the related commit in libuv: * d708df110a03332224bd9be1bbd23093d9cf9022 */ #ifdef WIN32 iotjs_jval_set_property_jval(process, IOTJS_MAGIC_STRING_PID, jerry_create_number(GetCurrentProcessId())); #else /* !WIN32 */ iotjs_jval_set_property_jval(process, IOTJS_MAGIC_STRING_PID, jerry_create_number(getpid())); #endif /* WIN32 */ set_process_env(process); // process.builtin_modules jerry_value_t builtin_modules = jerry_create_object(); set_builtin_modules(builtin_modules); iotjs_jval_set_property_jval(process, IOTJS_MAGIC_STRING_BUILTIN_MODULES, builtin_modules); jerry_release_value(builtin_modules); // 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 set_process_iotjs(process); bool wait_source = false; #ifdef JERRY_DEBUGGER if (iotjs_environment_config(iotjs_environment_get())->debugger != NULL) { wait_source = iotjs_environment_config(iotjs_environment_get()) ->debugger->wait_source; } #endif if (!wait_source) { set_process_argv(process); } set_process_private(process, wait_source); return process; } iotjs-1.0+715/src/modules/iotjs_module_pwm.c000066400000000000000000000213161371177304000210030ustar00rootroot00000000000000/* 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_pwm.h" #include "iotjs_uv_request.h" IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(pwm); IOTJS_DEFINE_PERIPH_CREATE_FUNCTION(pwm); static void iotjs_pwm_destroy(iotjs_pwm_t* pwm) { iotjs_pwm_destroy_platform_data(pwm->platform_data); IOTJS_RELEASE(pwm); } static void pwm_worker(uv_work_t* work_req) { iotjs_periph_data_t* worker_data = (iotjs_periph_data_t*)IOTJS_UV_REQUEST_EXTRA_DATA(work_req); iotjs_pwm_t* pwm = (iotjs_pwm_t*)worker_data->data; switch (worker_data->op) { case kPwmOpClose: worker_data->result = iotjs_pwm_close(pwm); break; case kPwmOpOpen: worker_data->result = iotjs_pwm_open(pwm); break; case kPwmOpSetDutyCycle: worker_data->result = iotjs_pwm_set_dutycycle(pwm); break; case kPwmOpSetEnable: worker_data->result = iotjs_pwm_set_enable(pwm); break; case kPwmOpSetFrequency: /* update the period */ case kPwmOpSetPeriod: worker_data->result = iotjs_pwm_set_period(pwm); break; default: IOTJS_ASSERT(!"Invalid Operation"); } } static jerry_value_t pwm_set_configuration(iotjs_pwm_t* pwm, jerry_value_t jconfig) { JS_GET_REQUIRED_CONF_VALUE(jconfig, pwm->duty_cycle, IOTJS_MAGIC_STRING_DUTYCYCLE, number); if (pwm->duty_cycle < 0.0 || pwm->duty_cycle > 1.0) { return JS_CREATE_ERROR(RANGE, "pwm.dutyCycle must be within 0.0 and 1.0"); } JS_GET_REQUIRED_CONF_VALUE(jconfig, pwm->period, IOTJS_MAGIC_STRING_PERIOD, number); if (pwm->period < 0) { return JS_CREATE_ERROR(RANGE, "pwm.period must be a positive value"); } JS_GET_REQUIRED_CONF_VALUE(jconfig, pwm->pin, IOTJS_MAGIC_STRING_PIN, number); return jerry_create_undefined(); } JS_FUNCTION(pwm_constructor) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, object); DJS_CHECK_ARG_IF_EXIST(1, function); // Create PWM object jerry_value_t jpwm = JS_GET_THIS(); iotjs_pwm_t* pwm = pwm_create(jpwm); jerry_value_t jconfig; JS_GET_REQUIRED_ARG_VALUE(0, jconfig, IOTJS_MAGIC_STRING_CONFIG, object); jerry_value_t res = iotjs_pwm_set_platform_config(pwm, jconfig); if (jerry_value_is_error(res)) { return res; } IOTJS_ASSERT(jerry_value_is_undefined(res)); res = pwm_set_configuration(pwm, jconfig); if (jerry_value_is_error(res)) { return res; } IOTJS_ASSERT(jerry_value_is_undefined(res)); jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); // If the callback doesn't exist, it is completed synchronously. // Otherwise, it will be executed asynchronously. if (!jerry_value_is_null(jcallback)) { iotjs_periph_call_async(pwm, jcallback, kPwmOpOpen, pwm_worker); } else if (!iotjs_pwm_open(pwm)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kPwmOpOpen)); } return jerry_create_undefined(); } JS_FUNCTION(pwm_close) { JS_DECLARE_THIS_PTR(pwm, pwm); DJS_CHECK_ARG_IF_EXIST(1, function); iotjs_periph_call_async(pwm, JS_GET_ARG_IF_EXIST(0, function), kPwmOpClose, pwm_worker); return jerry_create_undefined(); } JS_FUNCTION(pwm_close_sync) { JS_DECLARE_THIS_PTR(pwm, pwm); if (!iotjs_pwm_close(pwm)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kPwmOpClose)); } return jerry_create_undefined(); } JS_FUNCTION(pwm_set_duty_cycle) { JS_DECLARE_THIS_PTR(pwm, pwm); DJS_CHECK_ARGS(1, number); DJS_CHECK_ARG_IF_EXIST(1, function); jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); pwm->duty_cycle = JS_GET_ARG(0, number); if (pwm->duty_cycle < 0.0 || pwm->duty_cycle > 1.0) { return JS_CREATE_ERROR(RANGE, "pwm.dutyCycle must be within 0.0 and 1.0"); } iotjs_periph_call_async(pwm, jcallback, kPwmOpSetDutyCycle, pwm_worker); return jerry_create_undefined(); } JS_FUNCTION(pwm_set_duty_cycle_sync) { JS_DECLARE_THIS_PTR(pwm, pwm); DJS_CHECK_ARGS(1, number); pwm->duty_cycle = JS_GET_ARG(0, number); if (pwm->duty_cycle < 0.0 || pwm->duty_cycle > 1.0) { return JS_CREATE_ERROR(RANGE, "pwm.dutyCycle must be within 0.0 and 1.0"); } if (!iotjs_pwm_set_dutycycle(pwm)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kPwmOpSetDutyCycle)); } return jerry_create_undefined(); } JS_FUNCTION(pwm_set_enable) { JS_DECLARE_THIS_PTR(pwm, pwm); DJS_CHECK_ARGS(1, boolean); DJS_CHECK_ARG_IF_EXIST(1, function); jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); pwm->enable = JS_GET_ARG(0, boolean); iotjs_periph_call_async(pwm, jcallback, kPwmOpSetEnable, pwm_worker); return jerry_create_undefined(); } JS_FUNCTION(pwm_set_enable_sync) { JS_DECLARE_THIS_PTR(pwm, pwm); DJS_CHECK_ARGS(1, boolean); pwm->enable = JS_GET_ARG(0, boolean); if (!iotjs_pwm_set_enable(pwm)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kPwmOpSetEnable)); } return jerry_create_undefined(); } static jerry_value_t pwm_set_period_or_frequency(iotjs_pwm_t* pwm, const jerry_value_t jargv[], const jerry_length_t jargc, uint8_t op, bool async) { const double num_value = JS_GET_ARG(0, number); if (op == kPwmOpSetFrequency) { if (num_value <= 0) { return JS_CREATE_ERROR(RANGE, "frequency must be greater than 0"); } pwm->period = 1.0 / num_value; } else { if (num_value < 0) { return JS_CREATE_ERROR(RANGE, "period must be a positive value"); } pwm->period = num_value; } if (async) { iotjs_periph_call_async(pwm, JS_GET_ARG_IF_EXIST(1, function), op, pwm_worker); } else { if (!iotjs_pwm_set_period(pwm)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(op)); } } return jerry_create_undefined(); } JS_FUNCTION(pwm_set_frequency) { JS_DECLARE_THIS_PTR(pwm, pwm); DJS_CHECK_ARGS(1, number); DJS_CHECK_ARG_IF_EXIST(1, function); return pwm_set_period_or_frequency(pwm, jargv, jargc, kPwmOpSetFrequency, true); } JS_FUNCTION(pwm_set_frequency_sync) { JS_DECLARE_THIS_PTR(pwm, pwm); DJS_CHECK_ARGS(1, number); return pwm_set_period_or_frequency(pwm, jargv, jargc, kPwmOpSetFrequency, false); } JS_FUNCTION(pwm_set_period) { JS_DECLARE_THIS_PTR(pwm, pwm); DJS_CHECK_ARGS(1, number); DJS_CHECK_ARG_IF_EXIST(1, function); return pwm_set_period_or_frequency(pwm, jargv, jargc, kPwmOpSetPeriod, true); } JS_FUNCTION(pwm_set_period_sync) { JS_DECLARE_THIS_PTR(pwm, pwm); DJS_CHECK_ARGS(1, number); return pwm_set_period_or_frequency(pwm, jargv, jargc, kPwmOpSetPeriod, false); } jerry_value_t iotjs_init_pwm(void) { jerry_value_t jpwm_cons = jerry_create_external_function(pwm_constructor); jerry_value_t jprototype = jerry_create_object(); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_CLOSE, pwm_close); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_CLOSESYNC, pwm_close_sync); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_SETDUTYCYCLE, pwm_set_duty_cycle); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_SETDUTYCYCLESYNC, pwm_set_duty_cycle_sync); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_SETENABLE, pwm_set_enable); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_SETENABLESYNC, pwm_set_enable_sync); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_SETFREQUENCY, pwm_set_frequency); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_SETFREQUENCYSYNC, pwm_set_frequency_sync); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_SETPERIOD, pwm_set_period); iotjs_jval_set_method(jprototype, IOTJS_MAGIC_STRING_SETPERIODSYNC, pwm_set_period_sync); iotjs_jval_set_property_jval(jpwm_cons, IOTJS_MAGIC_STRING_PROTOTYPE, jprototype); jerry_release_value(jprototype); return jpwm_cons; } iotjs-1.0+715/src/modules/iotjs_module_pwm.h000066400000000000000000000034651371177304000210150ustar00rootroot00000000000000/* 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_PWM_H #define IOTJS_MODULE_PWM_H #include "iotjs_def.h" #include "iotjs_module_periph_common.h" #if defined(__TIZENRT__) #include #include #endif // Forward declaration of platform data. These are only used by platform code. // Generic PWM module never dereferences platform data pointer. typedef struct iotjs_pwm_platform_data_s iotjs_pwm_platform_data_t; typedef struct { jerry_value_t jobject; iotjs_pwm_platform_data_t* platform_data; uint32_t pin; double duty_cycle; double period; bool enable; } iotjs_pwm_t; jerry_value_t iotjs_pwm_set_platform_config(iotjs_pwm_t* pwm, const jerry_value_t jconfig); bool iotjs_pwm_open(iotjs_pwm_t* pwm); bool iotjs_pwm_set_period(iotjs_pwm_t* pwm); bool iotjs_pwm_set_dutycycle(iotjs_pwm_t* pwm); bool iotjs_pwm_set_enable(iotjs_pwm_t* pwm); bool iotjs_pwm_close(iotjs_pwm_t* pwm); // Platform-related functions; they are implemented // by platform code (i.e.: linux, nuttx, tizen). void iotjs_pwm_create_platform_data(iotjs_pwm_t* pwm); void iotjs_pwm_destroy_platform_data(iotjs_pwm_platform_data_t* platform_data); #endif /* IOTJS_MODULE_PWM_H */ iotjs-1.0+715/src/modules/iotjs_module_spi.c000066400000000000000000000247551371177304000210050ustar00rootroot00000000000000/* 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_uv_request.h" IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(spi); IOTJS_DEFINE_PERIPH_CREATE_FUNCTION(spi); static void iotjs_spi_destroy(iotjs_spi_t* spi) { iotjs_spi_destroy_platform_data(spi->platform_data); IOTJS_RELEASE(spi); } static int spi_get_array_data(char** buf, jerry_value_t jarray) { jerry_value_t jlength = iotjs_jval_get_property(jarray, IOTJS_MAGIC_STRING_LENGTH); IOTJS_ASSERT(!jerry_value_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++) { jerry_value_t jdata = iotjs_jval_get_property_by_index(jarray, i); (*buf)[i] = iotjs_jval_as_number(jdata); jerry_release_value(jdata); } jerry_release_value(jlength); return (int)length; } /* Default configuration: *{ * mode: spi.MODE[0], * chipSelect: spi.CHIPSELECT.NONE, * maxSpeed: 500000, * bitsPerWord: 8, * bitOrder: spi.BITORDER.MSB, * loopback: false * } */ static jerry_value_t spi_set_configuration(iotjs_spi_t* spi, jerry_value_t joptions) { jerry_value_t jmode = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_MODE); if (jerry_value_is_undefined(jmode)) { spi->mode = kSpiMode_0; } else { if (jerry_value_is_number(jmode)) { spi->mode = (SpiMode)iotjs_jval_as_number(jmode); } else { spi->mode = __kSpiModeMax; } if (spi->mode >= __kSpiModeMax) { return JS_CREATE_ERROR( TYPE, "Bad arguments - mode should be MODE[0], [1], [2] or [3]"); } } jerry_release_value(jmode); jerry_value_t jchip_select = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_CHIPSELECT); if (jerry_value_is_undefined(jchip_select)) { spi->chip_select = kSpiCsNone; } else { if (jerry_value_is_number(jchip_select)) { spi->chip_select = (SpiChipSelect)iotjs_jval_as_number(jchip_select); } else { spi->chip_select = __kSpiCsMax; } if (spi->chip_select >= __kSpiCsMax) { return JS_CREATE_ERROR( TYPE, "Bad arguments - chipSelect should be CHIPSELECT.NONE or HIGH"); } } jerry_release_value(jchip_select); jerry_value_t jmax_speed = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_MAXSPEED); if (jerry_value_is_undefined(jmax_speed)) { spi->max_speed = 500000; } else { if (!jerry_value_is_number(jmax_speed)) { return JS_CREATE_ERROR(TYPE, "Bad arguments - maxSpeed should be Number"); } spi->max_speed = iotjs_jval_as_number(jmax_speed); } jerry_release_value(jmax_speed); jerry_value_t jbits_per_word = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_BITSPERWORD); if (jerry_value_is_undefined(jbits_per_word)) { spi->bits_per_word = 8; } else { if (jerry_value_is_number(jbits_per_word)) { spi->bits_per_word = iotjs_jval_as_number(jbits_per_word); } else { spi->bits_per_word = 0; } if (spi->bits_per_word != 8 && spi->bits_per_word != 9) { return JS_CREATE_ERROR(TYPE, "Bad arguments - bitsPerWord should be 8 or 9"); } } jerry_release_value(jbits_per_word); jerry_value_t jbit_order = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_BITORDER); if (jerry_value_is_undefined(jbit_order)) { spi->bit_order = kSpiOrderMsb; } else { if (jerry_value_is_number(jbit_order)) { spi->bit_order = (SpiOrder)iotjs_jval_as_number(jbit_order); } else { spi->bit_order = __kSpiOrderMax; } if (spi->bit_order >= __kSpiOrderMax) { return JS_CREATE_ERROR( TYPE, "Bad arguments - bitOrder should be BITORDER.MSB or LSB"); } } jerry_release_value(jbit_order); jerry_value_t jloopback = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_LOOPBACK); if (jerry_value_is_undefined(jloopback)) { spi->loopback = false; } else { if (!jerry_value_is_boolean(jloopback)) { return JS_CREATE_ERROR(TYPE, "Bad arguments - loopback should be Boolean"); } spi->loopback = iotjs_jval_as_boolean(jloopback); } jerry_release_value(jloopback); return jerry_create_undefined(); } /* * SPI worker function */ static void spi_worker(uv_work_t* work_req) { iotjs_periph_data_t* worker_data = (iotjs_periph_data_t*)IOTJS_UV_REQUEST_EXTRA_DATA(work_req); iotjs_spi_t* spi = (iotjs_spi_t*)worker_data->data; switch (worker_data->op) { case kSpiOpClose: { worker_data->result = iotjs_spi_close(spi); break; } case kSpiOpOpen: { worker_data->result = iotjs_spi_open(spi); break; } case kSpiOpTransferArray: case kSpiOpTransferBuffer: { worker_data->result = iotjs_spi_transfer(spi); break; } default: IOTJS_ASSERT(!"Invalid Operation"); } } JS_FUNCTION(spi_constructor) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, object); DJS_CHECK_ARG_IF_EXIST(1, function); // Create SPI object jerry_value_t jspi = JS_GET_THIS(); iotjs_spi_t* spi = spi_create(jspi); // Set configuration jerry_value_t jconfig; JS_GET_REQUIRED_ARG_VALUE(0, jconfig, IOTJS_MAGIC_STRING_CONFIG, object); jerry_value_t res = iotjs_spi_set_platform_config(spi, jconfig); if (jerry_value_is_error(res)) { return res; } IOTJS_ASSERT(jerry_value_is_undefined(res)); res = spi_set_configuration(spi, jconfig); if (jerry_value_is_error(res)) { return res; } IOTJS_ASSERT(jerry_value_is_undefined(res)); jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); // If the callback doesn't exist, it is completed synchronously. // Otherwise, it will be executed asynchronously. if (!jerry_value_is_null(jcallback)) { iotjs_periph_call_async(spi, jcallback, kSpiOpOpen, spi_worker); } else if (!iotjs_spi_open(spi)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kSpiOpOpen)); } return jerry_create_undefined(); } static uint8_t spi_transfer_helper(jerry_value_t jtx_buf, iotjs_spi_t* spi) { uint8_t result = kSpiOpTransferBuffer; if (jerry_value_is_array(jtx_buf)) { spi->buf_len = spi_get_array_data(&spi->tx_buf_data, jtx_buf); result = kSpiOpTransferArray; } else if (jerry_value_is_object(jtx_buf)) { iotjs_bufferwrap_t* tx_buf = iotjs_bufferwrap_from_jbuffer(jtx_buf); spi->tx_buf_data = tx_buf->buffer; spi->buf_len = iotjs_bufferwrap_length(tx_buf); } IOTJS_ASSERT(spi->buf_len > 0); spi->rx_buf_data = iotjs_buffer_allocate(spi->buf_len); IOTJS_ASSERT(spi->tx_buf_data != NULL && spi->rx_buf_data != NULL); return result; } // FIXME: do not need transferArray if array buffer is implemented. JS_FUNCTION(spi_transfer) { JS_DECLARE_THIS_PTR(spi, spi); DJS_CHECK_ARG_IF_EXIST(1, function); uint8_t op = spi_transfer_helper(jargv[0], spi); iotjs_periph_call_async(spi, JS_GET_ARG_IF_EXIST(1, function), op, spi_worker); return jerry_create_undefined(); } JS_FUNCTION(spi_transfer_sync) { JS_DECLARE_THIS_PTR(spi, spi); uint8_t op = spi_transfer_helper(jargv[0], spi); jerry_value_t result = jerry_create_undefined(); if (!iotjs_spi_transfer(spi)) { result = JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(op)); } else { result = iotjs_jval_create_byte_array(spi->buf_len, spi->rx_buf_data); } if (op == kSpiOpTransferArray) { IOTJS_RELEASE(spi->tx_buf_data); } IOTJS_RELEASE(spi->rx_buf_data); return result; } JS_FUNCTION(spi_close) { JS_DECLARE_THIS_PTR(spi, spi); DJS_CHECK_ARG_IF_EXIST(1, function); iotjs_periph_call_async(spi, JS_GET_ARG_IF_EXIST(0, function), kSpiOpClose, spi_worker); return jerry_create_undefined(); } JS_FUNCTION(spi_close_sync) { JS_DECLARE_THIS_PTR(spi, spi); if (!iotjs_spi_close(spi)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kSpiOpClose)); } return jerry_create_undefined(); } jerry_value_t iotjs_init_spi(void) { jerry_value_t jspi_cons = jerry_create_external_function(spi_constructor); jerry_value_t prototype = jerry_create_object(); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_CLOSE, spi_close); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_CLOSESYNC, spi_close_sync); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_TRANSFER, spi_transfer); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_TRANSFERSYNC, spi_transfer_sync); iotjs_jval_set_property_jval(jspi_cons, IOTJS_MAGIC_STRING_PROTOTYPE, prototype); jerry_release_value(prototype); // SPI mode properties jerry_value_t jmode = jerry_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_cons, IOTJS_MAGIC_STRING_MODE_U, jmode); jerry_release_value(jmode); // SPI mode properties jerry_value_t jcs = jerry_create_object(); iotjs_jval_set_property_number(jcs, IOTJS_MAGIC_STRING_NONE_U, kSpiCsNone); iotjs_jval_set_property_number(jcs, IOTJS_MAGIC_STRING_HIGH_U, kSpiCsHigh); iotjs_jval_set_property_jval(jspi_cons, IOTJS_MAGIC_STRING_CHIPSELECT_U, jcs); jerry_release_value(jcs); // SPI order properties jerry_value_t jbit_order = jerry_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_cons, IOTJS_MAGIC_STRING_BITORDER_U, jbit_order); jerry_release_value(jbit_order); return jspi_cons; } iotjs-1.0+715/src/modules/iotjs_module_spi.h000066400000000000000000000041501371177304000207750ustar00rootroot00000000000000/* 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_module_periph_common.h" typedef enum { kSpiMode_0, kSpiMode_1, kSpiMode_2, kSpiMode_3, __kSpiModeMax } SpiMode; typedef enum { kSpiCsNone, kSpiCsHigh, __kSpiCsMax } SpiChipSelect; typedef enum { kSpiOrderMsb, kSpiOrderLsb, __kSpiOrderMax } SpiOrder; // Forward declaration of platform data. These are only used by platform code. // Generic SPI module never dereferences platform data pointer. typedef struct iotjs_spi_platform_data_s iotjs_spi_platform_data_t; // This SPI class provides interfaces for SPI operation. typedef struct { jerry_value_t jobject; iotjs_spi_platform_data_t* platform_data; 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_spi_t; jerry_value_t iotjs_spi_set_platform_config(iotjs_spi_t* spi, const jerry_value_t jconfig); bool iotjs_spi_open(iotjs_spi_t* spi); bool iotjs_spi_transfer(iotjs_spi_t* spi); bool iotjs_spi_close(iotjs_spi_t* spi); // Platform-related functions; they are implemented // by platform code (i.e.: linux, nuttx, tizen). void iotjs_spi_create_platform_data(iotjs_spi_t* spi); void iotjs_spi_destroy_platform_data(iotjs_spi_platform_data_t* pdata); #endif /* IOTJS_MODULE_SPI_H */ iotjs-1.0+715/src/modules/iotjs_module_stm32f4dis.c000066400000000000000000000016031371177304000220770ustar00rootroot00000000000000/* 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_stm32f4dis.h" jerry_value_t iotjs_init_stm32f4dis() { jerry_value_t stm32f4dis = jerry_create_object(); #if defined(__NUTTX__) iotjs_stm32f4dis_pin_initialize(stm32f4dis); #endif return stm32f4dis; } iotjs-1.0+715/src/modules/iotjs_module_stm32f4dis.h000066400000000000000000000014521371177304000221060ustar00rootroot00000000000000/* 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_STM32F4DIS_H #define IOTJS_MODULE_STM32F4DIS_H void iotjs_stm32f4dis_pin_initialize(jerry_value_t jobj); #endif /* IOTJS_MODULE_STM32F4DIS_H */ iotjs-1.0+715/src/modules/iotjs_module_stm32f7nucleo.c000066400000000000000000000017171371177304000226160ustar00rootroot00000000000000/* Copyright 2019-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_stm32f7nucleo.h" jerry_value_t iotjs_init_stm32f7nucleo() { jerry_value_t stm32f7nucleo = jerry_create_object(); /* Hardware support in progress, do initialization here */ #if defined(__NUTTX__) iotjs_stm32f7nucleo_pin_initialize(stm32f7nucleo); #endif return stm32f7nucleo; } iotjs-1.0+715/src/modules/iotjs_module_stm32f7nucleo.h000066400000000000000000000014551371177304000226220ustar00rootroot00000000000000/* Copyright 2019-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_STM32F4DIS_H #define IOTJS_MODULE_STM32F4DIS_H void iotjs_stm32f7nucleo_pin_initialize(jerry_value_t jobj); #endif /* IOTJS_MODULE_STM32F4DIS_H */ iotjs-1.0+715/src/modules/iotjs_module_tcp.c000066400000000000000000000305041371177304000207650ustar00rootroot00000000000000/* 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_tcp.h" #include "iotjs_module_buffer.h" #include "iotjs_uv_handle.h" #include "iotjs_uv_request.h" static const jerry_object_native_info_t this_module_native_info = { NULL }; void iotjs_tcp_object_init(jerry_value_t jtcp) { // uv_tcp_t* can be handled as uv_handle_t* or even as uv_stream_t* uv_handle_t* handle = iotjs_uv_handle_create(sizeof(uv_tcp_t), jtcp, &this_module_native_info, 0); const iotjs_environment_t* env = iotjs_environment_get(); uv_tcp_init(iotjs_environment_loop(env), (uv_tcp_t*)handle); } static void iotjs_tcp_report_req_result(uv_req_t* req, int status) { IOTJS_ASSERT(req != NULL); // Take callback function object. jerry_value_t jcallback = *IOTJS_UV_REQUEST_JSCALLBACK(req); // Only parameter is status code. jerry_value_t jstatus = jerry_create_number(status); // Make callback. iotjs_invoke_callback(jcallback, jerry_create_undefined(), &jstatus, 1); // Destroy args jerry_release_value(jstatus); // Release request. iotjs_uv_request_destroy(req); } JS_FUNCTION(tcp_constructor) { DJS_CHECK_THIS(); jerry_value_t jtcp = JS_GET_THIS(); iotjs_tcp_object_init(jtcp); return jerry_create_undefined(); } // Socket close result handler. void after_close(uv_handle_t* handle) { jerry_value_t jtcp = IOTJS_UV_HANDLE_DATA(handle)->jobject; // callback function. jerry_value_t jcallback = iotjs_jval_get_property(jtcp, IOTJS_MAGIC_STRING_ONCLOSE); if (jerry_value_is_function(jcallback)) { iotjs_invoke_callback(jcallback, jerry_create_undefined(), NULL, 0); } jerry_release_value(jcallback); } // Close socket JS_FUNCTION(tcp_close) { JS_DECLARE_PTR(jthis, uv_handle_t, uv_handle); iotjs_uv_handle_close(uv_handle, after_close); return jerry_create_undefined(); } // Socket binding, this function would be called from server socket before // start listening. // [0] address // [1] port JS_FUNCTION(tcp_bind) { JS_DECLARE_PTR(jthis, uv_tcp_t, tcp_handle); DJS_CHECK_ARGS(2, string, number); iotjs_string_t address = JS_GET_ARG(0, string); int port = JS_GET_ARG(1, number); sockaddr_in addr; int err = uv_ip4_addr(iotjs_string_data(&address), port, &addr); if (err == 0) { err = uv_tcp_bind(tcp_handle, (const sockaddr*)(&addr), 0); } iotjs_string_destroy(&address); return jerry_create_number(err); } // Connection request result handler. static void after_connect(uv_connect_t* req, int status) { iotjs_tcp_report_req_result((uv_req_t*)req, status); } // Create a connection using the socket. // [0] address // [1] port // [2] callback JS_FUNCTION(tcp_connect) { JS_DECLARE_PTR(jthis, uv_tcp_t, tcp_handle); DJS_CHECK_ARGS(3, string, number, function); iotjs_string_t address = JS_GET_ARG(0, string); int port = JS_GET_ARG(1, number); jerry_value_t jcallback = JS_GET_ARG(2, function); sockaddr_in addr; int err = uv_ip4_addr(iotjs_string_data(&address), port, &addr); if (err == 0) { // Create connection request and configure request data. uv_req_t* req_connect = iotjs_uv_request_create(sizeof(uv_connect_t), jcallback, 0); // Create connection request. err = uv_tcp_connect((uv_connect_t*)req_connect, tcp_handle, (const sockaddr*)(&addr), after_connect); if (err) { iotjs_uv_request_destroy(req_connect); } } iotjs_string_destroy(&address); return jerry_create_number(err); } // A client socket wants to connect to this server. // Parameters: // * uv_stream_t* handle - server handle // * int status - status code static void on_connection(uv_stream_t* handle, int status) { jerry_value_t jtcp = IOTJS_UV_HANDLE_DATA(handle)->jobject; // `onconnection` callback. jerry_value_t jonconnection = iotjs_jval_get_property(jtcp, IOTJS_MAGIC_STRING_ONCONNECTION); IOTJS_ASSERT(jerry_value_is_function(jonconnection)); // The callback takes two parameter // [0] status // [1] client tcp object size_t argc = 1; jerry_value_t args[2] = { jerry_create_number(status), 0 }; if (status == 0) { // Create client socket handle wrapper. jerry_value_t jcreate_tcp = iotjs_jval_get_property(jtcp, IOTJS_MAGIC_STRING_CREATETCP); IOTJS_ASSERT(jerry_value_is_function(jcreate_tcp)); jerry_value_t jclient_tcp = jerry_call_function(jcreate_tcp, jerry_create_undefined(), NULL, 0); IOTJS_ASSERT(!jerry_value_is_error(jclient_tcp)); IOTJS_ASSERT(jerry_value_is_object(jclient_tcp)); void* client_handle = NULL; bool has_client_handle = jerry_get_object_native_pointer(jclient_tcp, &client_handle, &this_module_native_info); if (!has_client_handle || uv_accept(handle, (uv_stream_t*)client_handle)) { jerry_release_value(args[0]); return; } args[argc++] = jclient_tcp; jerry_release_value(jcreate_tcp); } iotjs_invoke_callback(jonconnection, jtcp, args, argc); jerry_release_value(jonconnection); for (size_t i = 0; i < argc; i++) { jerry_release_value(args[i]); } } JS_FUNCTION(tcp_listen) { JS_DECLARE_PTR(jthis, uv_tcp_t, tcp_handle); DJS_CHECK_ARGS(1, number); int backlog = JS_GET_ARG(0, number); int err = uv_listen((uv_stream_t*)tcp_handle, backlog, on_connection); return jerry_create_number(err); } void AfterWrite(uv_write_t* req, int status) { iotjs_tcp_report_req_result((uv_req_t*)req, status); } JS_FUNCTION(tcp_write) { JS_DECLARE_PTR(jthis, uv_stream_t, tcp_handle); DJS_CHECK_ARGS(2, object, function); const jerry_value_t jbuffer = JS_GET_ARG(0, object); iotjs_bufferwrap_t* buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuffer); size_t len = iotjs_bufferwrap_length(buffer_wrap); uv_buf_t buf; buf.base = buffer_wrap->buffer; buf.len = len; jerry_value_t arg1 = JS_GET_ARG(1, object); uv_req_t* req_write = iotjs_uv_request_create(sizeof(uv_write_t), arg1, 0); int err = uv_write((uv_write_t*)req_write, tcp_handle, &buf, 1, AfterWrite); if (err) { iotjs_uv_request_destroy((uv_req_t*)req_write); } return jerry_create_number(err); } static void on_alloc(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { if (suggested_size > IOTJS_MAX_READ_BUFFER_SIZE) { suggested_size = IOTJS_MAX_READ_BUFFER_SIZE; } buf->base = iotjs_buffer_allocate(suggested_size); buf->len = suggested_size; } static void on_read(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) { jerry_value_t jtcp = IOTJS_UV_HANDLE_DATA(handle)->jobject; // socket object jerry_value_t jsocket = iotjs_jval_get_property(jtcp, IOTJS_MAGIC_STRING_OWNER); IOTJS_ASSERT(jerry_value_is_object(jsocket)); // onread callback jerry_value_t jonread = iotjs_jval_get_property(jtcp, IOTJS_MAGIC_STRING_ONREAD); IOTJS_ASSERT(jerry_value_is_function(jonread)); size_t argc = 3; jerry_value_t jargs[4] = { jsocket, jerry_create_number(nread), jerry_create_boolean(false), 0 }; if (nread <= 0) { iotjs_buffer_release(buf->base); if (nread < 0) { if (nread == UV__EOF) { jargs[2] = jerry_create_boolean(true); } iotjs_invoke_callback(jonread, jerry_create_undefined(), jargs, argc); } } else { jerry_value_t jbuffer = iotjs_bufferwrap_create_buffer((size_t)nread); iotjs_bufferwrap_t* buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuffer); iotjs_bufferwrap_copy(buffer_wrap, buf->base, (size_t)nread); jargs[argc++] = jbuffer; iotjs_invoke_callback(jonread, jerry_create_undefined(), jargs, argc); iotjs_buffer_release(buf->base); } for (uint8_t i = 0; i < argc; i++) { jerry_release_value(jargs[i]); } jerry_release_value(jonread); } JS_FUNCTION(tcp_read_start) { JS_DECLARE_PTR(jthis, uv_stream_t, tcp_handle); int err = uv_read_start(tcp_handle, on_alloc, on_read); return jerry_create_number(err); } static void AfterShutdown(uv_shutdown_t* req, int status) { iotjs_tcp_report_req_result((uv_req_t*)req, status); } JS_FUNCTION(tcp_shutdown) { JS_DECLARE_PTR(jthis, uv_stream_t, tcp_handle); DJS_CHECK_ARGS(1, function); jerry_value_t arg0 = JS_GET_ARG(0, object); uv_shutdown_t* req_shutdown = (uv_shutdown_t*)iotjs_uv_request_create(sizeof(uv_shutdown_t), arg0, 0); int err = uv_shutdown(req_shutdown, tcp_handle, AfterShutdown); if (err) { iotjs_uv_request_destroy((uv_req_t*)req_shutdown); } return jerry_create_number(err); } // Enable/Disable keepalive option. // [0] enable // [1] delay JS_FUNCTION(tcp_set_keep_alive) { JS_DECLARE_PTR(jthis, uv_tcp_t, tcp_handle); DJS_CHECK_ARGS(2, number, number); int enable = JS_GET_ARG(0, number); unsigned delay = JS_GET_ARG(1, number); int err = uv_tcp_keepalive(tcp_handle, enable, delay); return jerry_create_number(err); } JS_FUNCTION(tcp_err_name) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, number); int errorcode = JS_GET_ARG(0, number); return jerry_create_string_from_utf8( (const jerry_char_t*)uv_err_name(errorcode)); } // used in iotjs_module_udp.cpp void address_to_js(jerry_value_t obj, const sockaddr* addr) { char ip[INET6_ADDRSTRLEN]; const sockaddr_in* a4; const sockaddr_in6* a6; int port; switch (addr->sa_family) { case AF_INET6: { a6 = (const sockaddr_in6*)(addr); uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip); port = ntohs(a6->sin6_port); iotjs_jval_set_property_string_raw(obj, IOTJS_MAGIC_STRING_ADDRESS, ip); iotjs_jval_set_property_string_raw(obj, IOTJS_MAGIC_STRING_FAMILY, IOTJS_MAGIC_STRING_IPV6); iotjs_jval_set_property_number(obj, IOTJS_MAGIC_STRING_PORT, port); break; } case AF_INET: { a4 = (const sockaddr_in*)(addr); uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip); port = ntohs(a4->sin_port); iotjs_jval_set_property_string_raw(obj, IOTJS_MAGIC_STRING_ADDRESS, ip); iotjs_jval_set_property_string_raw(obj, IOTJS_MAGIC_STRING_FAMILY, IOTJS_MAGIC_STRING_IPV4); iotjs_jval_set_property_number(obj, IOTJS_MAGIC_STRING_PORT, port); break; } default: { iotjs_jval_set_property_string_raw(obj, IOTJS_MAGIC_STRING_ADDRESS, ""); break; } } } JS_FUNCTION(tcp_get_socket_name) { JS_DECLARE_PTR(jthis, uv_tcp_t, tcp_handle); DJS_CHECK_ARGS(1, object); sockaddr_storage storage; int addrlen = sizeof(storage); sockaddr* const addr = (sockaddr*)(&storage); int err = uv_tcp_getsockname(tcp_handle, addr, &addrlen); if (err == 0) address_to_js(JS_GET_ARG(0, object), addr); return jerry_create_number(err); } jerry_value_t iotjs_init_tcp(void) { jerry_value_t tcp = jerry_create_external_function(tcp_constructor); jerry_value_t prototype = jerry_create_object(); iotjs_jval_set_property_jval(tcp, IOTJS_MAGIC_STRING_PROTOTYPE, prototype); iotjs_jval_set_method(tcp, IOTJS_MAGIC_STRING_ERRNAME, tcp_err_name); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_CLOSE, tcp_close); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_CONNECT, tcp_connect); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_BIND, tcp_bind); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_LISTEN, tcp_listen); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_WRITE, tcp_write); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_READSTART, tcp_read_start); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_SHUTDOWN, tcp_shutdown); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_SETKEEPALIVE, tcp_set_keep_alive); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_GETSOCKNAME, tcp_get_socket_name); jerry_release_value(prototype); return tcp; } iotjs-1.0+715/src/modules/iotjs_module_tcp.h000066400000000000000000000017361371177304000207770ustar00rootroot00000000000000/* 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_MODULE_TCP_H #define IOTJS_MODULE_TCP_H #include "iotjs_binding.h" typedef struct sockaddr sockaddr; typedef struct sockaddr_in sockaddr_in; typedef struct sockaddr_in6 sockaddr_in6; typedef struct sockaddr_storage sockaddr_storage; void address_to_js(jerry_value_t obj, const sockaddr* addr); #endif /* IOTJS_MODULE_TCP_H */ iotjs-1.0+715/src/modules/iotjs_module_timer.c000066400000000000000000000051651371177304000213240ustar00rootroot00000000000000/* 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_uv_handle.h" static const jerry_object_native_info_t this_module_native_info = { NULL }; void iotjs_timer_object_init(jerry_value_t jtimer) { uv_handle_t* handle = iotjs_uv_handle_create(sizeof(uv_timer_t), jtimer, &this_module_native_info, 0); const iotjs_environment_t* env = iotjs_environment_get(); uv_timer_init(iotjs_environment_loop(env), (uv_timer_t*)handle); } static void timeout_handler(uv_timer_t* handle) { IOTJS_ASSERT(handle != NULL); jerry_value_t jobject = IOTJS_UV_HANDLE_DATA(handle)->jobject; jerry_value_t jcallback = iotjs_jval_get_property(jobject, IOTJS_MAGIC_STRING_HANDLETIMEOUT); iotjs_invoke_callback(jcallback, jobject, NULL, 0); jerry_release_value(jcallback); } JS_FUNCTION(timer_start) { // Check parameters. JS_DECLARE_PTR(jthis, uv_timer_t, timer_handle); DJS_CHECK_ARGS(2, number, number); // parameters. uint64_t timeout = JS_GET_ARG(0, number); uint64_t repeat = JS_GET_ARG(1, number); // Start timer. int res = uv_timer_start(timer_handle, timeout_handler, timeout, repeat); return jerry_create_number(res); } JS_FUNCTION(timer_stop) { JS_DECLARE_PTR(jthis, uv_handle_t, timer_handle); // Stop timer. if (!uv_is_closing(timer_handle)) { iotjs_uv_handle_close(timer_handle, NULL); } return jerry_create_number(0); } JS_FUNCTION(timer_constructor) { DJS_CHECK_THIS(); const jerry_value_t jtimer = JS_GET_THIS(); iotjs_timer_object_init(jtimer); return jerry_create_undefined(); } jerry_value_t iotjs_init_timer(void) { jerry_value_t timer = jerry_create_external_function(timer_constructor); jerry_value_t prototype = jerry_create_object(); iotjs_jval_set_property_jval(timer, IOTJS_MAGIC_STRING_PROTOTYPE, prototype); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_START, timer_start); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_STOP, timer_stop); jerry_release_value(prototype); return timer; } iotjs-1.0+715/src/modules/iotjs_module_tizen.c000066400000000000000000000022531371177304000213300ustar00rootroot00000000000000/* Copyright 2018-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_bridge.h" extern void iotjs_tizen_func(const char* command, const char* message, void* handle); /** * Init method called by IoT.js */ jerry_value_t iotjs_init_tizen() { char* module_name = IOTJS_MAGIC_STRING_TIZEN; jerry_value_t mymodule = jerry_create_object(); iotjs_jval_set_property_string_raw(mymodule, IOTJS_MAGIC_STRING_MODULE_NAME, module_name); iotjs_bridge_register(module_name, iotjs_tizen_func); return mymodule; } iotjs-1.0+715/src/modules/iotjs_module_tls.c000066400000000000000000000436621371177304000210120ustar00rootroot00000000000000/* Copyright 2018-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_module_tls.h" #include "iotjs_module_buffer.h" #include "stdarg.h" static void iotjs_tls_context_destroy(iotjs_tls_context_t *tls_context); static const jerry_object_native_info_t tls_context_native_info = { .free_cb = (jerry_object_native_free_callback_t)iotjs_tls_context_destroy }; static void iotjs_tls_context_destroy(iotjs_tls_context_t *tls_context) { if (tls_context->ref_count > 1) { tls_context->ref_count--; return; } mbedtls_x509_crt_free(&tls_context->cert_auth); mbedtls_x509_crt_free(&tls_context->own_cert); mbedtls_pk_free(&tls_context->pkey); mbedtls_ctr_drbg_free(&tls_context->ctr_drbg); mbedtls_entropy_free(&tls_context->entropy); IOTJS_RELEASE(tls_context); } static iotjs_tls_context_t *iotjs_tls_context_create( const jerry_value_t jobject) { iotjs_tls_context_t *tls_context = IOTJS_ALLOC(iotjs_tls_context_t); tls_context->ref_count = 1; tls_context->context_flags = 0; mbedtls_entropy_init(&tls_context->entropy); mbedtls_ctr_drbg_init(&tls_context->ctr_drbg); mbedtls_pk_init(&tls_context->pkey); mbedtls_x509_crt_init(&tls_context->own_cert); mbedtls_x509_crt_init(&tls_context->cert_auth); jerry_set_object_native_pointer(jobject, tls_context, &tls_context_native_info); return tls_context; } IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(tls); static void iotjs_tls_destroy(iotjs_tls_t *tls_data) { mbedtls_ssl_free(&tls_data->ssl); mbedtls_ssl_config_free(&tls_data->conf); iotjs_tls_context_destroy(tls_data->tls_context); IOTJS_RELEASE(tls_data->bio.receive_bio.mem); IOTJS_RELEASE(tls_data->bio.send_bio.mem); IOTJS_RELEASE(tls_data); } static iotjs_tls_t *iotjs_tls_create(const jerry_value_t jobject, iotjs_tls_context_t *tls_context) { iotjs_tls_t *tls_data = IOTJS_ALLOC(iotjs_tls_t); tls_context->ref_count++; tls_data->tls_context = tls_context; mbedtls_ssl_config_init(&tls_data->conf); mbedtls_ssl_init(&tls_data->ssl); tls_data->state = TLS_HANDSHAKE_READY; tls_data->jobject = jobject; jerry_set_object_native_pointer(jobject, tls_data, &this_module_native_info); return tls_data; } static void iotjs_bio_init(iotjs_bio_t *bio, size_t size) { bio->mem = (char *)iotjs_buffer_allocate(size); bio->size = size; bio->read_index = 0; bio->write_index = 0; } static size_t iotjs_bio_pending(iotjs_bio_t *bio) { if (bio->read_index <= bio->write_index) { return bio->write_index - bio->read_index; } return bio->write_index + bio->size - bio->read_index; } static size_t iotjs_bio_remaining(iotjs_bio_t *bio) { if (bio->write_index < bio->read_index) { return bio->read_index - bio->write_index - 1; } return bio->read_index + bio->size - bio->write_index - 1; } static void iotjs_bio_read(iotjs_bio_t *bio, char *buf, size_t size) { IOTJS_ASSERT(size <= iotjs_bio_pending(bio)); if (bio->read_index + size > bio->size) { size_t copy_size = bio->size - bio->read_index; memcpy(buf, bio->mem + bio->read_index, copy_size); size -= copy_size; buf += copy_size; bio->read_index = 0; } memcpy(buf, bio->mem + bio->read_index, size); bio->read_index += size; } static void iotjs_bio_write(iotjs_bio_t *bio, const char *buf, size_t size) { IOTJS_ASSERT(size <= iotjs_bio_remaining(bio)); if (bio->write_index + size > bio->size) { size_t copy_size = bio->size - bio->write_index; memcpy(bio->mem + bio->write_index, buf, copy_size); size -= copy_size; buf += copy_size; bio->write_index = 0; } memcpy(bio->mem + bio->write_index, buf, size); bio->write_index += size; } static int iotjs_bio_net_send(void *ctx, const unsigned char *buf, size_t len) { iotjs_bio_t *send_bio = &(((iotjs_bio_pair_t *)ctx)->send_bio); size_t remaining = iotjs_bio_remaining(send_bio); if (remaining == 0) { return MBEDTLS_ERR_SSL_WANT_WRITE; } if (len > remaining) { len = remaining; } iotjs_bio_write(send_bio, (const char *)buf, len); return (int)len; } static int iotjs_bio_net_receive(void *ctx, unsigned char *buf, size_t len) { iotjs_bio_t *receive_bio = &(((iotjs_bio_pair_t *)ctx)->receive_bio); size_t pending = iotjs_bio_pending(receive_bio); if (pending == 0) { return MBEDTLS_ERR_SSL_WANT_READ; } if (len > pending) { len = pending; } iotjs_bio_read(receive_bio, (char *)buf, len); return (int)len; } JS_FUNCTION(tls_tlscontext) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, object); jerry_value_t jtls = JS_GET_THIS(); iotjs_tls_context_t *tls_context = iotjs_tls_context_create(jtls); jerry_value_t joptions = JS_GET_ARG(0, object); // Set deterministic random bit generator if (mbedtls_ctr_drbg_seed(&tls_context->ctr_drbg, mbedtls_entropy_func, &tls_context->entropy, NULL, 0) != 0) { return JS_CREATE_ERROR(COMMON, "drbg seeding failed"); } // User provided certificate int ret = 0; jerry_value_t jcert = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_CERT); jerry_value_t jkey = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_KEY); iotjs_string_t cert_string; iotjs_string_t key_string; if (iotjs_jbuffer_as_string(jcert, &cert_string)) { const char *cert_chars = iotjs_string_data(&cert_string); ret = mbedtls_x509_crt_parse(&tls_context->own_cert, (const unsigned char *)cert_chars, (size_t)iotjs_string_size(&cert_string) + 1); iotjs_string_destroy(&cert_string); if (ret == 0 && iotjs_jbuffer_as_string(jkey, &key_string)) { const char *key_chars = iotjs_string_data(&key_string); ret = mbedtls_pk_parse_key(&tls_context->pkey, (const unsigned char *)key_chars, (size_t)iotjs_string_size(&key_string) + 1, NULL, 0); iotjs_string_destroy(&key_string); if (ret == 0) { // Both own_cert and pkey must be valid for setting this flag. tls_context->context_flags |= SSL_CONTEXT_HAS_KEY; } } else { ret = -1; } } else if (!jerry_value_is_undefined(jcert) || !jerry_value_is_undefined(jkey)) { ret = -1; } jerry_release_value(jcert); jerry_release_value(jkey); if (ret != 0) { return JS_CREATE_ERROR(COMMON, "key or certificate parsing failed"); } // User provided trusted certificates jerry_value_t jcert_auth = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_CA); iotjs_string_t cert_auth_string; if (iotjs_jbuffer_as_string(jcert_auth, &cert_auth_string)) { const char *cert_auth_chars = iotjs_string_data(&cert_auth_string); ret = mbedtls_x509_crt_parse(&tls_context->cert_auth, (const unsigned char *)cert_auth_chars, (size_t)iotjs_string_size(&cert_auth_string) + 1); iotjs_string_destroy(&cert_auth_string); } else if (!jerry_value_is_undefined(jcert_auth)) { ret = -1; } else { // Parse the default certificate authority ret = mbedtls_x509_crt_parse(&tls_context->cert_auth, (const unsigned char *)SSL_CA_PEM, sizeof(SSL_CA_PEM)); } jerry_release_value(jcert_auth); if (ret) { return JS_CREATE_ERROR(COMMON, "certificate authority (CA) parsing failed"); } return jerry_create_undefined(); } JS_FUNCTION(tls_init) { DJS_CHECK_ARGS(3, object, object, object); jerry_value_t jtls_socket = JS_GET_ARG(0, object); jerry_value_t joptions = JS_GET_ARG(1, object); // Get context jerry_value_t jtls_context = JS_GET_ARG(2, object); iotjs_tls_context_t *tls_context = NULL; if (!jerry_get_object_native_pointer(jtls_context, (void **)&tls_context, &tls_context_native_info)) { return JS_CREATE_ERROR(COMMON, "secure context not available"); } iotjs_tls_t *tls_data = iotjs_tls_create(jtls_socket, tls_context); // Check server jerry_value_t jis_server = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_ISSERVER); bool is_server = jerry_value_to_boolean(jis_server); jerry_release_value(jis_server); if (tls_context->context_flags & SSL_CONTEXT_HAS_KEY) { if (mbedtls_ssl_conf_own_cert(&tls_data->conf, &tls_context->own_cert, &tls_context->pkey) != 0) { return JS_CREATE_ERROR(COMMON, "certificate/private key cannot be set"); } } mbedtls_ssl_conf_ca_chain(&tls_data->conf, &tls_context->cert_auth, NULL); mbedtls_ssl_conf_rng(&tls_data->conf, mbedtls_ctr_drbg_random, &tls_context->ctr_drbg); int endpoint = is_server ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT; if (mbedtls_ssl_config_defaults(&tls_data->conf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) { return JS_CREATE_ERROR(COMMON, "SSL Configuration failed"); } // if true, verifies CAs, must emit error if fails int auth_mode = is_server ? MBEDTLS_SSL_VERIFY_NONE : MBEDTLS_SSL_VERIFY_REQUIRED; jerry_value_t jauth_mode = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_REJECTUNAUTHORIZED); if (!jerry_value_is_undefined(jauth_mode)) { if (jerry_value_to_boolean(jauth_mode)) { auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED; } else { auth_mode = MBEDTLS_SSL_VERIFY_OPTIONAL; } } jerry_release_value(jauth_mode); mbedtls_ssl_conf_authmode(&tls_data->conf, auth_mode); if (mbedtls_ssl_setup(&tls_data->ssl, &tls_data->conf)) { return JS_CREATE_ERROR(COMMON, "SSL setup failed"); } // Connect mbedtls with iotjs_net_send and iotjs_net_recv functions iotjs_bio_init(&(tls_data->bio.receive_bio), SSL_BIO_SIZE); iotjs_bio_init(&(tls_data->bio.send_bio), SSL_BIO_SIZE); mbedtls_ssl_set_bio(&tls_data->ssl, &(tls_data->bio), iotjs_bio_net_send, iotjs_bio_net_receive, NULL); return jerry_create_undefined(); } JS_FUNCTION(tls_connect) { JS_DECLARE_THIS_PTR(tls, tls_data); DJS_CHECK_ARGS(1, string); if (tls_data->state == TLS_HANDSHAKE_READY) { iotjs_string_t server_name = JS_GET_ARG(0, string); mbedtls_ssl_set_hostname(&tls_data->ssl, iotjs_string_data(&server_name)); iotjs_string_destroy(&server_name); } return jerry_create_undefined(); } static void iotjs_tls_send_pending(iotjs_tls_t *tls_data) { iotjs_bio_t *send_bio = &(tls_data->bio.send_bio); size_t pending = iotjs_bio_pending(send_bio); if (pending == 0) { return; } jerry_value_t jbuffer = iotjs_bufferwrap_create_buffer(pending); iotjs_bufferwrap_t *buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuffer); iotjs_bio_read(send_bio, buffer_wrap->buffer, pending); jerry_value_t jthis = tls_data->jobject; jerry_value_t fn = iotjs_jval_get_property(jthis, IOTJS_MAGIC_STRING_ONWRITE); iotjs_invoke_callback(fn, jthis, &jbuffer, 1); jerry_release_value(fn); jerry_release_value(jbuffer); } static void iotjs_tls_notify_error(iotjs_tls_t *tls_data) { jerry_value_t jerror = jerry_create_string((const jerry_char_t *)"error"); jerry_value_t jmessage = jerry_create_string((const jerry_char_t *)"TLS error"); jerry_value_t jthis = tls_data->jobject; jerry_value_t fn = iotjs_jval_get_property(jthis, IOTJS_MAGIC_STRING_EMIT); jerry_value_t jargv[2] = { jerror, jmessage }; iotjs_invoke_callback(fn, jthis, jargv, 2); jerry_release_value(fn); jerry_release_value(jargv[0]); jerry_release_value(jargv[1]); } JS_FUNCTION(tls_write) { JS_DECLARE_THIS_PTR(tls, tls_data); if (tls_data->state != TLS_CONNECTED) { return jerry_create_null(); } const unsigned char *data = NULL; size_t length = 0; bool is_end = false; if (jargc >= 1 && jerry_value_to_boolean(jargv[0])) { jerry_value_t jbuffer = JS_GET_ARG(0, object); iotjs_bufferwrap_t *buf = iotjs_bufferwrap_from_jbuffer(jbuffer); data = (const unsigned char *)buf->buffer; length = iotjs_bufferwrap_length(buf); } if (jargc >= 2 && jerry_value_to_boolean(jargv[1])) { is_end = true; } while (true) { int ret_val = mbedtls_ssl_write(&tls_data->ssl, data, length); if ((int)length == ret_val) { break; } iotjs_tls_send_pending(tls_data); if (ret_val > 0) { data += ret_val; length -= (size_t)ret_val; } else if (ret_val != MBEDTLS_ERR_SSL_WANT_WRITE) { tls_data->state = TLS_CLOSED; return jerry_create_null(); } } if (is_end) { while (true) { int ret_val = mbedtls_ssl_close_notify(&tls_data->ssl); if (ret_val == 0) { tls_data->state = TLS_CLOSED; break; } iotjs_tls_send_pending(tls_data); if (ret_val != MBEDTLS_ERR_SSL_WANT_WRITE) { iotjs_tls_notify_error(tls_data); tls_data->state = TLS_CLOSED; return jerry_create_null(); } } } /* Last package is returned as a buffer. */ iotjs_bio_t *send_bio = &(tls_data->bio.send_bio); size_t pending = iotjs_bio_pending(send_bio); jerry_value_t jbuffer = iotjs_bufferwrap_create_buffer(pending); iotjs_bufferwrap_t *buf = iotjs_bufferwrap_from_jbuffer(jbuffer); iotjs_bio_read(send_bio, buf->buffer, pending); return jbuffer; } static void tls_handshake(iotjs_tls_t *tls_data, jerry_value_t jthis) { tls_data->state = TLS_HANDSHAKE_IN_PROGRESS; // Continue handshaking process int ret_val = mbedtls_ssl_handshake(&tls_data->ssl); iotjs_tls_send_pending(tls_data); bool error; bool authorized; // Check whether handshake completed if (ret_val == 0) { tls_data->state = TLS_CONNECTED; error = false; authorized = mbedtls_ssl_get_verify_result(&tls_data->ssl) == 0; } else { if (ret_val == MBEDTLS_ERR_SSL_WANT_READ || ret_val == MBEDTLS_ERR_SSL_WANT_WRITE) { return; } tls_data->state = TLS_CLOSED; error = true; authorized = false; } // Result of certificate verification jerry_value_t jargv[2] = { jerry_create_boolean(error), jerry_create_boolean(authorized) }; jerry_value_t fn = iotjs_jval_get_property(jthis, IOTJS_MAGIC_STRING_ONHANDSHAKEDONE); iotjs_invoke_callback(fn, jthis, jargv, 2); jerry_release_value(fn); jerry_release_value(jargv[0]); jerry_release_value(jargv[1]); } JS_FUNCTION(tls_read) { JS_DECLARE_THIS_PTR(tls, tls_data); if (tls_data->state == TLS_CLOSED) { return jerry_create_boolean(false); } iotjs_bio_t *receive_bio = &(tls_data->bio.receive_bio); const char *data = NULL; size_t length = 0; if (jargc >= 1 && jerry_value_to_boolean(jargv[0])) { jerry_value_t jbuffer = JS_GET_ARG(0, object); iotjs_bufferwrap_t *buf = iotjs_bufferwrap_from_jbuffer(jbuffer); data = buf->buffer; length = iotjs_bufferwrap_length(buf); } do { size_t copy_size = iotjs_bio_remaining(receive_bio); if (copy_size > length) { copy_size = length; } iotjs_bio_write(receive_bio, data, copy_size); data += copy_size; length -= copy_size; if (tls_data->state != TLS_CONNECTED) { IOTJS_ASSERT(tls_data->state == TLS_HANDSHAKE_READY || tls_data->state == TLS_HANDSHAKE_IN_PROGRESS); tls_handshake(tls_data, jthis); if (tls_data->state != TLS_CONNECTED) { IOTJS_ASSERT(tls_data->state == TLS_HANDSHAKE_IN_PROGRESS || tls_data->state == TLS_CLOSED); if (length > 0 && tls_data->state == TLS_HANDSHAKE_IN_PROGRESS) { continue; } bool result = (tls_data->state != TLS_CLOSED); return jerry_create_boolean(result); } } while (true) { int ret_val = mbedtls_ssl_read(&tls_data->ssl, NULL, 0); iotjs_tls_send_pending(tls_data); if (ret_val == 0) { size_t pending = mbedtls_ssl_get_bytes_avail(&tls_data->ssl); if (pending == 0) { continue; } jerry_value_t jbuffer = iotjs_bufferwrap_create_buffer(pending); iotjs_bufferwrap_t *buf = iotjs_bufferwrap_from_jbuffer(jbuffer); ret_val = mbedtls_ssl_read(&tls_data->ssl, (unsigned char *)buf->buffer, pending); IOTJS_ASSERT(ret_val == (int)pending); IOTJS_UNUSED(ret_val); jerry_value_t fn = iotjs_jval_get_property(jthis, IOTJS_MAGIC_STRING_ONREAD); iotjs_invoke_callback(fn, jthis, &jbuffer, 1); jerry_release_value(jbuffer); jerry_release_value(fn); continue; } if (ret_val == MBEDTLS_ERR_SSL_WANT_READ) { break; } if (ret_val == MBEDTLS_ERR_SSL_WANT_WRITE) { continue; } tls_data->state = TLS_CLOSED; if (ret_val == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { return jerry_create_boolean(true); } iotjs_tls_notify_error(tls_data); return jerry_create_boolean(false); } } while (length > 0); return jerry_create_boolean(true); } jerry_value_t iotjs_init_tls(void) { jerry_value_t jtls = jerry_create_object(); iotjs_jval_set_method(jtls, IOTJS_MAGIC_STRING_CONNECT, tls_connect); iotjs_jval_set_method(jtls, IOTJS_MAGIC_STRING_READ, tls_read); iotjs_jval_set_method(jtls, IOTJS_MAGIC_STRING_TLSCONTEXT, tls_tlscontext); iotjs_jval_set_method(jtls, IOTJS_MAGIC_STRING_TLSINIT, tls_init); iotjs_jval_set_method(jtls, IOTJS_MAGIC_STRING_WRITE, tls_write); return jtls; } iotjs-1.0+715/src/modules/iotjs_module_tls.h000066400000000000000000000065021371177304000210070ustar00rootroot00000000000000/* Copyright 2018-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_TLS_H #define IOTJS_MODULE_TLS_H #include "iotjs_def.h" #include "mbedtls/certs.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/entropy.h" #include "mbedtls/net.h" #include "mbedtls/net_sockets.h" #include "mbedtls/ssl.h" // Default certificate const char SSL_CA_PEM[] = "-----BEGIN CERTIFICATE-----\n" "MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4GA1UECxMX\n" "R2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMT\n" "Ckdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQL\n" "ExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UE\n" "AxMKR2xvYmFsU2lnbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8o\n" "mUVCxKs+IVSbC9N/hHD6ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7\n" "SqbKSaZeqKeMWhG8eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQ\n" "BoZfXklqtTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd\n" "C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feq\n" "CapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8E\n" "BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IHV2ccHsBqBt5ZtJot39wZhi4w\n" "NgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxzaWduLm5ldC9yb290LXIyLmNy\n" "bDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEA\n" "mYFThxxol4aR7OBKuEQLq4GsJ0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkI\n" "k7mpM0sYmsL4h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRD\n" "LenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd\n" "AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7TBj0/VLZ\n" "jmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==\n" "-----END CERTIFICATE-----\n"; // Handshake states for tls context enum { TLS_HANDSHAKE_READY = 0, TLS_HANDSHAKE_IN_PROGRESS = 1, TLS_CONNECTED = 2, TLS_CLOSED = 3 }; typedef struct { char *mem; size_t size; size_t read_index; size_t write_index; } iotjs_bio_t; typedef struct { iotjs_bio_t receive_bio; iotjs_bio_t send_bio; } iotjs_bio_pair_t; enum { SSL_BIO_SUCCESS = 0, SSL_BIO_ERROR = -1, SSL_BIO_UNSET = -2, SSL_BIO_SIZE = 4096 }; enum { SSL_CONTEXT_HAS_KEY = (1 << 0) }; typedef struct { int ref_count; uint32_t context_flags; mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; mbedtls_pk_context pkey; mbedtls_x509_crt own_cert; mbedtls_x509_crt cert_auth; } iotjs_tls_context_t; typedef struct { jerry_value_t jobject; int state; iotjs_tls_context_t *tls_context; mbedtls_ssl_config conf; mbedtls_ssl_context ssl; iotjs_bio_pair_t bio; } iotjs_tls_t; #endif /* IOTJS_MODULE_TLS_H */ iotjs-1.0+715/src/modules/iotjs_module_uart.c000066400000000000000000000212071371177304000211520ustar00rootroot00000000000000/* 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 #include "iotjs_def.h" #include "iotjs_module_buffer.h" #include "iotjs_module_uart.h" #include "iotjs_uv_handle.h" #include "iotjs_uv_request.h" static void iotjs_uart_object_destroy(uv_handle_t* handle); static const jerry_object_native_info_t this_module_native_info = { .free_cb = (jerry_object_native_free_callback_t)iotjs_uart_object_destroy, }; void iotjs_uart_object_destroy(uv_handle_t* handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(handle); iotjs_uart_destroy_platform_data(uart->platform_data); IOTJS_RELEASE(handle); } static void uart_worker(uv_work_t* work_req) { iotjs_periph_data_t* worker_data = (iotjs_periph_data_t*)IOTJS_UV_REQUEST_EXTRA_DATA(work_req); uv_handle_t* uart_poll_handle = (uv_handle_t*)worker_data->data; switch (worker_data->op) { case kUartOpOpen: worker_data->result = iotjs_uart_open(uart_poll_handle); break; case kUartOpWrite: worker_data->result = iotjs_uart_write(uart_poll_handle); break; case kUartOpClose: iotjs_uv_handle_close(uart_poll_handle, iotjs_uart_handle_close_cb); worker_data->result = true; break; default: IOTJS_ASSERT(!"Invalid Operation"); } } static void iotjs_uart_read_cb(uv_poll_t* req, int status, int events) { iotjs_uart_t* uart = (iotjs_uart_t*)req->data; char buf[UART_WRITE_BUFFER_SIZE]; int i = read(uart->device_fd, buf, UART_WRITE_BUFFER_SIZE - 1); if (i > 0) { buf[i] = '\0'; DDDLOG("%s - read length: %d", __func__, i); jerry_value_t juart = IOTJS_UV_HANDLE_DATA(req)->jobject; jerry_value_t jemit = iotjs_jval_get_property(juart, IOTJS_MAGIC_STRING_EMIT); IOTJS_ASSERT(jerry_value_is_function(jemit)); jerry_value_t str = jerry_create_string((const jerry_char_t*)IOTJS_MAGIC_STRING_DATA); jerry_value_t jbuf = iotjs_bufferwrap_create_buffer((size_t)i); iotjs_bufferwrap_t* buf_wrap = iotjs_bufferwrap_from_jbuffer(jbuf); iotjs_bufferwrap_copy(buf_wrap, buf, (size_t)i); jerry_value_t jargs[] = { str, jbuf }; jerry_value_t jres = jerry_call_function(jemit, IOTJS_UV_HANDLE_DATA(req)->jobject, jargs, 2); IOTJS_ASSERT(!jerry_value_is_error(jres)); jerry_release_value(jres); jerry_release_value(str); jerry_release_value(jbuf); jerry_release_value(jemit); } } void iotjs_uart_register_read_cb(uv_poll_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); uv_loop_t* loop = iotjs_environment_loop(iotjs_environment_get()); uv_poll_init(loop, uart_poll_handle, uart->device_fd); uv_poll_start(uart_poll_handle, UV_READABLE, iotjs_uart_read_cb); } static jerry_value_t uart_set_configuration(iotjs_uart_t* uart, jerry_value_t jconfig) { jerry_value_t jbaud_rate = iotjs_jval_get_property(jconfig, IOTJS_MAGIC_STRING_BAUDRATE); if (jerry_value_is_undefined(jbaud_rate)) { uart->baud_rate = 9600; } else { if (!jerry_value_is_number(jbaud_rate)) { jerry_release_value(jbaud_rate); return JS_CREATE_ERROR(TYPE, "Bad configuration - baud rate must be a Number"); } unsigned br = (unsigned)iotjs_jval_as_number(jbaud_rate); jerry_release_value(jbaud_rate); if (br != 230400 && br != 115200 && br != 57600 && br != 38400 && br != 19200 && br != 9600 && br != 4800 && br != 2400 && br != 1800 && br != 1200 && br != 600 && br != 300 && br != 200 && br != 150 && br != 134 && br != 110 && br != 75 && br != 50 && br != 0) { return JS_CREATE_ERROR(TYPE, "Invalid baud rate"); } uart->baud_rate = br; } jerry_value_t jdata_bits = iotjs_jval_get_property(jconfig, IOTJS_MAGIC_STRING_DATABITS); if (jerry_value_is_undefined(jdata_bits)) { uart->data_bits = 8; } else { if (!jerry_value_is_number(jdata_bits)) { jerry_release_value(jdata_bits); return JS_CREATE_ERROR(TYPE, "Bad configuration - data bits must be a Number"); } uint8_t db = (uint8_t)iotjs_jval_as_number(jdata_bits); jerry_release_value(jdata_bits); if (db > 8 || db < 5) { return JS_CREATE_ERROR(TYPE, "Invalid data bits"); } uart->data_bits = db; } return jerry_create_undefined(); } JS_FUNCTION(uart_constructor) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, object); DJS_CHECK_ARG_IF_EXIST(1, function); // Create UART object const jerry_value_t juart = JS_GET_THIS(); uv_handle_t* uart_poll_handle = iotjs_uv_handle_create(sizeof(uv_poll_t), juart, &this_module_native_info, sizeof(iotjs_uart_t)); iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); // TODO: merge platform data allocation into the handle allocation. iotjs_uart_create_platform_data(uart); uart->device_fd = -1; jerry_value_t jconfig = JS_GET_ARG(0, object); // set configuration jerry_value_t res = iotjs_uart_set_platform_config(uart, jconfig); if (jerry_value_is_error(res)) { jerry_release_value(juart); return res; } res = uart_set_configuration(uart, jconfig); if (jerry_value_is_error(res)) { jerry_release_value(juart); return res; } DDDLOG("%s - baudRate: %d, dataBits: %d", __func__, uart->baud_rate, uart->data_bits); jerry_value_t jcallback = JS_GET_ARG_IF_EXIST(1, function); // If the callback doesn't exist, it is completed synchronously. // Otherwise, it will be executed asynchronously. if (!jerry_value_is_null(jcallback)) { iotjs_periph_call_async(uart_poll_handle, jcallback, kUartOpOpen, uart_worker); } else if (!iotjs_uart_open(uart_poll_handle)) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kUartOpOpen)); } return jerry_create_undefined(); } JS_FUNCTION(uart_write) { JS_DECLARE_PTR(jthis, uv_poll_t, uart_poll_handle); DJS_CHECK_ARGS(1, string); DJS_CHECK_ARG_IF_EXIST(1, function); iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); uart->buf_data = JS_GET_ARG(0, string); uart->buf_len = iotjs_string_size(&uart->buf_data); iotjs_periph_call_async(uart_poll_handle, JS_GET_ARG_IF_EXIST(1, function), kUartOpWrite, uart_worker); return jerry_create_undefined(); } JS_FUNCTION(uart_write_sync) { JS_DECLARE_PTR(jthis, uv_handle_t, uart_poll_handle); DJS_CHECK_ARGS(1, string); iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); uart->buf_data = JS_GET_ARG(0, string); uart->buf_len = iotjs_string_size(&uart->buf_data); bool result = iotjs_uart_write(uart_poll_handle); iotjs_string_destroy(&uart->buf_data); if (!result) { return JS_CREATE_ERROR(COMMON, iotjs_periph_error_str(kUartOpWrite)); } return jerry_create_undefined(); } JS_FUNCTION(uart_close) { JS_DECLARE_PTR(jthis, uv_poll_t, uart_poll_handle); DJS_CHECK_ARG_IF_EXIST(0, function); iotjs_periph_call_async(uart_poll_handle, JS_GET_ARG_IF_EXIST(0, function), kUartOpClose, uart_worker); return jerry_create_undefined(); } JS_FUNCTION(uart_close_sync) { JS_DECLARE_PTR(jthis, uv_handle_t, uart_poll_handle); iotjs_uv_handle_close(uart_poll_handle, iotjs_uart_handle_close_cb); return jerry_create_undefined(); } jerry_value_t iotjs_init_uart(void) { jerry_value_t juart_cons = jerry_create_external_function(uart_constructor); jerry_value_t prototype = jerry_create_object(); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_WRITE, uart_write); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_WRITESYNC, uart_write_sync); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_CLOSE, uart_close); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_CLOSESYNC, uart_close_sync); iotjs_jval_set_property_jval(juart_cons, IOTJS_MAGIC_STRING_PROTOTYPE, prototype); jerry_release_value(prototype); return juart_cons; } iotjs-1.0+715/src/modules/iotjs_module_uart.h000066400000000000000000000030661371177304000211620ustar00rootroot00000000000000/* 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_UART_H #define IOTJS_MODULE_UART_H #include "iotjs_def.h" #include "iotjs_module_periph_common.h" #define UART_WRITE_BUFFER_SIZE 512 typedef struct iotjs_uart_platform_data_s iotjs_uart_platform_data_t; typedef struct { int device_fd; unsigned baud_rate; uint8_t data_bits; iotjs_string_t buf_data; unsigned buf_len; iotjs_uart_platform_data_t* platform_data; } iotjs_uart_t; void iotjs_uart_handle_close_cb(uv_handle_t* handle); void iotjs_uart_register_read_cb(uv_poll_t* uart_poll_handle); void iotjs_uart_create_platform_data(iotjs_uart_t* uart); jerry_value_t iotjs_uart_set_platform_config(iotjs_uart_t* uart, const jerry_value_t jconfig); void iotjs_uart_destroy_platform_data(iotjs_uart_platform_data_t* pdata); bool iotjs_uart_open(uv_handle_t* uart_poll_handle); bool iotjs_uart_write(uv_handle_t* uart_poll_handle); #endif /* IOTJS_MODULE_UART_H */ iotjs-1.0+715/src/modules/iotjs_module_udp.c000066400000000000000000000251001371177304000207630ustar00rootroot00000000000000/* 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_buffer.h" #include "iotjs_module_tcp.h" #include "iotjs_uv_handle.h" #include "iotjs_uv_request.h" static const jerry_object_native_info_t this_module_native_info = { NULL }; void iotjs_udp_object_init(jerry_value_t judp) { uv_handle_t* handle = iotjs_uv_handle_create(sizeof(uv_udp_t), judp, &this_module_native_info, 0); const iotjs_environment_t* env = iotjs_environment_get(); uv_udp_init(iotjs_environment_loop(env), (uv_udp_t*)handle); } JS_FUNCTION(udp_constructor) { DJS_CHECK_THIS(); jerry_value_t judp = JS_GET_THIS(); iotjs_udp_object_init(judp); return jerry_create_undefined(); } JS_FUNCTION(udp_bind) { JS_DECLARE_PTR(jthis, uv_udp_t, udp_handle); DJS_CHECK_ARGS(2, string, number); iotjs_string_t address = JS_GET_ARG(0, string); const int port = JS_GET_ARG(1, number); jerry_value_t this_obj = JS_GET_THIS(); jerry_value_t reuse_addr = iotjs_jval_get_property(this_obj, IOTJS_MAGIC_STRING__REUSEADDR); IOTJS_ASSERT(jerry_value_is_boolean(reuse_addr) || jerry_value_is_undefined(reuse_addr)); unsigned int flags = 0; if (!jerry_value_is_undefined(reuse_addr)) { flags = iotjs_jval_as_boolean(reuse_addr) ? UV_UDP_REUSEADDR : 0; } char addr[sizeof(sockaddr_in6)]; int err = uv_ip4_addr(iotjs_string_data(&address), port, (sockaddr_in*)(&addr)); if (err == 0) { err = uv_udp_bind(udp_handle, (const sockaddr*)(&addr), flags); } jerry_release_value(reuse_addr); iotjs_string_destroy(&address); return jerry_create_number(err); } static void on_alloc(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { if (suggested_size > IOTJS_MAX_READ_BUFFER_SIZE) { suggested_size = IOTJS_MAX_READ_BUFFER_SIZE; } buf->base = iotjs_buffer_allocate(suggested_size); buf->len = suggested_size; } static void on_recv(uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags) { if (nread == 0 && addr == NULL) { iotjs_buffer_release(buf->base); return; } // udp handle jerry_value_t judp = IOTJS_UV_HANDLE_DATA(handle)->jobject; IOTJS_ASSERT(jerry_value_is_object(judp)); // onmessage callback jerry_value_t jonmessage = iotjs_jval_get_property(judp, IOTJS_MAGIC_STRING_ONMESSAGE); IOTJS_ASSERT(jerry_value_is_function(jonmessage)); jerry_value_t jargs[4] = { jerry_create_number(nread), jerry_acquire_value(judp), jerry_create_null(), jerry_create_object() }; if (nread < 0) { iotjs_buffer_release(buf->base); iotjs_invoke_callback(jonmessage, jerry_create_undefined(), jargs, 2); jerry_release_value(jonmessage); for (int i = 0; i < 4; i++) { jerry_release_value(jargs[i]); } return; } jargs[2] = iotjs_bufferwrap_create_buffer((size_t)nread); iotjs_bufferwrap_t* buffer_wrap = iotjs_bufferwrap_from_jbuffer(jargs[2]); iotjs_bufferwrap_copy(buffer_wrap, buf->base, (size_t)nread); address_to_js(jargs[3], addr); iotjs_invoke_callback(jonmessage, jerry_create_undefined(), jargs, 4); jerry_release_value(jonmessage); iotjs_buffer_release(buf->base); for (int i = 0; i < 4; i++) { jerry_release_value(jargs[i]); } } JS_FUNCTION(udp_recv_start) { JS_DECLARE_PTR(jthis, uv_udp_t, udp_handle); int err = uv_udp_recv_start(udp_handle, on_alloc, on_recv); // UV_EALREADY means that the socket is already bound but that's okay if (err == UV_EALREADY) err = 0; return jerry_create_number(err); } JS_FUNCTION(udp_recv_stop) { JS_DECLARE_PTR(jthis, uv_udp_t, udp_handle); int r = uv_udp_recv_stop(udp_handle); return jerry_create_number(r); } static void on_send(uv_udp_send_t* req, int status) { IOTJS_ASSERT(req != NULL); // Take callback function object. jerry_value_t jcallback = *IOTJS_UV_REQUEST_JSCALLBACK(req); if (jerry_value_is_function(jcallback)) { size_t msg_size = *((size_t*)IOTJS_UV_REQUEST_EXTRA_DATA(req)); jerry_value_t jargs[2] = { jerry_create_number(status), jerry_create_number(msg_size) }; iotjs_invoke_callback(jcallback, jerry_create_undefined(), jargs, 2); jerry_release_value(jargs[0]); jerry_release_value(jargs[1]); } iotjs_uv_request_destroy((uv_req_t*)req); } // Send messages using the socket. // [0] buffer // [1] port // [2] ip // [3] callback function JS_FUNCTION(udp_send) { JS_DECLARE_PTR(jthis, uv_udp_t, udp_handle); DJS_CHECK_ARGS(3, object, number, string); if (!jerry_value_is_undefined(jargv[3]) && !jerry_value_is_function(jargv[3])) { return JS_CREATE_ERROR(TYPE, "Invalid callback given"); } const jerry_value_t jbuffer = JS_GET_ARG(0, object); const unsigned short port = JS_GET_ARG(1, number); iotjs_string_t address = JS_GET_ARG(2, string); jerry_value_t jcallback = JS_GET_ARG(3, object); iotjs_bufferwrap_t* buffer_wrap = iotjs_jbuffer_get_bufferwrap_ptr(jbuffer); if (buffer_wrap == NULL) { return JS_CREATE_ERROR(TYPE, "Invalid buffer given"); } size_t len = iotjs_bufferwrap_length(buffer_wrap); uv_req_t* req_send = iotjs_uv_request_create(sizeof(uv_udp_send_t), jcallback, sizeof(len)); *((size_t*)IOTJS_UV_REQUEST_EXTRA_DATA(req_send)) = len; uv_buf_t buf; buf.base = buffer_wrap->buffer; buf.len = len; char addr[sizeof(sockaddr_in6)]; int err = uv_ip4_addr(iotjs_string_data(&address), port, (sockaddr_in*)(&addr)); if (err == 0) { err = uv_udp_send((uv_udp_send_t*)req_send, udp_handle, &buf, 1, (const sockaddr*)(&addr), on_send); } if (err) { iotjs_uv_request_destroy(req_send); } iotjs_string_destroy(&address); return jerry_create_number(err); } // Close socket JS_FUNCTION(udp_close) { JS_DECLARE_PTR(jthis, uv_handle_t, uv_handle); iotjs_uv_handle_close(uv_handle, NULL); return jerry_create_undefined(); } JS_FUNCTION(udp_get_socket_name) { JS_DECLARE_PTR(jthis, uv_udp_t, udp_handle); DJS_CHECK_ARGS(1, object); sockaddr_storage storage; int addrlen = sizeof(storage); sockaddr* const addr = (sockaddr*)(&storage); int err = uv_udp_getsockname(udp_handle, addr, &addrlen); if (err == 0) address_to_js(JS_GET_ARG(0, object), addr); return jerry_create_number(err); } // The order of these config types must match the order // in the dgram js module. enum config_type { BROADCAST, TTL, MULTICASTTTL, MULTICASTLOOPBACK }; JS_FUNCTION(udp_configure) { JS_DECLARE_PTR(jthis, uv_udp_t, udp_handle); DJS_CHECK_ARGS(2, number, number); jerry_value_t ret_value = jerry_create_null(); #if !defined(__NUTTX__) enum config_type type = JS_GET_ARG(0, number); int flag = JS_GET_ARG(1, number); int (*fn)(uv_udp_t*, int) = NULL; switch (type) { case BROADCAST: { fn = &uv_udp_set_broadcast; break; } case TTL: { fn = &uv_udp_set_ttl; break; } case MULTICASTTTL: { fn = &uv_udp_set_multicast_ttl; break; } case MULTICASTLOOPBACK: { fn = &uv_udp_set_multicast_loop; break; } default: { IOTJS_ASSERT(!"Unknown config type"); return jerry_create_null(); } } ret_value = jerry_create_number(fn(udp_handle, flag)); #else IOTJS_ASSERT(!"Not implemented"); #endif return ret_value; } static jerry_value_t set_membership(const jerry_value_t jthis, const jerry_value_t* jargv, const jerry_length_t jargc, uv_membership membership) { #if !defined(__NUTTX__) JS_DECLARE_PTR(jthis, uv_udp_t, udp_handle); DJS_CHECK_ARGS(1, string); iotjs_string_t address = JS_GET_ARG(0, string); bool is_undefined_or_null = jerry_value_is_undefined(jargv[1]) || jerry_value_is_null(jargv[1]); iotjs_string_t iface; const char* iface_cstr; if (is_undefined_or_null) { iface_cstr = NULL; } else { iface = iotjs_jval_as_string(jargv[1]); iface_cstr = iotjs_string_data(&iface); } int err = uv_udp_set_membership(udp_handle, iotjs_string_data(&address), iface_cstr, membership); if (!is_undefined_or_null) iotjs_string_destroy(&iface); iotjs_string_destroy(&address); return jerry_create_number(err); #else IOTJS_ASSERT(!"Not implemented"); return jerry_create_null(); #endif } JS_FUNCTION(udp_add_membership) { return set_membership(jthis, jargv, jargc, UV_JOIN_GROUP); } JS_FUNCTION(udp_drop_membership) { return set_membership(jthis, jargv, jargc, UV_LEAVE_GROUP); } JS_FUNCTION(udp_ref) { IOTJS_ASSERT(!"Not implemented"); return jerry_create_null(); } JS_FUNCTION(udp_unref) { IOTJS_ASSERT(!"Not implemented"); return jerry_create_null(); } jerry_value_t iotjs_init_udp(void) { jerry_value_t udp = jerry_create_external_function(udp_constructor); jerry_value_t prototype = jerry_create_object(); iotjs_jval_set_property_jval(udp, IOTJS_MAGIC_STRING_PROTOTYPE, prototype); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_BIND, udp_bind); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_RECVSTART, udp_recv_start); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_RECVSTOP, udp_recv_stop); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_SEND, udp_send); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_CLOSE, udp_close); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_GETSOCKNAME, udp_get_socket_name); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_CONFIGURE, udp_configure); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_ADDMEMBERSHIP, udp_add_membership); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_DROPMEMBERSHIP, udp_drop_membership); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_REF, udp_ref); iotjs_jval_set_method(prototype, IOTJS_MAGIC_STRING_UNREF, udp_unref); jerry_release_value(prototype); return udp; } iotjs-1.0+715/src/modules/iotjs_module_websocket.c000066400000000000000000000616531371177304000221760ustar00rootroot00000000000000/* Copyright 2018-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 #include #include "iotjs_def.h" #include "iotjs_module_buffer.h" #include "iotjs_module_crypto.h" #include "iotjs_module_websocket.h" IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(wsclient); static void iotjs_wsclient_destroy(iotjs_wsclient_t *wsclient) { IOTJS_RELEASE(wsclient->tcp_buff.buffer); IOTJS_RELEASE(wsclient->ws_buff.data); IOTJS_RELEASE(wsclient->generated_key); IOTJS_RELEASE(wsclient); } iotjs_wsclient_t *iotjs_wsclient_create(const jerry_value_t jobject) { iotjs_wsclient_t *wsclient = IOTJS_ALLOC(iotjs_wsclient_t); jerry_set_object_native_pointer(jobject, wsclient, &this_module_native_info); return wsclient; } static const char WS_GUID[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; /** * The protocol is as follows: * method + USER_ENDPOINT + protocol * host + USER_HOST + line_end * upgrade * connection * sec_websocket_key + line_end * sec_websocket_ver */ static const char method[] = "GET "; static const char protocol[] = " HTTP/1.1\r\n"; static const char host[] = "Host: "; static const char line_end[] = "\r\n"; static const char upgrade[] = "Upgrade: websocket\r\n"; static const char connection[] = "Connection: Upgrade\r\n"; static const char sec_websocket_key[] = "Sec-WebSocket-Key: "; static const char sec_websocket_ver[] = "Sec-WebSocket-Version: 13\r\n\r\n"; static const char handshake_response[] = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: " "Upgrade\r\nSec-WebSocket-Accept: "; static size_t header_fixed_size = sizeof(method) + sizeof(protocol) + sizeof(host) + sizeof(upgrade) + sizeof(connection) + sizeof(sec_websocket_key) + sizeof(sec_websocket_ver) - 9; // 9 is for every \0 void iotjs_websocket_create_callback(jerry_value_t jsref, jerry_value_t jmsg, char *name, jerry_value_t client) { jerry_value_t args[2]; args[0] = jmsg; args[1] = client; jerry_value_t fn = iotjs_jval_get_property(jsref, name); iotjs_invoke_callback(fn, jsref, args, 2); jerry_release_value(fn); } static unsigned char *ws_generate_key(jerry_value_t jsref, size_t *key_len) { unsigned char *key = IOTJS_CALLOC(16, unsigned char); for (int i = 0; i < 16; i++) { key[i] = rand() % 256; } unsigned char *ret_val = NULL; if (!(*key_len = iotjs_base64_encode(&ret_val, key, 16))) { jerry_value_t ret_str = jerry_create_string((jerry_char_t *)"mbedtls base64 encode failed"); iotjs_websocket_create_callback(jsref, ret_str, IOTJS_MAGIC_STRING_ONERROR, ret_str); jerry_release_value(ret_str); } IOTJS_RELEASE(key); return ret_val; } static char *iotjs_ws_write_header(char *dst, const char *src) { memcpy(dst, src, strlen(src)); return dst + strlen(src); } static char *iotjs_ws_write_data(char *buff, void *data, size_t size) { memcpy(buff, data, size); return buff + size; } static unsigned char *iotjs_make_handshake_key(char *client_key, size_t *key_len) { unsigned char *out_buff = NULL; size_t ws_guid_size = strlen(WS_GUID); size_t client_key_size = strnlen((char *)client_key, 24); size_t concatenated_size = ws_guid_size + client_key_size; unsigned char concatenated[concatenated_size + 1]; memcpy(concatenated, client_key, client_key_size); memcpy(concatenated + client_key_size, WS_GUID, ws_guid_size); concatenated[concatenated_size] = '\0'; size_t out_buff_size = iotjs_sha1_encode(&out_buff, concatenated, concatenated_size); unsigned char *key_out = NULL; if (!(*key_len = iotjs_base64_encode(&key_out, out_buff, out_buff_size))) { key_out = NULL; } IOTJS_RELEASE(out_buff); return key_out; } static bool iotjs_check_handshake_key(char *server_key, jerry_value_t jsref) { bool ret_val = true; void *native_p; if (!jerry_get_object_native_pointer(jsref, &native_p, &this_module_native_info)) { ret_val = false; } iotjs_wsclient_t *wsclient = (iotjs_wsclient_t *)native_p; size_t key_len = 0; unsigned char *key; if (!(key = iotjs_make_handshake_key((char *)wsclient->generated_key, &key_len))) { ret_val = false; } if (key && strncmp(server_key, (const char *)key, key_len)) { ret_val = false; } IOTJS_RELEASE(wsclient->generated_key); IOTJS_RELEASE(key); return ret_val; } static jerry_value_t iotjs_websocket_encode_frame(uint8_t opcode, bool mask, bool compress, char *payload, size_t payload_len) { uint8_t header[2] = { 0 }; uint64_t buffer_size = payload_len + sizeof(header); header[0] |= WS_FIN_BIT; header[0] |= opcode; if (compress) { header[0] |= 0x40; } if (mask) { header[1] |= WS_MASK_BIT; buffer_size += 4; // mask key size is 32 bits } uint8_t extended_len_size = 0; if (payload_len <= WS_ONE_BYTE_LENGTH) { header[1] |= payload_len; } else if (payload_len <= UINT16_MAX) { header[1] |= WS_TWO_BYTES_LENGTH; extended_len_size = 2; } else { header[1] |= WS_THREE_BYTES_LENGTH; extended_len_size = 8; } buffer_size += extended_len_size; jerry_value_t jframe = iotjs_bufferwrap_create_buffer(buffer_size); iotjs_bufferwrap_t *frame_wrap = iotjs_bufferwrap_from_jbuffer(jframe); char *buff_ptr = frame_wrap->buffer; *buff_ptr++ = (char)header[0]; *buff_ptr++ = (char)header[1]; if (extended_len_size) { if (extended_len_size == 2) { uint16_t len = payload_len; *buff_ptr++ = *((char *)&len + 1); *buff_ptr++ = *((char *)&len); } else { uint64_t len = payload_len; for (int8_t i = sizeof(uint64_t) - 1; i >= 0; i--) { *buff_ptr++ = *((char *)&len + i); } } } if (payload != NULL) { if (mask) { uint8_t key[4]; for (uint8_t i = 0; i < sizeof(key); i++) { key[i] = rand() % 256; } buff_ptr = iotjs_ws_write_data(buff_ptr, key, sizeof(key)); for (size_t i = 0; i < payload_len; i++) { payload[i] ^= key[i % 4]; } } buff_ptr = iotjs_ws_write_data(buff_ptr, payload, payload_len); } return jframe; } static void iotjs_websocket_create_buffer_and_cb(char **buff_ptr, uint32_t payload_len, char *cb_type, jerry_value_t jsref, jerry_value_t client) { if (payload_len > 0) { jerry_value_t ret_buff = iotjs_bufferwrap_create_buffer(payload_len); iotjs_bufferwrap_t *buff_wrap = iotjs_bufferwrap_from_jbuffer(ret_buff); iotjs_ws_write_data(buff_wrap->buffer, *buff_ptr, payload_len); *buff_ptr += payload_len; iotjs_websocket_create_callback(jsref, ret_buff, cb_type, client); jerry_release_value(ret_buff); return; } iotjs_websocket_create_callback(jsref, jerry_create_undefined(), cb_type, client); } static jerry_value_t iotjs_websocket_check_error(uint8_t code) { switch (code) { case WS_ERR_INVALID_UTF8: { return JS_CREATE_ERROR(COMMON, "Invalid UTF8 string in UTF8 message"); } case WS_ERR_INVALID_TERMINATE_CODE: { return JS_CREATE_ERROR(COMMON, "Invalid terminate code received"); } case WS_ERR_UNKNOWN_OPCODE: { return JS_CREATE_ERROR(COMMON, "Uknown opcode received"); } case WS_ERR_NATIVE_POINTER_ERR: { return JS_CREATE_ERROR(COMMON, "WebSocket native pointer unavailable"); } case WS_ERR_FRAME_SIZE_LIMIT: { return JS_CREATE_ERROR(COMMON, "Frame size received exceeds limit"); } default: { return jerry_create_undefined(); }; } } JS_FUNCTION(prepare_handshake_request) { DJS_CHECK_THIS(); jerry_value_t jsref = JS_GET_ARG(0, object); jerry_value_t jhost = JS_GET_ARG(1, any); jerry_value_t jendpoint = JS_GET_ARG(2, any); iotjs_string_t l_host; iotjs_string_t l_endpoint; if (!(iotjs_jbuffer_as_string(jendpoint, &l_endpoint)) || !(iotjs_jbuffer_as_string(jhost, &l_host))) { return JS_CREATE_ERROR(COMMON, "Invalid host and/or path arguments!"); }; iotjs_wsclient_t *wsclient = NULL; if (!jerry_get_object_native_pointer(jsref, (void **)&wsclient, &this_module_native_info)) { return iotjs_websocket_check_error(WS_ERR_NATIVE_POINTER_ERR); } size_t generated_key_len = 0; wsclient->generated_key = ws_generate_key(jsref, &generated_key_len); jerry_value_t jfinal = iotjs_bufferwrap_create_buffer( header_fixed_size + iotjs_string_size(&l_endpoint) + iotjs_string_size(&l_host) + (sizeof(line_end) * 2) + generated_key_len); iotjs_bufferwrap_t *final_wrap = iotjs_bufferwrap_from_jbuffer(jfinal); char *buff_ptr = final_wrap->buffer; buff_ptr = iotjs_ws_write_header(buff_ptr, method); memcpy(buff_ptr, iotjs_string_data(&l_endpoint), iotjs_string_size(&l_endpoint)); buff_ptr += iotjs_string_size(&l_endpoint); buff_ptr = iotjs_ws_write_header(buff_ptr, protocol); buff_ptr = iotjs_ws_write_header(buff_ptr, host); memcpy(buff_ptr, iotjs_string_data(&l_host), iotjs_string_size(&l_host)); buff_ptr += iotjs_string_size(&l_host); buff_ptr = iotjs_ws_write_header(buff_ptr, line_end); buff_ptr = iotjs_ws_write_header(buff_ptr, upgrade); buff_ptr = iotjs_ws_write_header(buff_ptr, connection); buff_ptr = iotjs_ws_write_header(buff_ptr, sec_websocket_key); memcpy(buff_ptr, wsclient->generated_key, generated_key_len); buff_ptr += generated_key_len; buff_ptr = iotjs_ws_write_header(buff_ptr, line_end); buff_ptr = iotjs_ws_write_header(buff_ptr, sec_websocket_ver); iotjs_string_destroy(&l_endpoint); iotjs_string_destroy(&l_host); return jfinal; } /** * HTTP/1.1 101 Switching Protocols * Upgrade: websocket * Connection: Upgrade * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= */ JS_FUNCTION(receive_handshake_data) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(1, string); iotjs_string_t client_key = JS_GET_ARG(0, string); size_t key_len = 0; unsigned char *key; if (!(key = iotjs_make_handshake_key((char *)iotjs_string_data(&client_key), &key_len))) { return JS_CREATE_ERROR(COMMON, "mbedtls base64 encode failed"); } jerry_value_t jfinal = iotjs_bufferwrap_create_buffer( sizeof(handshake_response) - 1 + key_len + sizeof(line_end) * 2); iotjs_bufferwrap_t *final_wrap = iotjs_bufferwrap_from_jbuffer(jfinal); char *buff_ptr = final_wrap->buffer; buff_ptr = iotjs_ws_write_header(buff_ptr, handshake_response); memcpy(buff_ptr, key, key_len); buff_ptr += key_len; buff_ptr = iotjs_ws_write_header(buff_ptr, line_end); buff_ptr = iotjs_ws_write_header(buff_ptr, line_end); iotjs_string_destroy(&client_key); IOTJS_RELEASE(key); return jfinal; } JS_FUNCTION(parse_handshake_data) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(2, object, object); jerry_value_t jbuffer = JS_GET_ARG(0, object); iotjs_bufferwrap_t *buff_wrap = iotjs_bufferwrap_from_jbuffer(jbuffer); if (buff_wrap->length < 12 || strncmp(buff_wrap->buffer + 9, "101", 3)) { return JS_CREATE_ERROR(COMMON, "WebSocket connection failed"); } jerry_value_t jsref = JS_GET_ARG(1, object); char ws_accept[] = "Sec-WebSocket-Accept: "; char *frame_end = strstr(buff_wrap->buffer, "\r\n\r\n"); char *key_pos = strstr(buff_wrap->buffer, ws_accept) + strlen(ws_accept); char key[28] = { 0 }; memcpy(key, key_pos, 28); frame_end += 4; // \r\n\r\n if (!iotjs_check_handshake_key(key, jsref)) { return JS_CREATE_ERROR(COMMON, "WebSocket handshake key comparison failed"); } size_t header_size = (size_t)(frame_end - buff_wrap->buffer); if (buff_wrap->length > header_size) { size_t remaining_length = buff_wrap->length - header_size; jerry_value_t jdata = iotjs_bufferwrap_create_buffer(remaining_length); iotjs_bufferwrap_t *data_wrap = iotjs_bufferwrap_from_jbuffer(jdata); memcpy(data_wrap->buffer, buff_wrap->buffer + header_size, remaining_length); data_wrap->length = remaining_length; return jdata; } return jerry_create_undefined(); } static void iotjs_websocket_concat_tcp_buffers(iotjs_wsclient_t *wsclient, iotjs_bufferwrap_t *buff_recv) { char *tmp_buf = wsclient->tcp_buff.buffer; wsclient->tcp_buff.buffer = IOTJS_CALLOC(wsclient->tcp_buff.length + buff_recv->length, char); memcpy(wsclient->tcp_buff.buffer, tmp_buf, wsclient->tcp_buff.length); memcpy(wsclient->tcp_buff.buffer + wsclient->tcp_buff.length, buff_recv->buffer, buff_recv->length); wsclient->tcp_buff.length += buff_recv->length; IOTJS_RELEASE(tmp_buf); } static uint8_t iotjs_websocket_decode_frame(iotjs_wsclient_t *wsclient, char *first_byte, char *buff_ptr, uint32_t payload_len, jerry_value_t jsref, bool mask, jerry_value_t client) { uint8_t fin_bit = (first_byte[0] >> 7) & 0x01; uint8_t opcode = first_byte[0] & 0x0F; uint32_t *mask_key = NULL; if (mask) { mask_key = (uint32_t *)buff_ptr; buff_ptr += sizeof(uint32_t); for (uint64_t i = 0; i < payload_len; i++) { buff_ptr[i] ^= ((unsigned char *)(mask_key))[i % 4]; } } switch (opcode) { case WS_OP_CONTINUE: { if (wsclient->ws_buff.length == 0) { wsclient->ws_buff.masked = mask; wsclient->ws_buff.first_byte = first_byte[0]; wsclient->ws_buff.data = IOTJS_CALLOC(payload_len, char); memcpy(wsclient->ws_buff.data, buff_ptr, payload_len); wsclient->ws_buff.length = payload_len; break; } char *tmp_ptr = wsclient->ws_buff.data; uint32_t tmp_len = wsclient->ws_buff.length; wsclient->ws_buff.data = IOTJS_CALLOC(wsclient->ws_buff.length + payload_len, char); memcpy(wsclient->ws_buff.data, tmp_ptr, tmp_len); memcpy(wsclient->ws_buff.data + tmp_len, buff_ptr, payload_len); wsclient->ws_buff.length += payload_len; IOTJS_RELEASE(tmp_ptr); if (fin_bit) { uint8_t ret_val = iotjs_websocket_decode_frame(wsclient, &wsclient->ws_buff.first_byte, wsclient->ws_buff.data, wsclient->ws_buff.length, jsref, wsclient->ws_buff.masked, client); IOTJS_RELEASE(wsclient->ws_buff.data); wsclient->ws_buff.length = 0; wsclient->ws_buff.first_byte = 0; return ret_val; } break; } case WS_OP_UTF8: case WS_OP_BINARY: { if (opcode == WS_OP_UTF8 && !jerry_is_valid_utf8_string((unsigned char *)buff_ptr, payload_len)) { return WS_ERR_INVALID_UTF8; } iotjs_websocket_create_buffer_and_cb(&buff_ptr, payload_len, IOTJS_MAGIC_STRING_ONMESSAGE, jsref, client); break; } case WS_OP_TERMINATE: { if (payload_len > 0) { uint16_t ret_code = (uint16_t)((unsigned char)buff_ptr[0] << 8 | (unsigned char)buff_ptr[1]); if (ret_code > 4999 || ret_code < 1000) { return WS_ERR_INVALID_TERMINATE_CODE; } buff_ptr += 2; payload_len -= 2; size_t ret_code_str_size = 4; char ret_code_str[ret_code_str_size + 1]; snprintf(ret_code_str, ret_code_str_size + 1, "%d", ret_code); jerry_value_t ret_buff = iotjs_bufferwrap_create_buffer(payload_len + ret_code_str_size); iotjs_bufferwrap_t *ret_wrap = iotjs_bufferwrap_from_jbuffer(ret_buff); char *local_ptr = ret_wrap->buffer; local_ptr = iotjs_ws_write_data(local_ptr, ret_code_str, ret_code_str_size); local_ptr = iotjs_ws_write_data(local_ptr, buff_ptr, payload_len); buff_ptr += payload_len; iotjs_websocket_create_callback(jsref, ret_buff, IOTJS_MAGIC_STRING_ONCLOSE, client); jerry_release_value(ret_buff); break; } iotjs_websocket_create_callback(jsref, jerry_create_undefined(), IOTJS_MAGIC_STRING_ONCLOSE, client); break; } case WS_OP_PING: { iotjs_websocket_create_buffer_and_cb(&buff_ptr, payload_len, IOTJS_MAGIC_STRING_PONG, jsref, client); break; } case WS_OP_PONG: { iotjs_websocket_create_buffer_and_cb(&buff_ptr, payload_len, IOTJS_MAGIC_STRING_ONPINGRESP, jsref, client); break; } default: return WS_ERR_UNKNOWN_OPCODE; break; } return 0; } JS_FUNCTION(ws_receive) { DJS_CHECK_THIS(); DJS_CHECK_ARGS(3, object, object, object); jerry_value_t jsref = JS_GET_ARG(0, object); iotjs_wsclient_t *wsclient = NULL; if (!jerry_get_object_native_pointer(jsref, (void **)&wsclient, &this_module_native_info)) { return iotjs_websocket_check_error(WS_ERR_NATIVE_POINTER_ERR); } jerry_value_t jbuffer = JS_GET_ARG(1, object); iotjs_bufferwrap_t *buffer_wrap = iotjs_bufferwrap_from_jbuffer(jbuffer); jerry_value_t client = JS_GET_ARG(2, object); if (buffer_wrap->length == 0) { return jerry_create_undefined(); } char *current_buffer = buffer_wrap->buffer; char *current_buffer_end = current_buffer + buffer_wrap->length; if (wsclient->tcp_buff.length > 0) { iotjs_websocket_concat_tcp_buffers(wsclient, buffer_wrap); current_buffer = wsclient->tcp_buff.buffer; current_buffer_end = current_buffer + wsclient->tcp_buff.length; } while (true) { if (current_buffer >= current_buffer_end) { if (wsclient->tcp_buff.length > 0) { IOTJS_RELEASE(wsclient->tcp_buff.buffer); wsclient->tcp_buff.length = 0; } return jerry_create_undefined(); } if (current_buffer + 2 > current_buffer_end) { break; } char *first_byte = current_buffer; uint8_t payload_byte = (current_buffer[1]) & WS_THREE_BYTES_LENGTH; uint8_t mask = (first_byte[1] >> 7) & 0x01; current_buffer += 2; uint32_t payload_len; if (!(payload_byte ^ WS_TWO_BYTES_LENGTH)) { if (current_buffer + sizeof(uint16_t) > current_buffer_end) { break; } unsigned char *len_buffer = (unsigned char *)current_buffer; payload_len = (uint16_t)(len_buffer[0] << 8 | len_buffer[1]); current_buffer += sizeof(uint16_t); } else if (!(payload_byte ^ WS_THREE_BYTES_LENGTH)) { uint64_t payload_64bit_len; if (current_buffer + sizeof(uint64_t) > current_buffer_end) { break; } for (uint8_t i = 0; i < sizeof(uint64_t); i++) { memcpy((uint8_t *)&payload_64bit_len + i, current_buffer + sizeof(uint64_t) - 1 - i, sizeof(uint8_t)); } if (payload_64bit_len > UINT32_MAX) { return WS_ERR_FRAME_SIZE_LIMIT; } payload_len = (uint32_t)payload_64bit_len; current_buffer += sizeof(uint64_t); } else { payload_len = payload_byte; } if (mask && ((current_buffer + 4 > current_buffer_end) || (current_buffer + 4 + payload_len > current_buffer_end))) { break; } else if (!mask && (current_buffer + payload_len > current_buffer_end)) { break; } uint8_t ret_val = iotjs_websocket_decode_frame(wsclient, first_byte, current_buffer, payload_len, jsref, mask, client); if (ret_val) { return iotjs_websocket_check_error(ret_val); } current_buffer += mask ? 4 : 0; current_buffer += payload_len; } if (current_buffer == wsclient->tcp_buff.buffer) { return jerry_create_undefined(); } uint32_t remaining_size = (uint32_t)(current_buffer_end - current_buffer); char *buffer = IOTJS_CALLOC(remaining_size, char); memcpy(buffer, current_buffer, remaining_size); if (wsclient->tcp_buff.buffer != NULL) { IOTJS_RELEASE(wsclient->tcp_buff.buffer); } wsclient->tcp_buff.buffer = buffer; wsclient->tcp_buff.length = remaining_size; return jerry_create_undefined(); } JS_FUNCTION(ws_init) { DJS_CHECK_THIS(); const jerry_value_t jws = JS_GET_ARG(0, object); iotjs_wsclient_t *wsclient = iotjs_wsclient_create(jws); wsclient->tcp_buff.buffer = NULL; wsclient->tcp_buff.length = 0; wsclient->ws_buff.data = NULL; wsclient->ws_buff.length = 0; wsclient->generated_key = NULL; return jerry_create_undefined(); } JS_FUNCTION(ws_close) { DJS_CHECK_THIS(); bool masked = false; uint8_t opcode = WS_OP_TERMINATE; iotjs_string_t payload = iotjs_string_create(); jerry_value_t jmsg = JS_GET_ARG(0, any); jerry_value_t jcode = JS_GET_ARG(1, any); iotjs_string_t msg = iotjs_string_create(); // Client side close frame must be ALWAYS masked masked = iotjs_jbuffer_as_string(jmsg, &msg) || jerry_value_is_number(jcode); if (jerry_value_is_number(jcode)) { uint16_t code = jerry_get_number_value(jcode); iotjs_string_append(&payload, (const char *)&code + 1, 1); iotjs_string_append(&payload, (const char *)&code, 1); } if (!iotjs_string_is_empty(&msg)) { // We have no status code, but do have msg, append the status code if (iotjs_string_is_empty(&payload)) { uint16_t code = 1000; iotjs_string_append(&payload, (const char *)&code + 1, 1); iotjs_string_append(&payload, (const char *)&code, 1); } iotjs_string_append(&payload, iotjs_string_data(&msg), iotjs_string_size(&msg)); iotjs_string_destroy(&msg); } jerry_value_t ret_val = iotjs_websocket_encode_frame(opcode, masked, false, (char *)iotjs_string_data(&payload), iotjs_string_size(&payload)); if (payload.data != NULL) { iotjs_string_destroy(&payload); } return ret_val; } JS_FUNCTION(ws_send_data) { DJS_CHECK_THIS(); jerry_value_t jmsg = JS_GET_ARG(0, any); iotjs_string_t msg = iotjs_string_create(); if (!iotjs_jbuffer_as_string(jmsg, &msg)) { return jerry_create_undefined(); } bool binary = jerry_get_boolean_value(jargv[1]); bool mask = jerry_get_boolean_value(jargv[2]); bool compress = jerry_get_boolean_value(jargv[3]); uint8_t opcode = binary ? WS_OP_BINARY : WS_OP_UTF8; jerry_value_t ret_val = iotjs_websocket_encode_frame(opcode, mask, compress, (char *)iotjs_string_data(&msg), iotjs_string_size(&msg)); iotjs_string_destroy(&msg); return ret_val; } JS_FUNCTION(ws_ping_or_pong) { DJS_CHECK_THIS(); uint8_t opcode = jerry_get_boolean_value(JS_GET_ARG(0, any)) ? WS_OP_PING : WS_OP_PONG; jerry_value_t jmsg = JS_GET_ARG(1, any); iotjs_string_t msg = iotjs_string_create(); jerry_value_t ret_val; if (iotjs_jbuffer_as_string(jmsg, &msg)) { ret_val = iotjs_websocket_encode_frame(opcode, jerry_get_boolean_value( JS_GET_ARG(2, any)), false, (char *)iotjs_string_data(&msg), iotjs_string_size(&msg)); iotjs_string_destroy(&msg); } else { ret_val = iotjs_websocket_encode_frame(opcode, false, false, NULL, 0); } return ret_val; } jerry_value_t iotjs_init_websocket(void) { IOTJS_UNUSED(WS_GUID); jerry_value_t jws = jerry_create_object(); iotjs_jval_set_method(jws, IOTJS_MAGIC_STRING_CLOSE, ws_close); iotjs_jval_set_method(jws, IOTJS_MAGIC_STRING_PARSEHANDSHAKEDATA, parse_handshake_data); iotjs_jval_set_method(jws, IOTJS_MAGIC_STRING_PING, ws_ping_or_pong); iotjs_jval_set_method(jws, IOTJS_MAGIC_STRING_PREPAREHANDSHAKE, prepare_handshake_request); iotjs_jval_set_method(jws, IOTJS_MAGIC_STRING_SEND, ws_send_data); iotjs_jval_set_method(jws, IOTJS_MAGIC_STRING_WSINIT, ws_init); iotjs_jval_set_method(jws, IOTJS_MAGIC_STRING_WSRECEIVE, ws_receive); iotjs_jval_set_method(jws, IOTJS_MAGIC_STRING_WSRECEIVEHANDSHAKEDATA, receive_handshake_data); return jws; } iotjs-1.0+715/src/modules/iotjs_module_websocket.h000066400000000000000000000030211371177304000221640ustar00rootroot00000000000000/* Copyright 2018-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_WEBSOCKET_H #define IOTJS_MODULE_WEBSOCKET_H enum { WS_OP_CONTINUE = 0x00, WS_OP_UTF8 = 0x01, WS_OP_BINARY = 0x02, WS_OP_TERMINATE = 0x08, WS_OP_PING = 0x09, WS_OP_PONG = 0x0a, } iotjs_websocket_opcodes; enum { WS_FIN_BIT = 0x80, WS_MASK_BIT = WS_FIN_BIT, } iotjs_websocket_header_bits; enum { WS_ERR_INVALID_UTF8 = 1, WS_ERR_INVALID_TERMINATE_CODE = 2, WS_ERR_UNKNOWN_OPCODE = 3, WS_ERR_NATIVE_POINTER_ERR = 4, WS_ERR_FRAME_SIZE_LIMIT = 5, } iotjs_websocket_err_codes; enum { WS_ONE_BYTE_LENGTH = 125, WS_TWO_BYTES_LENGTH, WS_THREE_BYTES_LENGTH, } iotjs_websocket_frame_len_types; typedef struct { struct { uint32_t length; char *buffer; } tcp_buff; struct { uint32_t length; char *data; char first_byte; bool masked; } ws_buff; unsigned char *generated_key; } iotjs_wsclient_t; #endif /* IOTJS_MODULE_WEBSOCKET_H */ iotjs-1.0+715/src/modules/linux/000077500000000000000000000000001371177304000164135ustar00rootroot00000000000000iotjs-1.0+715/src/modules/linux/iotjs_module_adc-linux.c000066400000000000000000000051351371177304000232240ustar00rootroot00000000000000/* 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(__linux__) #error "Module __FILE__ is for Linux only" #endif #include #include #include #include #include "iotjs_systemio-linux.h" #include "modules/iotjs_module_adc.h" #define ADC_PIN_FORMAT ADC_INTERFACE ADC_PIN_INTERFACE #define ADC_PATH_BUFFER_SIZE DEVICE_IO_PATH_BUFFER_SIZE #define ADC_PIN_BUFFER_SIZE DEVICE_IO_PIN_BUFFER_SIZE #define ADC_VALUE_BUFFER_SIZE 64 struct iotjs_adc_platform_data_s { iotjs_string_t device; }; void iotjs_adc_create_platform_data(iotjs_adc_t* adc) { adc->platform_data = IOTJS_ALLOC(iotjs_adc_platform_data_t); } void iotjs_adc_destroy_platform_data(iotjs_adc_platform_data_t* platform_data) { iotjs_string_destroy(&platform_data->device); IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_adc_set_platform_config(iotjs_adc_t* adc, const jerry_value_t jconfig) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; JS_GET_REQUIRED_CONF_VALUE(jconfig, platform_data->device, IOTJS_MAGIC_STRING_DEVICE, string); return jerry_create_undefined(); } // Implementation used here are based on: // https://www.kernel.org/doc/Documentation/adc/sysfs.txt bool iotjs_adc_read(iotjs_adc_t* adc) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; const char* device_path = iotjs_string_data(&platform_data->device); char buffer[ADC_VALUE_BUFFER_SIZE]; if (!iotjs_systemio_open_read_close(device_path, buffer, sizeof(buffer))) { return false; } adc->value = atoi(buffer) != 0; return true; } bool iotjs_adc_close(iotjs_adc_t* adc) { return true; } bool iotjs_adc_open(iotjs_adc_t* adc) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; DDDLOG("%s()", __func__); const char* device_path = iotjs_string_data(&platform_data->device); // Check if ADC interface exists. if (!iotjs_systemio_check_path(device_path)) { return false; } return true; } iotjs-1.0+715/src/modules/linux/iotjs_module_blehcisocket-linux.c000066400000000000000000000275561371177304000251470ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ #include #include #include #include #include #include #include "iotjs_def.h" #include "modules/iotjs_module_blehcisocket.h" #include "modules/iotjs_module_buffer.h" #define BTPROTO_L2CAP 0 #define BTPROTO_HCI 1 #define SOL_HCI 0 #define HCI_FILTER 2 #define HCIGETDEVLIST _IOR('H', 210, int) #define HCIGETDEVINFO _IOR('H', 211, int) #define HCI_CHANNEL_RAW 0 #define HCI_CHANNEL_USER 1 #define HCI_CHANNEL_CONTROL 3 #define HCI_DEV_NONE 0xffff #define HCI_MAX_DEV 16 #define ATT_CID 4 enum { HCI_UP, HCI_INIT, HCI_RUNNING, HCI_PSCAN, HCI_ISCAN, HCI_AUTH, HCI_ENCRYPT, HCI_INQUIRY, HCI_RAW, }; struct sockaddr_hci { sa_family_t hci_family; unsigned short hci_dev; unsigned short hci_channel; }; struct hci_dev_req { uint16_t dev_id; uint32_t dev_opt; }; struct hci_dev_list_req { uint16_t dev_num; struct hci_dev_req dev_req[0]; }; typedef struct hci_dev_list_req hci_dev_list_req_type; typedef struct { uint8_t b[6]; } __attribute__((packed)) bdaddr_t; struct hci_dev_info { uint16_t dev_id; char name[8]; bdaddr_t bdaddr; uint32_t flags; uint8_t type; uint8_t features[8]; uint32_t pkt_type; uint32_t link_policy; uint32_t link_mode; uint16_t acl_mtu; uint16_t acl_pkts; uint16_t sco_mtu; uint16_t sco_pkts; // hci_dev_stats uint32_t err_rx; uint32_t err_tx; uint32_t cmd_tx; uint32_t evt_rx; uint32_t acl_tx; uint32_t acl_rx; uint32_t sco_tx; uint32_t sco_rx; uint32_t byte_rx; uint32_t byte_tx; }; struct sockaddr_l2 { sa_family_t l2_family; unsigned short l2_psm; bdaddr_t l2_bdaddr; unsigned short l2_cid; uint8_t l2_bdaddr_type; }; void iotjs_blehcisocket_initialize(iotjs_blehcisocket_t* blehcisocket) { blehcisocket->_l2socketCount = 0; blehcisocket->_socket = socket(AF_BLUETOOTH, SOCK_RAW | SOCK_CLOEXEC, BTPROTO_HCI); uv_loop_t* loop = iotjs_environment_loop(iotjs_environment_get()); uv_poll_init(loop, &(blehcisocket->_pollHandle), blehcisocket->_socket); blehcisocket->_pollHandle.data = blehcisocket; } void iotjs_blehcisocket_close(iotjs_blehcisocket_t* blehcisocket) { uv_close((uv_handle_t*)&(blehcisocket->_pollHandle), NULL); close(blehcisocket->_socket); } void iotjs_blehcisocket_start(iotjs_blehcisocket_t* blehcisocket) { uv_poll_start(&blehcisocket->_pollHandle, UV_READABLE, iotjs_blehcisocket_poll_cb); } int iotjs_blehcisocket_bindRaw(iotjs_blehcisocket_t* blehcisocket, int* devId) { struct sockaddr_hci a; struct hci_dev_info di; memset(&a, 0, sizeof(a)); a.hci_family = AF_BLUETOOTH; a.hci_dev = iotjs_blehcisocket_devIdFor(blehcisocket, devId, true); a.hci_channel = HCI_CHANNEL_RAW; blehcisocket->_devId = a.hci_dev; blehcisocket->_mode = HCI_CHANNEL_RAW; if (bind(blehcisocket->_socket, (struct sockaddr*)&a, sizeof(a)) < 0) { DLOG("ERROR on binding: %s", strerror(errno)); return blehcisocket->_devId; } // get the local address and address type memset(&di, 0x00, sizeof(di)); di.dev_id = blehcisocket->_devId; memset(blehcisocket->_address, 0, sizeof(blehcisocket->_address)); blehcisocket->_addressType = 0; if (ioctl(blehcisocket->_socket, HCIGETDEVINFO, (void*)&di) > -1) { memcpy(blehcisocket->_address, &di.bdaddr, sizeof(di.bdaddr)); blehcisocket->_addressType = di.type; if (blehcisocket->_addressType == 3) { // 3 is a weird type, use 1 (public) instead blehcisocket->_addressType = 1; } } return blehcisocket->_devId; } int iotjs_blehcisocket_bindUser(iotjs_blehcisocket_t* blehcisocket, int* devId) { struct sockaddr_hci a; memset(&a, 0, sizeof(a)); a.hci_family = AF_BLUETOOTH; a.hci_dev = iotjs_blehcisocket_devIdFor(blehcisocket, devId, false); a.hci_channel = HCI_CHANNEL_USER; blehcisocket->_devId = a.hci_dev; blehcisocket->_mode = HCI_CHANNEL_USER; if (bind(blehcisocket->_socket, (struct sockaddr*)&a, sizeof(a)) < 0) { DLOG("ERROR on binding: %s", strerror(errno)); } return blehcisocket->_devId; } void iotjs_blehcisocket_bindControl(iotjs_blehcisocket_t* blehcisocket) { struct sockaddr_hci a; memset(&a, 0, sizeof(a)); a.hci_family = AF_BLUETOOTH; a.hci_dev = HCI_DEV_NONE; a.hci_channel = HCI_CHANNEL_CONTROL; blehcisocket->_mode = HCI_CHANNEL_CONTROL; if (bind(blehcisocket->_socket, (struct sockaddr*)&a, sizeof(a)) < 0) { DLOG("ERROR on binding: %s", strerror(errno)); } } bool iotjs_blehcisocket_isDevUp(iotjs_blehcisocket_t* blehcisocket) { struct hci_dev_info di; bool isUp = false; memset(&di, 0x00, sizeof(di)); di.dev_id = blehcisocket->_devId; if (ioctl(blehcisocket->_socket, HCIGETDEVINFO, (void*)&di) > -1) { isUp = (di.flags & (1 << HCI_UP)) != 0; } return isUp; } void iotjs_blehcisocket_setFilter(iotjs_blehcisocket_t* blehcisocket, char* data, size_t length) { if (setsockopt(blehcisocket->_socket, SOL_HCI, HCI_FILTER, data, (socklen_t)length) < 0) { iotjs_blehcisocket_emitErrnoError(blehcisocket); } } void iotjs_blehcisocket_poll(iotjs_blehcisocket_t* blehcisocket) { int length = 0; char data[1024]; length = read(blehcisocket->_socket, data, sizeof(data)); if (length > 0) { if (blehcisocket->_mode == HCI_CHANNEL_RAW) { if (iotjs_blehcisocket_kernelDisconnectWorkArounds(blehcisocket, length, data) < 0) { return; } } jerry_value_t jhcisocket = blehcisocket->jobject; jerry_value_t jemit = iotjs_jval_get_property(jhcisocket, "emit"); IOTJS_ASSERT(jerry_value_is_function(jemit)); jerry_value_t str = jerry_create_string((const jerry_char_t*)"data"); IOTJS_ASSERT(length >= 0); jerry_value_t jbuf = iotjs_bufferwrap_create_buffer((size_t)length); iotjs_bufferwrap_t* buf_wrap = iotjs_bufferwrap_from_jbuffer(jbuf); iotjs_bufferwrap_copy(buf_wrap, data, (size_t)length); jerry_value_t jargs[2] = { str, jbuf }; jerry_value_t jres = jerry_call_function(jemit, jhcisocket, jargs, 2); IOTJS_ASSERT(!jerry_value_is_error(jres)); jerry_release_value(jres); jerry_release_value(str); jerry_release_value(jbuf); jerry_release_value(jemit); } } void iotjs_blehcisocket_stop(iotjs_blehcisocket_t* blehcisocket) { uv_poll_stop(&blehcisocket->_pollHandle); } void iotjs_blehcisocket_write(iotjs_blehcisocket_t* blehcisocket, char* data, size_t length) { if (write(blehcisocket->_socket, data, length) < 0) { iotjs_blehcisocket_emitErrnoError(blehcisocket); } } void iotjs_blehcisocket_emitErrnoError(iotjs_blehcisocket_t* blehcisocket) { jerry_value_t jhcisocket = blehcisocket->jobject; jerry_value_t jemit = iotjs_jval_get_property(jhcisocket, "emit"); IOTJS_ASSERT(jerry_value_is_function(jemit)); jerry_value_t str = jerry_create_string((const jerry_char_t*)"error"); jerry_value_t jerror = iotjs_jval_create_error_without_error_flag(strerror(errno)); jerry_value_t jargs[2] = { str, jerror }; jerry_value_t jres = jerry_call_function(jemit, jhcisocket, jargs, 2); IOTJS_ASSERT(!jerry_value_is_error(jres)); jerry_release_value(jres); jerry_release_value(str); jerry_release_value(jerror); jerry_release_value(jemit); } int iotjs_blehcisocket_devIdFor(iotjs_blehcisocket_t* blehcisocket, int* pDevId, bool isUp) { int devId = 0; // default if (pDevId == NULL) { struct hci_dev_list_req* dl; struct hci_dev_req* dr; dl = (struct hci_dev_list_req*)calloc(HCI_MAX_DEV * sizeof(*dr) + sizeof(*dl), 1); dr = dl->dev_req; dl->dev_num = HCI_MAX_DEV; if (ioctl(blehcisocket->_socket, HCIGETDEVLIST, dl) > -1) { for (int i = 0; i < dl->dev_num; i++, dr++) { bool devUp = dr->dev_opt & (1 << HCI_UP); bool match = isUp ? devUp : !devUp; if (match) { devId = dr->dev_id; break; } } } free(dl); } else { devId = *pDevId; } return devId; } int iotjs_blehcisocket_kernelDisconnectWorkArounds( iotjs_blehcisocket_t* blehcisocket, int length, char* data) { if (length == 22 && data[0] == 0x04 && data[1] == 0x3e && data[2] == 0x13 && data[3] == 0x01 && data[4] == 0x00) { int l2socket; struct sockaddr_l2 l2a; unsigned short l2cid; unsigned short handle = *((unsigned short*)(&data[5])); #if __BYTE_ORDER == __LITTLE_ENDIAN l2cid = ATT_CID; #elif __BYTE_ORDER == __BIG_ENDIAN l2cid = bswap_16(ATT_CID); #else #error "Unknown byte order" #endif l2socket = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP); if (l2socket < 0) { DLOG("ERROR creating socket: %s", strerror(errno)); return -1; } memset(&l2a, 0, sizeof(l2a)); l2a.l2_family = AF_BLUETOOTH; l2a.l2_cid = l2cid; memcpy(&l2a.l2_bdaddr, blehcisocket->_address, sizeof(l2a.l2_bdaddr)); l2a.l2_bdaddr_type = blehcisocket->_addressType; if (bind(l2socket, (struct sockaddr*)&l2a, sizeof(l2a)) < 0) { DLOG("ERROR on binding: %s", strerror(errno)); close(l2socket); return -1; } memset(&l2a, 0, sizeof(l2a)); l2a.l2_family = AF_BLUETOOTH; memcpy(&l2a.l2_bdaddr, &data[9], sizeof(l2a.l2_bdaddr)); l2a.l2_cid = l2cid; l2a.l2_bdaddr_type = data[8] + 1; if (connect(l2socket, (struct sockaddr*)&l2a, sizeof(l2a)) < 0) { DLOG("ERROR connecting socket: %s", strerror(errno)); close(l2socket); return -1; } blehcisocket->_l2sockets[handle] = l2socket; blehcisocket->_l2socketCount++; } else if (length == 7 && data[0] == 0x04 && data[1] == 0x05 && data[2] == 0x04 && data[3] == 0x00) { unsigned short handle = *((unsigned short*)(&data[4])); if (blehcisocket->_l2socketCount > 0) { close(blehcisocket->_l2sockets[handle]); blehcisocket->_l2socketCount--; } } return 0; } void iotjs_blehcisocket_poll_cb(uv_poll_t* handle, int status, int events) { iotjs_blehcisocket_t* blehcisocket = (iotjs_blehcisocket_t*)handle->data; iotjs_blehcisocket_poll(blehcisocket); } iotjs-1.0+715/src/modules/linux/iotjs_module_gpio-linux.c000066400000000000000000000171641371177304000234400ustar00rootroot00000000000000/* 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 #include #include #include #include #include "iotjs_systemio-linux.h" #include "modules/iotjs_module_gpio.h" #define GPIO_INTERFACE "/sys/class/gpio/" #define GPIO_EXPORT "export" #define GPIO_UNEXPORT "unexport" #define GPIO_DIRECTION "direction" #define GPIO_EDGE "edge" #define GPIO_VALUE "value" #define GPIO_PIN_INTERFACE "gpio%d/" #define GPIO_PIN_FORMAT_EXPORT GPIO_INTERFACE "export" #define GPIO_PIN_FORMAT_UNEXPORT GPIO_INTERFACE "unexport" #define GPIO_PIN_FORMAT GPIO_INTERFACE GPIO_PIN_INTERFACE #define GPIO_PIN_FORMAT_DIRECTION GPIO_PIN_FORMAT GPIO_DIRECTION #define GPIO_PIN_FORMAT_EDGE GPIO_PIN_FORMAT GPIO_EDGE #define GPIO_PIN_FORMAT_VALUE GPIO_PIN_FORMAT GPIO_VALUE #define GPIO_PATH_BUFFER_SIZE DEVICE_IO_PATH_BUFFER_SIZE #define GPIO_PIN_BUFFER_SIZE DEVICE_IO_PIN_BUFFER_SIZE #define GPIO_VALUE_BUFFER_SIZE 10 struct iotjs_gpio_platform_data_s { int value_fd; uv_thread_t thread; uv_mutex_t mutex; }; // Implementation used here are based on: // https://www.kernel.org/doc/Documentation/gpio/sysfs.txt static const char* gpio_edge_string[] = { "none", "rising", "falling", "both" }; static int gpio_get_value_fd(iotjs_gpio_t* gpio) { int fd; uv_mutex_lock(&gpio->platform_data->mutex); fd = gpio->platform_data->value_fd; uv_mutex_unlock(&gpio->platform_data->mutex); return fd; } static void gpio_set_value_fd(iotjs_gpio_t* gpio, int fd) { uv_mutex_lock(&gpio->platform_data->mutex); gpio->platform_data->value_fd = fd; uv_mutex_unlock(&gpio->platform_data->mutex); } static void gpio_emit_change_event(iotjs_gpio_t* gpio) { jerry_value_t jgpio = gpio->jobject; jerry_value_t jonChange = iotjs_jval_get_property(jgpio, "onChange"); IOTJS_ASSERT(jerry_value_is_function(jonChange)); jerry_value_t jres = jerry_call_function(jonChange, jgpio, NULL, 0); IOTJS_ASSERT(!jerry_value_is_error(jres)); jerry_release_value(jres); jerry_release_value(jonChange); } static bool gpio_clear_dummy_value(int fd) { char buffer[1]; if (lseek(fd, 0, SEEK_SET) < 0) { DLOG("GPIO Error in lseek"); return false; } if (read(fd, &buffer, 1) < 0) { DLOG("GPIO Error in read"); return false; } return true; } static int gpio_edge_poll(struct pollfd* pollfd) { int ret; // Wait edge if ((ret = poll(pollfd, 1, -1)) > 0) { if (!gpio_clear_dummy_value(pollfd->fd)) return -1; } return ret; } static void gpio_edge_detection_cb(void* data) { int fd; iotjs_gpio_t* gpio = (iotjs_gpio_t*)data; struct pollfd pollfd; if ((fd = gpio_get_value_fd(gpio)) < 0) { DLOG("GPIO Error: cannot start edge detection"); return; } memset(&pollfd, 0, sizeof(pollfd)); pollfd.fd = fd; pollfd.events = POLLPRI | POLLERR; if (!gpio_clear_dummy_value(fd)) return; while (true) { if ((fd = gpio_get_value_fd(gpio)) < 0) return; if (gpio_edge_poll(&pollfd) > 0) { gpio_emit_change_event(gpio); } else { DLOG("GPIO Error on poll: %s", strerror(errno)); } } } static bool gpio_set_direction(uint32_t pin, GpioDirection direction) { IOTJS_ASSERT(direction == kGpioDirectionIn || direction == kGpioDirectionOut); char direction_path[GPIO_PATH_BUFFER_SIZE]; snprintf(direction_path, GPIO_PATH_BUFFER_SIZE, GPIO_PIN_FORMAT_DIRECTION, pin); const char* buffer = (direction == kGpioDirectionIn) ? "in" : "out"; DDDLOG("%s - path: %s, dir: %s", __func__, direction_path, buffer); return iotjs_systemio_open_write_close(direction_path, buffer); } // FIXME: Implement SetPinMode() static bool gpio_set_mode(uint32_t pin, GpioMode mode) { return true; } static bool gpio_set_edge(iotjs_gpio_t* gpio) { char edge_path[GPIO_PATH_BUFFER_SIZE]; snprintf(edge_path, GPIO_PATH_BUFFER_SIZE, GPIO_PIN_FORMAT_EDGE, gpio->pin); iotjs_systemio_open_write_close(edge_path, gpio_edge_string[gpio->edge]); if (gpio->direction == kGpioDirectionIn && gpio->edge != kGpioEdgeNone) { char value_path[GPIO_PATH_BUFFER_SIZE]; snprintf(value_path, GPIO_PATH_BUFFER_SIZE, GPIO_PIN_FORMAT_VALUE, gpio->pin); if ((gpio->platform_data->value_fd = open(value_path, O_RDONLY)) < 0) { DLOG("GPIO Error in open"); return false; } // Create edge detection thread // When the GPIO pin is closed, thread is terminated. int ret = uv_thread_create(&gpio->platform_data->thread, gpio_edge_detection_cb, (void*)gpio); if (ret < 0) { DLOG("GPIO Error in uv_thread_create"); } return false; } return true; } void iotjs_gpio_create_platform_data(iotjs_gpio_t* gpio) { gpio->platform_data = IOTJS_ALLOC(iotjs_gpio_platform_data_t); gpio->platform_data->value_fd = -1; uv_mutex_init(&gpio->platform_data->mutex); } void iotjs_gpio_destroy_platform_data( iotjs_gpio_platform_data_t* platform_data) { IOTJS_RELEASE(platform_data); } bool iotjs_gpio_write(iotjs_gpio_t* gpio) { char value_path[GPIO_PATH_BUFFER_SIZE]; snprintf(value_path, GPIO_PATH_BUFFER_SIZE, GPIO_PIN_FORMAT_VALUE, gpio->pin); const char* buffer = gpio->value ? "1" : "0"; DDDLOG("%s - pin: %d, value: %d", __func__, gpio->pin, gpio->value); return iotjs_systemio_open_write_close(value_path, buffer); } bool iotjs_gpio_read(iotjs_gpio_t* gpio) { char buffer[GPIO_VALUE_BUFFER_SIZE]; char value_path[GPIO_PATH_BUFFER_SIZE]; snprintf(value_path, GPIO_PATH_BUFFER_SIZE, GPIO_PIN_FORMAT_VALUE, gpio->pin); if (!iotjs_systemio_open_read_close(value_path, buffer, GPIO_VALUE_BUFFER_SIZE - 1)) { return false; } gpio->value = atoi(buffer) != 0; return true; } bool iotjs_gpio_close(iotjs_gpio_t* gpio) { char buff[GPIO_PIN_BUFFER_SIZE]; snprintf(buff, GPIO_PIN_BUFFER_SIZE, "%d", gpio->pin); gpio_set_value_fd(gpio, -1); close(gpio->platform_data->value_fd); return iotjs_systemio_open_write_close(GPIO_PIN_FORMAT_UNEXPORT, buff); } bool iotjs_gpio_open(iotjs_gpio_t* gpio) { DDDLOG("%s - pin: %d, dir: %d, mode: %d", __func__, gpio->pin, gpio->direction, gpio->mode); // Open GPIO pin. char exported_path[GPIO_PATH_BUFFER_SIZE]; snprintf(exported_path, GPIO_PATH_BUFFER_SIZE, GPIO_PIN_FORMAT, gpio->pin); const char* created_files[] = { GPIO_DIRECTION, GPIO_EDGE, GPIO_VALUE }; int created_files_length = sizeof(created_files) / sizeof(created_files[0]); if (!iotjs_systemio_device_open(GPIO_PIN_FORMAT_EXPORT, gpio->pin, exported_path, created_files, created_files_length)) { return false; } // Set direction. if (!gpio_set_direction(gpio->pin, gpio->direction)) { return false; } // Set mode. if (!gpio_set_mode(gpio->pin, gpio->mode)) { return false; } // Set edge. if (!gpio_set_edge(gpio)) { return false; } return true; } bool iotjs_gpio_set_direction(iotjs_gpio_t* gpio) { if (!gpio_set_direction(gpio->pin, gpio->direction)) { DLOG("%s, Cannot set direction.", __func__); return false; } return true; } iotjs-1.0+715/src/modules/linux/iotjs_module_i2c-linux.c000066400000000000000000000107041371177304000231500ustar00rootroot00000000000000/* The MIT License (MIT) * * Copyright (c) 2005-2014 RoadNarrows LLC. * http://roadnarrows.com * 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. */ /* 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. */ /* Some functions are modified from the RoadNarrows-robotics i2c library. * (distributed under the MIT license.) */ #include #include #include #include #include #include #include #include #include #include "modules/iotjs_module_i2c.h" #define I2C_SLAVE_FORCE 0x0706 struct iotjs_i2c_platform_data_s { iotjs_string_t device; int device_fd; uint8_t addr; }; void iotjs_i2c_create_platform_data(iotjs_i2c_t* i2c) { i2c->platform_data = IOTJS_ALLOC(iotjs_i2c_platform_data_t); i2c->platform_data->device_fd = -1; } void iotjs_i2c_destroy_platform_data(iotjs_i2c_platform_data_t* pdata) { iotjs_string_destroy(&pdata->device); IOTJS_RELEASE(pdata); } jerry_value_t iotjs_i2c_set_platform_config(iotjs_i2c_t* i2c, const jerry_value_t jconfig) { iotjs_i2c_platform_data_t* platform_data = i2c->platform_data; JS_GET_REQUIRED_CONF_VALUE(jconfig, platform_data->device, IOTJS_MAGIC_STRING_DEVICE, string); return jerry_create_undefined(); } #define I2C_METHOD_HEADER(arg) \ iotjs_i2c_platform_data_t* platform_data = arg->platform_data; \ IOTJS_ASSERT(platform_data); \ if (platform_data->device_fd < 0) { \ DLOG("%s: I2C is not opened", __func__); \ return false; \ } bool iotjs_i2c_open(iotjs_i2c_t* i2c) { iotjs_i2c_platform_data_t* platform_data = i2c->platform_data; platform_data->device_fd = open(iotjs_string_data(&platform_data->device), O_RDWR); if (platform_data->device_fd == -1) { DLOG("%s : cannot open", __func__); return false; } if (ioctl(platform_data->device_fd, I2C_SLAVE_FORCE, i2c->address) < 0) { DLOG("%s : cannot set address", __func__); return false; } return true; } bool iotjs_i2c_close(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); if (close(platform_data->device_fd) < 0) { DLOG("%s : cannot close", __func__); return false; } platform_data->device_fd = -1; return true; } bool iotjs_i2c_write(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); uint8_t len = i2c->buf_len; char* data = i2c->buf_data; int ret = write(platform_data->device_fd, data, len); IOTJS_RELEASE(i2c->buf_data); return ret == len; } bool iotjs_i2c_read(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); uint8_t len = i2c->buf_len; i2c->buf_data = iotjs_buffer_allocate(len); return read(platform_data->device_fd, i2c->buf_data, len) == len; } iotjs-1.0+715/src/modules/linux/iotjs_module_pwm-linux.c000066400000000000000000000170401371177304000232760ustar00rootroot00000000000000/* 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 #include #include #include #include "iotjs_systemio-linux.h" #include "modules/iotjs_module_pwm.h" // Generic PWM implementation for linux. #define PWM_INTERFACE "/sys/class/pwm/pwmchip%d/" #define PWM_PIN_INTERFACE "pwm%d/" #define PWM_PIN_FORMAT PWM_INTERFACE PWM_PIN_INTERFACE #define PWM_EXPORT PWM_INTERFACE "export" #define PWM_UNEXPORT PWM_INTERFACE "unexport" #define PWM_PIN_DUTYCYCLE "duty_cycle" #define PWM_PIN_PERIOD "period" #define PWM_PIN_ENABlE "enable" #define PWM_PATH_BUFFER_SIZE 64 #define PWM_VALUE_BUFFER_SIZE 32 struct iotjs_pwm_platform_data_s { int chip; iotjs_string_t device; }; void iotjs_pwm_create_platform_data(iotjs_pwm_t* pwm) { pwm->platform_data = IOTJS_ALLOC(iotjs_pwm_platform_data_t); pwm->platform_data->chip = 0; } void iotjs_pwm_destroy_platform_data(iotjs_pwm_platform_data_t* pdata) { iotjs_string_destroy(&pdata->device); IOTJS_RELEASE(pdata); } jerry_value_t iotjs_pwm_set_platform_config(iotjs_pwm_t* pwm, const jerry_value_t jconfig) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; jerry_value_t jchip = iotjs_jval_get_property(jconfig, IOTJS_MAGIC_STRING_CHIP); if (jerry_value_is_error(jchip)) { return jchip; } if (jerry_value_is_number(jchip)) { platform_data->chip = iotjs_jval_as_number(jchip); } else { platform_data->chip = 0; } jerry_release_value(jchip); return jerry_create_undefined(); } // Generate device path for specified PWM device. // The path may include node suffix if passed ('enable', 'period', 'duty_cycle') // Pointer to a allocated string is returned, or null in case of error. // If PWM_PIN_FORMAT format results in an empty string, // NULL is returned (and fileName is ignored). static char* generate_device_subpath(iotjs_string_t* device, const char* fileName) { char* devicePath = NULL; // Do not print anything, only calculate resulting string length. size_t prefixSize = iotjs_string_size(device); if (prefixSize > 0) { size_t suffixSize = fileName ? strlen(fileName) : 0; devicePath = iotjs_buffer_allocate(prefixSize + suffixSize + 1); if (devicePath) { // Do not need to check bounds, the buffer is of exact required size. memcpy(devicePath, iotjs_string_data(device), prefixSize); memcpy(devicePath + prefixSize, fileName, suffixSize); devicePath[prefixSize + suffixSize] = 0; } } return devicePath; } // Limit period to [0..1]s static double adjust_period(double period) { if (period < 0) { return 0.0; } else if (period > 1) { return 1.0; } else { return period; } } bool iotjs_pwm_open(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; char path[PWM_PATH_BUFFER_SIZE] = { 0 }; if (snprintf(path, PWM_PATH_BUFFER_SIZE, PWM_PIN_FORMAT, platform_data->chip, pwm->pin) < 0) { return false; } platform_data->device = iotjs_string_create_with_size(path, strlen(path)); // See if the PWM is already opened. if (!iotjs_systemio_check_path(path)) { // Write exporting PWM path char export_path[PWM_PATH_BUFFER_SIZE] = { 0 }; snprintf(export_path, PWM_PATH_BUFFER_SIZE, PWM_EXPORT, platform_data->chip); const char* created_files[] = { PWM_PIN_DUTYCYCLE, PWM_PIN_PERIOD, PWM_PIN_ENABlE }; int created_files_length = sizeof(created_files) / sizeof(created_files[0]); if (!iotjs_systemio_device_open(export_path, pwm->pin, path, created_files, created_files_length)) { return false; } } // Set options. if (pwm->period >= 0) { if (!iotjs_pwm_set_period(pwm)) { return false; } if (pwm->duty_cycle >= 0) { if (!iotjs_pwm_set_dutycycle(pwm)) { return false; } } } DDDLOG("%s - path: %s", __func__, path); return true; } bool iotjs_pwm_set_period(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; bool result = false; if (isfinite(pwm->period) && pwm->period >= 0.0) { char* devicePath = generate_device_subpath(&platform_data->device, PWM_PIN_PERIOD); if (devicePath) { // Linux API uses nanoseconds, thus 1E9 unsigned int value = (unsigned)(adjust_period(pwm->period) * 1.E9); DDDLOG("%s - path: %s, value: %fs", __func__, devicePath, 1.E-9 * value); char buf[PWM_VALUE_BUFFER_SIZE]; if (snprintf(buf, sizeof(buf), "%d", value) > 0) { result = iotjs_systemio_open_write_close(devicePath, buf); } IOTJS_RELEASE(devicePath); } } return result; } bool iotjs_pwm_set_dutycycle(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; bool result = false; double dutyCycle = pwm->duty_cycle; if (isfinite(pwm->period) && pwm->period >= 0.0 && isfinite(dutyCycle) && 0.0 <= dutyCycle && dutyCycle <= 1.0) { char* devicePath = generate_device_subpath(&platform_data->device, PWM_PIN_DUTYCYCLE); if (devicePath) { double period = adjust_period(pwm->period); // Linux API uses nanoseconds, thus 1E9 unsigned dutyCycleValue = (unsigned)(period * pwm->duty_cycle * 1E9); DDDLOG("%s - path: %s, value: %d\n", __func__, devicePath, dutyCycleValue); char buf[PWM_VALUE_BUFFER_SIZE]; if (snprintf(buf, sizeof(buf), "%d", dutyCycleValue) < 0) { return false; } result = iotjs_systemio_open_write_close(devicePath, buf); IOTJS_RELEASE(devicePath); } } return result; } bool iotjs_pwm_set_enable(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; bool result = false; char* devicePath = generate_device_subpath(&platform_data->device, PWM_PIN_ENABlE); if (devicePath) { char value[4]; if (snprintf(value, sizeof(value), "%d", pwm->enable) < 0) { return false; } DDDLOG("%s - path: %s, set: %d\n", __func__, devicePath, pwm->enable); char buf[PWM_VALUE_BUFFER_SIZE]; if (snprintf(buf, sizeof(buf), "%d", pwm->enable) < 0) { return false; } result = iotjs_systemio_open_write_close(devicePath, buf); IOTJS_RELEASE(devicePath); } return result; } bool iotjs_pwm_close(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; char path[PWM_PATH_BUFFER_SIZE] = { 0 }; if (snprintf(path, PWM_PATH_BUFFER_SIZE, PWM_PIN_FORMAT, platform_data->chip, pwm->pin) < 0) { return false; } if (iotjs_systemio_check_path(path)) { // Write exporting pin path char unexport_path[PWM_PATH_BUFFER_SIZE] = { 0 }; if (snprintf(unexport_path, PWM_PATH_BUFFER_SIZE, PWM_UNEXPORT, platform_data->chip) < 0) { return false; } iotjs_systemio_device_close(unexport_path, pwm->pin); } DDDLOG("%s- path: %s", __func__, path); return true; } iotjs-1.0+715/src/modules/linux/iotjs_module_spi-linux.c000066400000000000000000000114071371177304000232670ustar00rootroot00000000000000/* 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 #include #include #include "iotjs_def.h" #include "iotjs_systemio-linux.h" #include "modules/iotjs_module_buffer.h" #include "modules/iotjs_module_spi.h" #define ADC_DEVICE_PATH_FORMAT "/dev/spidev%d.%d" #define ADC_DEVICE_PATH_BUFFER_SIZE 16 struct iotjs_spi_platform_data_s { iotjs_string_t device; int device_fd; }; void iotjs_spi_create_platform_data(iotjs_spi_t* spi) { spi->platform_data = IOTJS_ALLOC(iotjs_spi_platform_data_t); spi->platform_data->device_fd = -1; } void iotjs_spi_destroy_platform_data(iotjs_spi_platform_data_t* pdata) { iotjs_string_destroy(&pdata->device); IOTJS_RELEASE(pdata); } jerry_value_t iotjs_spi_set_platform_config(iotjs_spi_t* spi, const jerry_value_t jconfig) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; JS_GET_REQUIRED_CONF_VALUE(jconfig, platform_data->device, IOTJS_MAGIC_STRING_DEVICE, string); return jerry_create_undefined(); } static bool spi_set_configuration(iotjs_spi_t* spi) { int fd = spi->platform_data->device_fd; if (fd < 0) { return false; } uint8_t data; switch (spi->mode) { case kSpiMode_0: data = SPI_MODE_0; break; case kSpiMode_1: data = SPI_MODE_1; break; case kSpiMode_2: data = SPI_MODE_2; break; case kSpiMode_3: data = SPI_MODE_3; break; default: data = SPI_MODE_0; } if (spi->loopback) { data |= SPI_LOOP; } if (spi->chip_select == kSpiCsHigh) { data |= SPI_CS_HIGH; } if (ioctl(fd, SPI_IOC_WR_MODE, &spi->mode) < 0) { return false; } if (spi->bit_order == kSpiOrderLsb) { data = 1; if (ioctl(fd, SPI_IOC_WR_LSB_FIRST, &data) < 0) { return false; } } if (ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &spi->bits_per_word) < 0) { return false; } if (ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &spi->max_speed) < 0) { return false; } DDDLOG( "SPI Options \n mode: %d\n chipSelect: %d\n bitOrder: %d\n " "maxSpeed: %d\n bitPerWord: %d\n loopback: %d", spi->mode, spi->chip_select, spi->bit_order, spi->max_speed, spi->bits_per_word, spi->loopback); return true; } bool iotjs_spi_transfer(iotjs_spi_t* spi) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; struct spi_ioc_transfer data = {.tx_buf = (unsigned long)spi->tx_buf_data, .rx_buf = (unsigned long)spi->rx_buf_data, .len = spi->buf_len, .speed_hz = spi->max_speed, .bits_per_word = spi->bits_per_word, .delay_usecs = 0 }; // Transfer data int err = ioctl(platform_data->device_fd, SPI_IOC_MESSAGE(1), &data); if (err < 1) { DLOG("%s - transfer failed: %d", __func__, err); return false; } return true; } bool iotjs_spi_close(iotjs_spi_t* spi) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; if (platform_data->device_fd >= 0) { const iotjs_environment_t* env = iotjs_environment_get(); uv_loop_t* loop = iotjs_environment_loop(env); uv_fs_t fs_close_req; int err = uv_fs_close(loop, &fs_close_req, platform_data->device_fd, NULL); uv_fs_req_cleanup(&fs_close_req); if (err < 0) { DLOG("%s - close failed: %d", __func__, err); return false; } platform_data->device_fd = -1; } return true; } bool iotjs_spi_open(iotjs_spi_t* spi) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; const char* device_path = iotjs_string_data(&platform_data->device); if (!iotjs_systemio_check_path(device_path)) { return false; } // Open file const iotjs_environment_t* env = iotjs_environment_get(); uv_loop_t* loop = iotjs_environment_loop(env); uv_fs_t open_req; int result = uv_fs_open(loop, &open_req, device_path, O_RDONLY, 0666, NULL); uv_fs_req_cleanup(&open_req); if (result < 0) { return false; } platform_data->device_fd = open_req.result; // Set options if (!spi_set_configuration(spi)) { return false; } return true; } iotjs-1.0+715/src/modules/linux/iotjs_module_uart-linux.c000066400000000000000000000101461371177304000234460ustar00rootroot00000000000000/* 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 #include #include #include #include "iotjs_uv_handle.h" #include "modules/iotjs_module_uart.h" struct iotjs_uart_platform_data_s { iotjs_string_t device_path; }; static unsigned baud_to_constant(unsigned baudRate) { switch (baudRate) { case 50: return B50; case 75: return B75; case 110: return B110; case 134: return B134; case 150: return B150; case 200: return B200; case 300: return B300; case 600: return B600; case 1200: return B1200; case 1800: return B1800; case 2400: return B2400; case 4800: return B4800; case 9600: return B9600; case 19200: return B19200; case 38400: return B38400; case 57600: return B57600; case 115200: return B115200; case 230400: return B230400; } return B0; } static int databits_to_constant(int dataBits) { switch (dataBits) { case 8: return CS8; case 7: return CS7; case 6: return CS6; case 5: return CS5; } return -1; } void iotjs_uart_create_platform_data(iotjs_uart_t* uart) { uart->platform_data = IOTJS_ALLOC(iotjs_uart_platform_data_t); } void iotjs_uart_destroy_platform_data( iotjs_uart_platform_data_t* platform_data) { IOTJS_ASSERT(platform_data); iotjs_string_destroy(&platform_data->device_path); IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_uart_set_platform_config(iotjs_uart_t* uart, const jerry_value_t jconfig) { JS_GET_REQUIRED_CONF_VALUE(jconfig, uart->platform_data->device_path, IOTJS_MAGIC_STRING_DEVICE, string); return jerry_create_undefined(); } bool iotjs_uart_open(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); int fd = open(iotjs_string_data(&uart->platform_data->device_path), O_RDWR | O_NOCTTY | O_NDELAY); if (fd < 0) { return false; } struct termios options; tcgetattr(fd, &options); options.c_cflag = CLOCAL | CREAD; options.c_cflag |= (tcflag_t)baud_to_constant(uart->baud_rate); options.c_cflag |= (tcflag_t)databits_to_constant(uart->data_bits); options.c_iflag = IGNPAR; options.c_oflag = 0; options.c_lflag = 0; tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &options); uart->device_fd = fd; iotjs_uart_register_read_cb((uv_poll_t*)uart_poll_handle); return true; } bool iotjs_uart_write(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); int bytesWritten = 0; unsigned offset = 0; int fd = uart->device_fd; const char* buf_data = iotjs_string_data(&uart->buf_data); DDDLOG("%s - data: %s", __func__, buf_data); do { errno = 0; bytesWritten = write(fd, buf_data + offset, uart->buf_len - offset); tcdrain(fd); DDDLOG("%s - size: %d", __func__, uart->buf_len - offset); if (bytesWritten != -1) { offset += (unsigned)bytesWritten; continue; } if (errno == EINTR) { continue; } return false; } while (uart->buf_len > offset); return true; } void iotjs_uart_handle_close_cb(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); if (close(uart->device_fd) < 0) { DLOG(iotjs_periph_error_str(kUartOpClose)); IOTJS_ASSERT(0); } } iotjs-1.0+715/src/modules/mock/000077500000000000000000000000001371177304000162055ustar00rootroot00000000000000iotjs-1.0+715/src/modules/mock/iotjs_module_gpio-mock.c000066400000000000000000000033721371177304000230200ustar00rootroot00000000000000/* Copyright 2018-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 #include "modules/iotjs_module_gpio.h" struct iotjs_gpio_platform_data_s { bool is_open; bool level; }; void iotjs_gpio_create_platform_data(iotjs_gpio_t* gpio) { gpio->platform_data = IOTJS_ALLOC(iotjs_gpio_platform_data_t); } void iotjs_gpio_destroy_platform_data( iotjs_gpio_platform_data_t* platform_data) { IOTJS_RELEASE(platform_data); } bool iotjs_gpio_open(iotjs_gpio_t* gpio) { DDDLOG("%s - pin: %d, direction: %d, mode: %d", __func__, gpio->pin, gpio->direction, gpio->mode); if (gpio->platform_data->is_open) { return false; // pin is open already } gpio->platform_data->is_open = true; return true; } bool iotjs_gpio_write(iotjs_gpio_t* gpio) { gpio->platform_data->level = gpio->value; return true; } bool iotjs_gpio_read(iotjs_gpio_t* gpio) { gpio->value = gpio->platform_data->level; return true; } bool iotjs_gpio_close(iotjs_gpio_t* gpio) { if (!gpio->platform_data->is_open) { return false; // pin is not open } gpio->platform_data->is_open = false; return true; } bool iotjs_gpio_set_direction(iotjs_gpio_t* gpio) { return true; } iotjs-1.0+715/src/modules/mock/iotjs_module_i2c-mock.c000066400000000000000000000027301371177304000225340ustar00rootroot00000000000000/* Copyright 2018-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 "modules/iotjs_module_i2c.h" struct iotjs_i2c_platform_data_s { int bus; }; void iotjs_i2c_create_platform_data(iotjs_i2c_t* i2c) { i2c->platform_data = IOTJS_ALLOC(iotjs_i2c_platform_data_t); } void iotjs_i2c_destroy_platform_data(iotjs_i2c_platform_data_t* platform_data) { IOTJS_ASSERT(platform_data); IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_i2c_set_platform_config(iotjs_i2c_t* i2c, const jerry_value_t jconfig) { return jerry_create_undefined(); } bool iotjs_i2c_open(iotjs_i2c_t* i2c) { return true; } bool iotjs_i2c_close(iotjs_i2c_t* i2c) { return true; } bool iotjs_i2c_write(iotjs_i2c_t* i2c) { IOTJS_RELEASE(i2c->buf_data); return true; } bool iotjs_i2c_read(iotjs_i2c_t* i2c) { i2c->buf_data = iotjs_buffer_allocate(i2c->buf_len); return true; } iotjs-1.0+715/src/modules/mock/iotjs_module_pwm-mock.c000066400000000000000000000044611371177304000226650ustar00rootroot00000000000000/* Copyright 2019-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 "modules/iotjs_module_pwm.h" struct iotjs_pwm_platform_data_s { bool is_open; }; void iotjs_pwm_create_platform_data(iotjs_pwm_t* pwm) { pwm->platform_data = IOTJS_ALLOC(iotjs_pwm_platform_data_t); } void iotjs_pwm_destroy_platform_data(iotjs_pwm_platform_data_t* pdata) { IOTJS_RELEASE(pdata); } jerry_value_t iotjs_pwm_set_platform_config(iotjs_pwm_t* pwm, const jerry_value_t jconfig) { IOTJS_UNUSED(pwm); IOTJS_UNUSED(jconfig); if (jerry_value_is_object(jconfig)) { return jerry_create_undefined(); } else { return JS_CREATE_ERROR(COMMON, "Config must be an object."); } } bool iotjs_pwm_open(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; IOTJS_ASSERT(platform_data != NULL); if (platform_data->is_open) { return false; // pin is open already } platform_data->is_open = true; return true; } bool iotjs_pwm_set_period(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; IOTJS_ASSERT(platform_data != NULL); return true; } bool iotjs_pwm_set_dutycycle(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; IOTJS_ASSERT(platform_data != NULL); return true; } bool iotjs_pwm_set_enable(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; IOTJS_ASSERT(platform_data != NULL); return true; } bool iotjs_pwm_close(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; IOTJS_ASSERT(platform_data != NULL); if (!platform_data->is_open) { return false; // pin is not open } platform_data->is_open = false; return true; } iotjs-1.0+715/src/modules/nuttx/000077500000000000000000000000001371177304000164365ustar00rootroot00000000000000iotjs-1.0+715/src/modules/nuttx/iotjs_module_adc-nuttx.c000066400000000000000000000077431371177304000233010ustar00rootroot00000000000000/* 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__) #error "Module __FILE__ is for NuttX only" #endif #include #include #include #include "iotjs_def.h" #include "iotjs_systemio-nuttx.h" #include "modules/iotjs_module_adc.h" #define ADC_DEVICE_PATH_FORMAT "/dev/adc%d" #define ADC_DEVICE_PATH_BUFFER_SIZE 12 struct iotjs_adc_platform_data_s { uint32_t pin; }; void iotjs_adc_create_platform_data(iotjs_adc_t* adc) { adc->platform_data = IOTJS_ALLOC(iotjs_adc_platform_data_t); adc->platform_data->pin = 0; } void iotjs_adc_destroy_platform_data(iotjs_adc_platform_data_t* platform_data) { IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_adc_set_platform_config(iotjs_adc_t* adc, const jerry_value_t jconfig) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; JS_GET_REQUIRED_CONF_VALUE(jconfig, platform_data->pin, IOTJS_MAGIC_STRING_PIN, number); return jerry_create_undefined(); } static void adc_get_path(char* buffer, int32_t number) { // Create ADC device path snprintf(buffer, ADC_DEVICE_PATH_BUFFER_SIZE - 1, ADC_DEVICE_PATH_FORMAT, number); } static bool adc_read_data(uint32_t pin, struct adc_msg_s* msg) { int32_t adc_number = ADC_GET_NUMBER(pin); char path[ADC_DEVICE_PATH_BUFFER_SIZE] = { 0 }; adc_get_path(path, adc_number); const iotjs_environment_t* env = iotjs_environment_get(); uv_loop_t* loop = iotjs_environment_loop(env); int result, close_result; // Open file uv_fs_t open_req; result = uv_fs_open(loop, &open_req, path, O_RDONLY, 0666, NULL); uv_fs_req_cleanup(&open_req); if (result < 0) { return false; } // Read value uv_fs_t read_req; uv_buf_t uvbuf = uv_buf_init((char*)msg, sizeof(*msg)); result = uv_fs_read(loop, &read_req, open_req.result, &uvbuf, 1, 0, NULL); uv_fs_req_cleanup(&read_req); // Close file uv_fs_t close_req; close_result = uv_fs_close(loop, &close_req, open_req.result, NULL); uv_fs_req_cleanup(&close_req); if (result < 0 || close_result < 0) { return false; } DDDLOG("ADC Read - path: %s, value: %d", path, msg->am_data); return true; } bool iotjs_adc_read(iotjs_adc_t* adc) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; struct adc_msg_s msg; if (!adc_read_data(platform_data->pin, &msg)) { return false; } adc->value = msg.am_data; return true; } bool iotjs_adc_close(iotjs_adc_t* adc) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; uint32_t pin = platform_data->pin; int32_t adc_number = ADC_GET_NUMBER(pin); char path[ADC_DEVICE_PATH_BUFFER_SIZE] = { 0 }; adc_get_path(path, adc_number); // Release driver if (unregister_driver(path) < 0) { return false; } iotjs_gpio_unconfig_nuttx(pin); return true; } bool iotjs_adc_open(iotjs_adc_t* adc) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; uint32_t pin = platform_data->pin; int32_t adc_number = ADC_GET_NUMBER(pin); int32_t timer = SYSIO_GET_TIMER(pin); struct adc_dev_s* adc_dev = iotjs_adc_config_nuttx(adc_number, timer, pin); char path[ADC_DEVICE_PATH_BUFFER_SIZE] = { 0 }; adc_get_path(path, adc_number); if (adc_register(path, adc_dev) != 0) { return false; } DDDLOG("%s - path: %s, number: %d, timer: %d", __func__, path, adc_number, timer); return true; } iotjs-1.0+715/src/modules/nuttx/iotjs_module_blehcisocket-nuttx.c000066400000000000000000000050441371177304000252010ustar00rootroot00000000000000/* 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 "iotjs_def.h" #include "modules/iotjs_module_blehcisocket.h" void iotjs_blehcisocket_initialize(iotjs_blehcisocket_t* blehcisocket) { IOTJS_ASSERT(!"Not implemented"); } void iotjs_blehcisocket_close(iotjs_blehcisocket_t* blehcisocket) { IOTJS_ASSERT(!"Not implemented"); } void iotjs_blehcisocket_start(iotjs_blehcisocket_t* blehcisocket) { IOTJS_ASSERT(!"Not implemented"); } int iotjs_blehcisocket_bindRaw(iotjs_blehcisocket_t* blehcisocket, int* devId) { IOTJS_ASSERT(!"Not implemented"); return 0; } int iotjs_blehcisocket_bindUser(iotjs_blehcisocket_t* blehcisocket, int* devId) { IOTJS_ASSERT(!"Not implemented"); return 0; } void iotjs_blehcisocket_bindControl(iotjs_blehcisocket_t* blehcisocket) { IOTJS_ASSERT(!"Not implemented"); } bool iotjs_blehcisocket_isDevUp(iotjs_blehcisocket_t* blehcisocket) { IOTJS_ASSERT(!"Not implemented"); return false; } void iotjs_blehcisocket_setFilter(iotjs_blehcisocket_t* blehcisocket, char* data, size_t length) { IOTJS_ASSERT(!"Not implemented"); } void iotjs_blehcisocket_poll(iotjs_blehcisocket_t* blehcisocket) { IOTJS_ASSERT(!"Not implemented"); } void iotjs_blehcisocket_stop(iotjs_blehcisocket_t* blehcisocket) { IOTJS_ASSERT(!"Not implemented"); } void iotjs_blehcisocket_write(iotjs_blehcisocket_t* blehcisocket, char* data, size_t length) { IOTJS_ASSERT(!"Not implemented"); } void iotjs_blehcisocket_emitErrnoError(iotjs_blehcisocket_t* blehcisocket) { IOTJS_ASSERT(!"Not implemented"); } int iotjs_blehcisocket_devIdFor(iotjs_blehcisocket_t* blehcisocket, int* pDevId, bool isUp) { IOTJS_ASSERT(!"Not implemented"); return 0; } int iotjs_blehcisocket_kernelDisconnectWorkArounds( iotjs_blehcisocket_t* blehcisocket, int length, char* data) { IOTJS_ASSERT(!"Not implemented"); return 0; } iotjs-1.0+715/src/modules/nuttx/iotjs_module_gpio-nuttx.c000066400000000000000000000041611371177304000234770ustar00rootroot00000000000000/* 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 "modules/iotjs_module_gpio.h" #include "stm32_gpio.h" #define GPIO_FREQUENCY_DEFAULT GPIO_SPEED_25MHz #define GPIO_PINCNT_IN_NUTTXPORT 16 #define GPIO_CONFIG_OK 0 uint32_t gpioDirection[] = { GPIO_INPUT, GPIO_OUTPUT | GPIO_OUTPUT_SET | GPIO_FREQUENCY_DEFAULT, }; uint32_t gpioMode[] = { 0, // none GPIO_PULLUP, GPIO_PULLDOWN, GPIO_FLOAT, GPIO_PUSHPULL, GPIO_OPENDRAIN, }; void iotjs_gpio_create_platform_data(iotjs_gpio_t* gpio) { } void iotjs_gpio_destroy_platform_data( iotjs_gpio_platform_data_t* platform_data) { } bool iotjs_gpio_write(iotjs_gpio_t* gpio) { DDDLOG("%s - pin: %d, value: %d", __func__, gpio->pin, gpio->value); stm32_gpiowrite(gpio->pin, gpio->value); return true; } bool iotjs_gpio_read(iotjs_gpio_t* gpio) { DDDLOG("%s - pin: %d", __func__, gpio->pin); gpio->value = stm32_gpioread(gpio->pin); return true; } bool iotjs_gpio_close(iotjs_gpio_t* gpio) { iotjs_gpio_write(gpio); return true; } static bool gpio_set_config(iotjs_gpio_t* gpio) { uint32_t cfgset = 0; // Set pin direction and mode cfgset = gpioDirection[gpio->direction] | gpioMode[gpio->mode] | gpio->pin; if (stm32_configgpio(cfgset) != GPIO_CONFIG_OK) { return false; } return true; } bool iotjs_gpio_open(iotjs_gpio_t* gpio) { DDDLOG("%s - pin: %d, dir: %d, mode: %d", __func__, gpio->pin, gpio->direction, gpio->mode); return gpio_set_config(gpio); } bool iotjs_gpio_set_direction(iotjs_gpio_t* gpio) { return gpio_set_config(gpio); } iotjs-1.0+715/src/modules/nuttx/iotjs_module_i2c-nuttx.c000066400000000000000000000067541371177304000232300ustar00rootroot00000000000000/* 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__) #error "Module __FILE__ is for nuttx only" #endif #include #include "iotjs_systemio-nuttx.h" #include "modules/iotjs_module_i2c.h" #define I2C_DEFAULT_FREQUENCY 400000 #define I2C_DEFAULT_ADDRESS_LENGTH 7 struct iotjs_i2c_platform_data_s { int bus; struct i2c_master_s* i2c_master; struct i2c_config_s config; }; void iotjs_i2c_create_platform_data(iotjs_i2c_t* i2c) { i2c->platform_data = IOTJS_ALLOC(iotjs_i2c_platform_data_t); i2c->platform_data->i2c_master = NULL; } void iotjs_i2c_destroy_platform_data(iotjs_i2c_platform_data_t* pdata) { IOTJS_RELEASE(pdata); } jerry_value_t iotjs_i2c_set_platform_config(iotjs_i2c_t* i2c, const jerry_value_t jconfig) { iotjs_i2c_platform_data_t* platform_data = i2c->platform_data; JS_GET_REQUIRED_CONF_VALUE(jconfig, platform_data->bus, IOTJS_MAGIC_STRING_BUS, number); return jerry_create_undefined(); } #define I2C_METHOD_HEADER(arg) \ iotjs_i2c_platform_data_t* platform_data = arg->platform_data; \ IOTJS_ASSERT(platform_data); \ if (!platform_data->i2c_master) { \ DLOG("%s: I2C is not opened", __func__); \ return false; \ } bool iotjs_i2c_open(iotjs_i2c_t* i2c) { iotjs_i2c_platform_data_t* platform_data = i2c->platform_data; IOTJS_ASSERT(platform_data); platform_data->config.address = i2c->address; platform_data->config.addrlen = I2C_DEFAULT_ADDRESS_LENGTH; platform_data->i2c_master = iotjs_i2c_config_nuttx(platform_data->bus); if (!platform_data->i2c_master) { DLOG("%s : cannot open", __func__); return false; } platform_data->config.frequency = I2C_DEFAULT_FREQUENCY; return true; } bool iotjs_i2c_close(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); if (iotjs_i2c_unconfig_nuttx(platform_data->i2c_master) < 0) { DLOG("%s : cannot close", __func__); return false; } return true; } bool iotjs_i2c_write(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); uint8_t len = i2c->buf_len; uint8_t* data = (uint8_t*)i2c->buf_data; IOTJS_ASSERT(len > 0); int ret = i2c_write(platform_data->i2c_master, &platform_data->config, data, len); IOTJS_RELEASE(i2c->buf_data); if (ret < 0) { DLOG("%s : cannot write - %d", __func__, ret); return false; } return true; } bool iotjs_i2c_read(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); uint8_t len = i2c->buf_len; i2c->buf_data = iotjs_buffer_allocate(len); IOTJS_ASSERT(len > 0); int ret = i2c_read(platform_data->i2c_master, &platform_data->config, (uint8_t*)i2c->buf_data, len); if (ret != 0) { DLOG("%s : cannot read - %d", __func__, ret); return false; } return true; } iotjs-1.0+715/src/modules/nuttx/iotjs_module_pwm-nuttx.c000066400000000000000000000105561371177304000233510ustar00rootroot00000000000000/* 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 #include #include #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 struct iotjs_pwm_platform_data_s { int device_fd; }; void iotjs_pwm_create_platform_data(iotjs_pwm_t* pwm) { pwm->platform_data = IOTJS_ALLOC(iotjs_pwm_platform_data_t); pwm->platform_data->device_fd = -1; } void iotjs_pwm_destroy_platform_data(iotjs_pwm_platform_data_t* pdata) { IOTJS_RELEASE(pdata); } jerry_value_t iotjs_pwm_set_platform_config(iotjs_pwm_t* pwm, const jerry_value_t jconfig) { return jerry_create_undefined(); } static bool pwm_set_options(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; int fd = platform_data->device_fd; if (fd < 0) { DLOG("%s - file open failed", __func__); return false; } struct pwm_info_s info; // Clamp so that the value inverted fits into uint32 if (pwm->period < 2.33E-10) pwm->period = 2.33E-10; info.frequency = (uint32_t)(1.0 / pwm->period); double duty_value = pwm->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; } bool iotjs_pwm_open(iotjs_pwm_t* pwm) { int timer = SYSIO_GET_TIMER(pwm->pin); char path[PWM_DEVICE_PATH_BUFFER_SIZE] = { 0 }; if (snprintf(path, PWM_DEVICE_PATH_BUFFER_SIZE, PWM_DEVICE_PATH_FORMAT, (timer - 1)) < 0) { return false; } if (access(path, F_OK) != 0) { struct pwm_lowerhalf_s* pwm_lowerhalf = iotjs_pwm_config_nuttx(timer, pwm->pin); DDDLOG("%s - path: %s, timer: %d\n", __func__, path, timer); if (pwm_register(path, pwm_lowerhalf) != 0) { return false; } } // File open iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; platform_data->device_fd = open(path, O_RDONLY); if (platform_data->device_fd < 0) { DLOG("%s - file open failed", __func__); return false; } if (!pwm_set_options(pwm)) { return false; } return true; } bool iotjs_pwm_set_period(iotjs_pwm_t* pwm) { return pwm_set_options(pwm); } bool iotjs_pwm_set_dutycycle(iotjs_pwm_t* pwm) { return pwm_set_options(pwm); } bool iotjs_pwm_set_enable(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; int fd = platform_data->device_fd; if (fd < 0) { DLOG("%s - file open failed", __func__); return false; } DDDLOG("%s - enable: %d", __func__, pwm->enable); int ret; if (pwm->enable) { ret = ioctl(fd, PWMIOC_START, 0); } else { ret = ioctl(fd, PWMIOC_STOP, 0); } if (ret < 0) { DLOG("%s - setEnable failed", __func__); return false; } return true; } bool iotjs_pwm_close(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; int fd = platform_data->device_fd; if (fd < 0) { DLOG("%s - file not opened", __func__); return false; } DDDLOG("%s", __func__); // Close file close(fd); platform_data->device_fd = -1; uint32_t timer = SYSIO_GET_TIMER(pwm->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(pwm->pin); return true; } #endif // __NUTTX__ iotjs-1.0+715/src/modules/nuttx/iotjs_module_spi-nuttx.c000066400000000000000000000060031371177304000233310ustar00rootroot00000000000000/* 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__) #error "Module __FILE__ is for nuttx only" #endif #include #include "iotjs_systemio-nuttx.h" #include "chip.h" #include "modules/iotjs_module_spi.h" struct iotjs_spi_platform_data_s { int bus; uint32_t cs_chip; struct spi_dev_s* spi_dev; }; void iotjs_spi_create_platform_data(iotjs_spi_t* spi) { spi->platform_data = IOTJS_ALLOC(iotjs_spi_platform_data_t); spi->platform_data->bus = -1; spi->platform_data->cs_chip = 0; spi->platform_data->spi_dev = NULL; } void iotjs_spi_destroy_platform_data(iotjs_spi_platform_data_t* pdata) { IOTJS_RELEASE(pdata); } jerry_value_t iotjs_spi_set_platform_config(iotjs_spi_t* spi, const jerry_value_t jconfig) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; JS_GET_REQUIRED_CONF_VALUE(jconfig, platform_data->bus, IOTJS_MAGIC_STRING_BUS, number); return jerry_create_undefined(); } bool iotjs_spi_transfer(iotjs_spi_t* spi) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; struct spi_dev_s* spi_dev = platform_data->spi_dev; SPI_LOCK(spi_dev, true); SPI_SETFREQUENCY(spi_dev, spi->max_speed); SPI_SETMODE(spi_dev, spi->mode); SPI_SETBITS(spi_dev, spi->bits_per_word); // Select the SPI iotjs_gpio_write_nuttx(platform_data->cs_chip, false); SPI_EXCHANGE(spi_dev, spi->tx_buf_data, spi->rx_buf_data, spi->buf_len); // Unselect the SPI device iotjs_gpio_write_nuttx(platform_data->cs_chip, true); SPI_LOCK(spi_dev, false); return true; } bool iotjs_spi_close(iotjs_spi_t* spi) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; iotjs_gpio_unconfig_nuttx(platform_data->cs_chip); return true; } bool iotjs_spi_open(iotjs_spi_t* spi) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; switch (platform_data->bus) { case 1: platform_data->cs_chip = (GPIO_OUTPUT | GPIO_PUSHPULL | GPIO_SPEED_50MHz | GPIO_PORTA | GPIO_PIN15 | GPIO_OUTPUT_SET); break; default: return false; } iotjs_gpio_config_nuttx(platform_data->cs_chip); if (!(platform_data->spi_dev = iotjs_spi_config_nuttx(platform_data->bus, platform_data->cs_chip))) { DLOG("%s - SPI open failed %d", __func__, platform_data->bus); return false; } return true; } iotjs-1.0+715/src/modules/nuttx/iotjs_module_stm32f4dis-nuttx.c000066400000000000000000000153111371177304000244420ustar00rootroot00000000000000/* 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 "iotjs_def.h" #include "iotjs_systemio-nuttx.h" #include "stm32_gpio.h" #include "modules/iotjs_module_stm32f4dis.h" #if ENABLE_MODULE_ADC static void iotjs_pin_initialize_adc(jerry_value_t jobj) { unsigned int number_bit; // ADC pin name is "ADC.(number)_(timer)". #define SET_ADC_CONSTANT(number, timer) \ number_bit = (GPIO_ADC##number##_IN##timer); \ number_bit |= (ADC_NUMBER(number)); \ number_bit |= (SYSIO_TIMER_NUMBER(timer)); \ iotjs_jval_set_property_number(jobj, "ADC" #number "_" #timer, number_bit); #define SET_ADC_CONSTANT_NUMBER(number) \ SET_ADC_CONSTANT(number, 0); \ SET_ADC_CONSTANT(number, 1); \ SET_ADC_CONSTANT(number, 2); \ SET_ADC_CONSTANT(number, 3); \ SET_ADC_CONSTANT(number, 4); \ SET_ADC_CONSTANT(number, 5); \ SET_ADC_CONSTANT(number, 6); \ SET_ADC_CONSTANT(number, 7); \ SET_ADC_CONSTANT(number, 8); \ SET_ADC_CONSTANT(number, 9); \ SET_ADC_CONSTANT(number, 10); \ SET_ADC_CONSTANT(number, 11); \ SET_ADC_CONSTANT(number, 12); \ SET_ADC_CONSTANT(number, 13); \ SET_ADC_CONSTANT(number, 14); \ SET_ADC_CONSTANT(number, 15); SET_ADC_CONSTANT_NUMBER(1); SET_ADC_CONSTANT_NUMBER(2); SET_ADC_CONSTANT_NUMBER(3); #undef SET_ADC_CONSTANT_NUMBER #undef SET_ADC_CONSTANT } #endif /* ENABLE_MODULE_ADC */ #if ENABLE_MODULE_GPIO static void iotjs_pin_initialize_gpio(jerry_value_t jobj) { // Set GPIO pin from configuration bits of nuttx. // GPIO pin name is "P(port)(pin)". #define SET_GPIO_CONSTANT(port, pin) \ iotjs_jval_set_property_number(jobj, "P" #port #pin, \ (GPIO_PORT##port | GPIO_PIN##pin)); #define SET_GPIO_CONSTANT_PORT(port) \ SET_GPIO_CONSTANT(port, 0); \ SET_GPIO_CONSTANT(port, 1); \ SET_GPIO_CONSTANT(port, 2); \ SET_GPIO_CONSTANT(port, 3); \ SET_GPIO_CONSTANT(port, 4); \ SET_GPIO_CONSTANT(port, 5); \ SET_GPIO_CONSTANT(port, 6); \ SET_GPIO_CONSTANT(port, 7); \ SET_GPIO_CONSTANT(port, 8); \ SET_GPIO_CONSTANT(port, 9); \ SET_GPIO_CONSTANT(port, 10); \ SET_GPIO_CONSTANT(port, 11); \ SET_GPIO_CONSTANT(port, 12); \ SET_GPIO_CONSTANT(port, 13); \ SET_GPIO_CONSTANT(port, 14); \ SET_GPIO_CONSTANT(port, 15); SET_GPIO_CONSTANT_PORT(A); SET_GPIO_CONSTANT_PORT(B); SET_GPIO_CONSTANT_PORT(C); SET_GPIO_CONSTANT_PORT(D); SET_GPIO_CONSTANT_PORT(E); SET_GPIO_CONSTANT(H, 0); SET_GPIO_CONSTANT(H, 1); #undef SET_GPIO_CONSTANT_PORT #undef SET_GPIO_CONSTANT } #endif /* ENABLE_MODULE_GPIO */ #if ENABLE_MODULE_PWM static void iotjs_pin_initialize_pwm(jerry_value_t jobj) { unsigned int timer_bit; // Set PWM pin from configuration bits of nuttx. // PWM pin name is "PWM(timer).CH(channel)_(n)". #define SET_GPIO_CONSTANT(timer, channel, order) \ timer_bit = (GPIO_TIM##timer##_CH##channel##OUT_##order); \ timer_bit |= (SYSIO_TIMER_NUMBER(timer)); \ iotjs_jval_set_property_number(jtim##timer, "CH" #channel "_" #order, \ timer_bit); #define SET_GPIO_CONSTANT_CHANNEL(timer, channel) \ SET_GPIO_CONSTANT(timer, channel, 1); \ SET_GPIO_CONSTANT(timer, channel, 2); #define SET_GPIO_CONSTANT_TIM(timer) \ jerry_value_t jtim##timer = jerry_create_object(); \ iotjs_jval_set_property_jval(jobj, "PWM" #timer, jtim##timer); #define SET_GPIO_CONSTANT_TIM_1(timer) \ SET_GPIO_CONSTANT_TIM(timer); \ SET_GPIO_CONSTANT_CHANNEL(timer, 1); #define SET_GPIO_CONSTANT_TIM_2(timer) \ SET_GPIO_CONSTANT_TIM(timer); \ SET_GPIO_CONSTANT_CHANNEL(timer, 1); \ SET_GPIO_CONSTANT_CHANNEL(timer, 2); #define SET_GPIO_CONSTANT_TIM_4(timer) \ SET_GPIO_CONSTANT_TIM(timer); \ SET_GPIO_CONSTANT_CHANNEL(timer, 1); \ SET_GPIO_CONSTANT_CHANNEL(timer, 2); \ SET_GPIO_CONSTANT_CHANNEL(timer, 3); \ SET_GPIO_CONSTANT_CHANNEL(timer, 4); SET_GPIO_CONSTANT_TIM_4(1); // PA8, PE9, PA9, PE11, PA10, PE13, PA11, PE14 jerry_release_value(jtim1); SET_GPIO_CONSTANT_TIM_4(2); // PA0, PA15, PA1, PB3, PA2, PB10, PA3, PB11 iotjs_jval_set_property_number(jtim2, "CH1_3", GPIO_TIM2_CH1OUT_3); // PA5 jerry_release_value(jtim2); SET_GPIO_CONSTANT_TIM_4(3); // PA6, PB4, PA7, PB5, PB0, PC8, PB1, PC9 iotjs_jval_set_property_number(jtim3, "CH1_3", GPIO_TIM3_CH1OUT_3); // PC6 iotjs_jval_set_property_number(jtim3, "CH2_3", GPIO_TIM3_CH2OUT_3); // PC7 jerry_release_value(jtim3); SET_GPIO_CONSTANT_TIM_4(4); // PB6, PD12, PB7, PD13, PB8, PD14, PB9, PD15 jerry_release_value(jtim4); SET_GPIO_CONSTANT_TIM_4(5); // PA0, PH10, PA1, PH11, PA2, PH12, PA3, PI0 jerry_release_value(jtim5); SET_GPIO_CONSTANT_TIM_4(8); // PC6, PI5, PC7, PI6, PC8, PI7, PC9, PI2 jerry_release_value(jtim8); SET_GPIO_CONSTANT_TIM_2(9); // PA2, PE5, PA3, PE6 jerry_release_value(jtim9); SET_GPIO_CONSTANT_TIM_1(10); // PB8, PF6 jerry_release_value(jtim10); SET_GPIO_CONSTANT_TIM_1(11); // PB9, PF7 jerry_release_value(jtim11); SET_GPIO_CONSTANT_TIM_2(12); // PH6, PB14, PB15, PH9 jerry_release_value(jtim12); SET_GPIO_CONSTANT_TIM_1(13); // PA6, PF8 jerry_release_value(jtim13); SET_GPIO_CONSTANT_TIM_1(14); // PA7, PF9 jerry_release_value(jtim14); #undef SET_GPIO_CONSTANT_TIM_4 #undef SET_GPIO_CONSTANT_TIM_2 #undef SET_GPIO_CONSTANT_TIM_1 #undef SET_GPIO_CONSTANT_TIM #undef SET_GPIO_CONSTANT_CHANNEL #undef SET_GPIO_CONSTANT } #endif /* ENABLE_MODULE_PWM */ void iotjs_stm32f4dis_pin_initialize(jerry_value_t jobj) { jerry_value_t jpin = jerry_create_object(); iotjs_jval_set_property_jval(jobj, "pin", jpin); #if ENABLE_MODULE_ADC iotjs_pin_initialize_adc(jpin); #endif /* ENABLE_MODULE_ADC */ #if ENABLE_MODULE_GPIO iotjs_pin_initialize_gpio(jpin); #endif /* ENABLE_MODULE_GPIO */ #if ENABLE_MODULE_PWM iotjs_pin_initialize_pwm(jpin); #endif /* ENABLE_MODULE_PWM */ jerry_release_value(jpin); } #endif // __NUTTX__ iotjs-1.0+715/src/modules/nuttx/iotjs_module_stm32f7nucleo-nuttx.c000066400000000000000000000107741371177304000251630ustar00rootroot00000000000000/* Copyright 2019-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__) && defined(TARGET_BOARD_STM32F7NUCLEO) #include "iotjs_systemio-nuttx.h" #include "stm32_gpio.h" #include "iotjs_def.h" #include "modules/iotjs_module_stm32f7nucleo.h" #if ENABLE_MODULE_ADC static void iotjs_pin_initialize_adc(jerry_value_t jobj) { unsigned int number_bit; // ADC pin name is "ADC(number)_(timer)". #define SET_ADC_CONSTANT(number, timer) \ number_bit = (GPIO_ADC##number##_IN##timer); \ number_bit |= (ADC_NUMBER(number)); \ number_bit |= (SYSIO_TIMER_NUMBER(timer)); \ iotjs_jval_set_property_number(jobj, "ADC" #number "_" #timer, number_bit); #define SET_ADC_CONSTANT_NUMBER(number) SET_ADC_CONSTANT(number, 3); SET_ADC_CONSTANT_NUMBER(1); #undef SET_ADC_CONSTANT_NUMBER #undef SET_ADC_CONSTANT } #endif /* ENABLE_MODULE_ADC */ #if ENABLE_MODULE_GPIO static void iotjs_pin_initialize_gpio(jerry_value_t jobj) { // Set GPIO pin from configuration bits of nuttx. // GPIO pin name is "P(port)(pin)". #define SET_GPIO_CONSTANT(port, pin) \ iotjs_jval_set_property_number(jobj, "P" #port #pin, \ (GPIO_PORT##port | GPIO_PIN##pin)); #define SET_GPIO_CONSTANT_PORT(port) \ SET_GPIO_CONSTANT(port, 0); \ SET_GPIO_CONSTANT(port, 1); \ SET_GPIO_CONSTANT(port, 2); \ SET_GPIO_CONSTANT(port, 3); \ SET_GPIO_CONSTANT(port, 4); \ SET_GPIO_CONSTANT(port, 5); \ SET_GPIO_CONSTANT(port, 6); \ SET_GPIO_CONSTANT(port, 7); \ SET_GPIO_CONSTANT(port, 8); \ SET_GPIO_CONSTANT(port, 9); \ SET_GPIO_CONSTANT(port, 10); \ SET_GPIO_CONSTANT(port, 11); \ SET_GPIO_CONSTANT(port, 12); \ SET_GPIO_CONSTANT(port, 13); \ SET_GPIO_CONSTANT(port, 14); \ SET_GPIO_CONSTANT(port, 15); SET_GPIO_CONSTANT_PORT(A); SET_GPIO_CONSTANT_PORT(B); SET_GPIO_CONSTANT_PORT(C); SET_GPIO_CONSTANT_PORT(D); SET_GPIO_CONSTANT_PORT(E); SET_GPIO_CONSTANT(H, 0); SET_GPIO_CONSTANT(H, 1); #undef SET_GPIO_CONSTANT_PORT #undef SET_GPIO_CONSTANT } #endif /* ENABLE_MODULE_GPIO */ #if ENABLE_MODULE_PWM static void iotjs_pin_initialize_pwm(jerry_value_t jobj) { unsigned int timer_bit; // Set PWM pin from configuration bits of nuttx. // PWM pin name is "PWM(timer).CH(channel)_(n)". #define SET_GPIO_CONSTANT(timer, channel, order) \ timer_bit = (GPIO_TIM##timer##_CH##channel##OUT_##order); \ timer_bit |= (SYSIO_TIMER_NUMBER(timer)); \ iotjs_jval_set_property_number(jtim##timer, "CH" #channel "_" #order, \ timer_bit); #define SET_GPIO_CONSTANT_CHANNEL(timer, channel) \ SET_GPIO_CONSTANT(timer, channel, 1); #define SET_GPIO_CONSTANT_TIM(timer) \ jerry_value_t jtim##timer = jerry_create_object(); \ iotjs_jval_set_property_jval(jobj, "PWM" #timer, jtim##timer); #define SET_GPIO_CONSTANT_TIM_1(timer) \ SET_GPIO_CONSTANT_TIM(timer); \ SET_GPIO_CONSTANT_CHANNEL(timer, 1); SET_GPIO_CONSTANT_TIM_1(1); jerry_release_value(jtim1); SET_GPIO_CONSTANT_TIM_1(2); jerry_release_value(jtim2); SET_GPIO_CONSTANT_TIM_1(3); jerry_release_value(jtim3); SET_GPIO_CONSTANT_TIM_1(4); jerry_release_value(jtim4); #undef SET_GPIO_CONSTANT_TIM_1 #undef SET_GPIO_CONSTANT_TIM_2 #undef SET_GPIO_CONSTANT_TIM #undef SET_GPIO_CONSTANT_CHANNEL #undef SET_GPIO_CONSTANT } #endif /* ENABLE_MODULE_PWM */ void iotjs_stm32f7nucleo_pin_initialize(jerry_value_t jobj) { jerry_value_t jpin = jerry_create_object(); iotjs_jval_set_property_jval(jobj, "pin", jpin); #if ENABLE_MODULE_ADC iotjs_pin_initialize_adc(jpin); #endif /* ENABLE_MODULE_ADC */ #if ENABLE_MODULE_GPIO iotjs_pin_initialize_gpio(jpin); #endif /* ENABLE_MODULE_GPIO */ #if ENABLE_MODULE_PWM iotjs_pin_initialize_pwm(jpin); #endif /* ENABLE_MODULE_PWM */ jerry_release_value(jpin); } #endif // __NUTTX__ iotjs-1.0+715/src/modules/nuttx/iotjs_module_uart-nuttx.c000066400000000000000000000053571371177304000235240ustar00rootroot00000000000000/* 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 "modules/iotjs_module_uart.h" #include "iotjs_uv_handle.h" struct iotjs_uart_platform_data_s { iotjs_string_t device_path; }; void iotjs_uart_create_platform_data(iotjs_uart_t* uart) { uart->platform_data = IOTJS_ALLOC(iotjs_uart_platform_data_t); } void iotjs_uart_destroy_platform_data( iotjs_uart_platform_data_t* platform_data) { IOTJS_ASSERT(platform_data); iotjs_string_destroy(&platform_data->device_path); IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_uart_set_platform_config(iotjs_uart_t* uart, const jerry_value_t jconfig) { JS_GET_REQUIRED_CONF_VALUE(jconfig, uart->platform_data->device_path, IOTJS_MAGIC_STRING_DEVICE, string); return jerry_create_undefined(); } bool iotjs_uart_open(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); int fd = open(iotjs_string_data(&uart->platform_data->device_path), O_RDWR | O_NOCTTY | O_NDELAY); if (fd < 0) { return false; } uart->device_fd = fd; iotjs_uart_register_read_cb((uv_poll_t*)uart); return true; } bool iotjs_uart_write(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); int bytesWritten = 0; unsigned offset = 0; int fd = uart->device_fd; const char* buf_data = iotjs_string_data(&uart->buf_data); DDDLOG("%s - data: %s", __func__, buf_data); do { errno = 0; bytesWritten = write(fd, buf_data + offset, uart->buf_len - offset); DDDLOG("%s - size: %d", __func__, uart->buf_len - offset); if (bytesWritten != -1) { offset += (unsigned)bytesWritten; continue; } if (errno == EINTR) { continue; } return false; } while (uart->buf_len > offset); return true; } void iotjs_uart_handle_close_cb(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); if (close(uart->device_fd) < 0) { DLOG(iotjs_periph_error_str(kUartOpClose)); IOTJS_ASSERT(0); } } iotjs-1.0+715/src/modules/tizen/000077500000000000000000000000001371177304000164055ustar00rootroot00000000000000iotjs-1.0+715/src/modules/tizen/iotjs_module_gpio-tizen.c000066400000000000000000000064541371177304000234240ustar00rootroot00000000000000/* 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 #include #include "modules/iotjs_module_gpio.h" struct iotjs_gpio_platform_data_s { peripheral_gpio_h peripheral_gpio; }; void iotjs_gpio_create_platform_data(iotjs_gpio_t* gpio) { gpio->platform_data = IOTJS_ALLOC(iotjs_gpio_platform_data_t); } void iotjs_gpio_destroy_platform_data( iotjs_gpio_platform_data_t* platform_data) { IOTJS_RELEASE(platform_data); } bool iotjs_gpio_write(iotjs_gpio_t* gpio) { int retVal = peripheral_gpio_write(gpio->platform_data->peripheral_gpio, gpio->value); return PERIPHERAL_ERROR_NONE == retVal; } bool iotjs_gpio_read(iotjs_gpio_t* gpio) { uint32_t value; int retVal = peripheral_gpio_read(gpio->platform_data->peripheral_gpio, &value); if (retVal != PERIPHERAL_ERROR_NONE) { return false; } gpio->value = (bool)value; return true; } bool iotjs_gpio_close(iotjs_gpio_t* gpio) { peripheral_gpio_close(gpio->platform_data->peripheral_gpio); return true; } bool iotjs_gpio_open(iotjs_gpio_t* gpio) { peripheral_gpio_h _gpio; int retVal = peripheral_gpio_open((int)gpio->pin, &_gpio); if (retVal != PERIPHERAL_ERROR_NONE) { return false; } gpio->platform_data->peripheral_gpio = _gpio; peripheral_gpio_direction_e _direction; if (gpio->direction == kGpioDirectionIn) { _direction = PERIPHERAL_GPIO_DIRECTION_IN; } else { _direction = PERIPHERAL_GPIO_DIRECTION_OUT_INITIALLY_LOW; } retVal = peripheral_gpio_set_direction(_gpio, _direction); if (retVal != PERIPHERAL_ERROR_NONE) { return false; } // Mode is not supported by Peripheral API for Tizen peripheral_gpio_edge_e _edge; switch (gpio->edge) { case kGpioEdgeNone: _edge = PERIPHERAL_GPIO_EDGE_NONE; break; case kGpioEdgeRising: _edge = PERIPHERAL_GPIO_EDGE_RISING; break; case kGpioEdgeFalling: _edge = PERIPHERAL_GPIO_EDGE_FALLING; break; case kGpioEdgeBoth: _edge = PERIPHERAL_GPIO_EDGE_BOTH; break; default: _edge = PERIPHERAL_GPIO_EDGE_NONE; } retVal = peripheral_gpio_set_edge_mode(_gpio, _edge); if (retVal != PERIPHERAL_ERROR_NONE) { return false; } return true; } bool iotjs_gpio_set_direction(iotjs_gpio_t* gpio) { peripheral_gpio_direction_e direction; if (gpio->direction == kGpioDirectionIn) { direction = PERIPHERAL_GPIO_DIRECTION_IN; } else { direction = PERIPHERAL_GPIO_DIRECTION_OUT_INITIALLY_LOW; } int ret = peripheral_gpio_set_direction(gpio->platform_data->peripheral_gpio, direction); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s, Cannot set direction(%d).", __func__, ret); return false; } return true; } iotjs-1.0+715/src/modules/tizen/iotjs_module_i2c-tizen.c000066400000000000000000000063541371177304000231420ustar00rootroot00000000000000/* Copyright 2018-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(__TIZEN__) #error "Module __FILE__ is for Tizen only" #endif #include #include "modules/iotjs_module_i2c.h" struct iotjs_i2c_platform_data_s { int bus; peripheral_i2c_h i2c_h; }; void iotjs_i2c_create_platform_data(iotjs_i2c_t* i2c) { i2c->platform_data = IOTJS_ALLOC(iotjs_i2c_platform_data_t); i2c->platform_data->i2c_h = NULL; } void iotjs_i2c_destroy_platform_data(iotjs_i2c_platform_data_t* pdata) { IOTJS_RELEASE(pdata); } jerry_value_t iotjs_i2c_set_platform_config(iotjs_i2c_t* i2c, const jerry_value_t jconfig) { iotjs_i2c_platform_data_t* platform_data = i2c->platform_data; JS_GET_REQUIRED_CONF_VALUE(jconfig, platform_data->bus, IOTJS_MAGIC_STRING_BUS, number); return jerry_create_undefined(); } #define I2C_METHOD_HEADER(arg) \ iotjs_i2c_platform_data_t* platform_data = arg->platform_data; \ IOTJS_ASSERT(platform_data); \ if (!platform_data->i2c_h) { \ DLOG("%s: I2C is not opened", __func__); \ return false; \ } bool iotjs_i2c_open(iotjs_i2c_t* i2c) { iotjs_i2c_platform_data_t* platform_data = i2c->platform_data; IOTJS_ASSERT(platform_data); int ret = peripheral_i2c_open(platform_data->bus, i2c->address, &platform_data->i2c_h); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s : cannot open(%d)", __func__, ret); return false; } return true; } bool iotjs_i2c_close(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); int ret = peripheral_i2c_close(platform_data->i2c_h); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s : cannot close(%d)", __func__, ret); return false; } return true; } bool iotjs_i2c_write(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); IOTJS_ASSERT(i2c->buf_len > 0); int ret = peripheral_i2c_write(platform_data->i2c_h, (uint8_t*)i2c->buf_data, i2c->buf_len); IOTJS_RELEASE(i2c->buf_data); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s : cannot write(%d)", __func__, ret); return false; } return true; } bool iotjs_i2c_read(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); uint8_t len = i2c->buf_len; i2c->buf_data = iotjs_buffer_allocate(len); IOTJS_ASSERT(len > 0); int ret = peripheral_i2c_read(platform_data->i2c_h, (uint8_t*)i2c->buf_data, len); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s : cannot read(%d)", __func__, ret); return false; } return true; } iotjs-1.0+715/src/modules/tizen/iotjs_module_pwm-tizen.c000066400000000000000000000065731371177304000232730ustar00rootroot00000000000000/* Copyright 2018-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 #include "modules/iotjs_module_pwm.h" struct iotjs_pwm_platform_data_s { peripheral_pwm_h pwm_h; }; void iotjs_pwm_create_platform_data(iotjs_pwm_t* pwm) { pwm->platform_data = IOTJS_ALLOC(iotjs_pwm_platform_data_t); pwm->platform_data->pwm_h = NULL; } void iotjs_pwm_destroy_platform_data(iotjs_pwm_platform_data_t* pdata) { IOTJS_RELEASE(pdata); } jerry_value_t iotjs_pwm_set_platform_config(iotjs_pwm_t* pwm, const jerry_value_t jconfig) { return jerry_create_undefined(); } static bool pwm_set_options(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; if (platform_data->pwm_h == NULL) { DLOG("%s - cannot set options", __func__); return false; } return iotjs_pwm_set_period(pwm) && iotjs_pwm_set_dutycycle(pwm); } bool iotjs_pwm_open(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; int ret = peripheral_pwm_open(0, (int)pwm->pin, &platform_data->pwm_h); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s : cannot open(%d)", __func__, ret); return false; } return pwm_set_options(pwm); } #define PWM_METHOD_HEADER \ IOTJS_ASSERT(pwm && pwm->platform_data); \ iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; \ if (platform_data->pwm_h == NULL) { \ DLOG("%s: PWM is not opened", __func__); \ return false; \ } bool iotjs_pwm_set_period(iotjs_pwm_t* pwm) { PWM_METHOD_HEADER uint32_t period_ns = pwm->period * 1E9; int ret = peripheral_pwm_set_period(platform_data->pwm_h, period_ns); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s : cannot set period(%d)", __func__, ret); return false; } return true; } bool iotjs_pwm_set_dutycycle(iotjs_pwm_t* pwm) { PWM_METHOD_HEADER uint32_t duty_cycle_ns = pwm->period * pwm->duty_cycle * 1E9; int ret = peripheral_pwm_set_duty_cycle(platform_data->pwm_h, duty_cycle_ns); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s : cannot set duty-cycle(%d)", __func__, ret); return false; } return true; } bool iotjs_pwm_set_enable(iotjs_pwm_t* pwm) { PWM_METHOD_HEADER int ret = peripheral_pwm_set_enabled(platform_data->pwm_h, pwm->enable); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s : cannot set enable(%d)", __func__, ret); return false; } return true; } bool iotjs_pwm_close(iotjs_pwm_t* pwm) { PWM_METHOD_HEADER int ret = peripheral_pwm_close(platform_data->pwm_h); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s : cannot close(%d)", __func__, ret); return false; } platform_data->pwm_h = NULL; return true; } iotjs-1.0+715/src/modules/tizen/iotjs_module_spi-tizen.c000066400000000000000000000111721371177304000232520ustar00rootroot00000000000000/* Copyright 2018-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 #include "modules/iotjs_module_spi.h" struct iotjs_spi_platform_data_s { int bus; peripheral_spi_h spi_h; }; static peripheral_spi_mode_e mode_to_constant(SpiMode mode) { switch (mode) { case kSpiMode_0: return PERIPHERAL_SPI_MODE_0; case kSpiMode_1: return PERIPHERAL_SPI_MODE_1; case kSpiMode_2: return PERIPHERAL_SPI_MODE_2; case kSpiMode_3: return PERIPHERAL_SPI_MODE_3; default: IOTJS_ASSERT(!"Invalid SPI mode"); return PERIPHERAL_SPI_MODE_0; } } static peripheral_spi_bit_order_e bit_order_to_constant(SpiOrder order) { switch (order) { case kSpiOrderLsb: return PERIPHERAL_SPI_BIT_ORDER_LSB; case kSpiOrderMsb: return PERIPHERAL_SPI_BIT_ORDER_MSB; default: IOTJS_ASSERT(!"Invalid SPI bitOrder"); return PERIPHERAL_SPI_BIT_ORDER_MSB; } } void iotjs_spi_create_platform_data(iotjs_spi_t* spi) { spi->platform_data = IOTJS_ALLOC(iotjs_spi_platform_data_t); spi->platform_data->spi_h = NULL; } void iotjs_spi_destroy_platform_data(iotjs_spi_platform_data_t* platform_data) { IOTJS_ASSERT(platform_data); IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_spi_set_platform_config(iotjs_spi_t* spi, const jerry_value_t jconfig) { JS_GET_REQUIRED_CONF_VALUE(jconfig, spi->platform_data->bus, IOTJS_MAGIC_STRING_BUS, number); return jerry_create_undefined(); } #define SPI_METHOD_HEADER(arg) \ iotjs_spi_platform_data_t* platform_data = arg->platform_data; \ IOTJS_ASSERT(platform_data); \ if (!platform_data->spi_h) { \ DLOG("%s: SPI is not opened", __func__); \ return false; \ } bool iotjs_spi_open(iotjs_spi_t* spi) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; int ret = peripheral_spi_open(platform_data->bus, spi->chip_select, &platform_data->spi_h); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot open(%d)", __func__, ret); return false; } // Set mode ret = peripheral_spi_set_mode(platform_data->spi_h, mode_to_constant(spi->mode)); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot set mode(%d)", __func__, ret); peripheral_spi_close(platform_data->spi_h); return false; } // Set bit order ret = peripheral_spi_set_bit_order(platform_data->spi_h, bit_order_to_constant(spi->bit_order)); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot set bit order(%d)", __func__, ret); peripheral_spi_close(platform_data->spi_h); return false; } // Set bits per word ret = peripheral_spi_set_bits_per_word(platform_data->spi_h, spi->bits_per_word); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot set bit per word(%d)", __func__, ret); peripheral_spi_close(platform_data->spi_h); return false; } // Set maxSpeed ret = peripheral_spi_set_frequency(platform_data->spi_h, spi->max_speed); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot set maxSpeed(%d)", __func__, ret); peripheral_spi_close(platform_data->spi_h); return false; } return true; } bool iotjs_spi_transfer(iotjs_spi_t* spi) { SPI_METHOD_HEADER(spi) int ret = peripheral_spi_transfer(platform_data->spi_h, (uint8_t*)spi->tx_buf_data, (uint8_t*)spi->rx_buf_data, spi->buf_len); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot transfer(%d)", __func__, ret); return false; } return true; } bool iotjs_spi_close(iotjs_spi_t* spi) { SPI_METHOD_HEADER(spi) int ret = peripheral_spi_close(platform_data->spi_h); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot close(%d)", __func__, ret); return false; } platform_data->spi_h = NULL; return true; } iotjs-1.0+715/src/modules/tizen/iotjs_module_tizen-tizen.c000066400000000000000000000174411371177304000236150ustar00rootroot00000000000000/* Copyright 2018-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 "modules/iotjs_module_bridge.h" #include #include typedef enum { IOTJS_ERROR_RESULT_FAILED = INT_MIN, IOTJS_ERROR_INVALID_PARAMETER, IOTJS_ERROR_OUT_OF_MEMORY, IOTJS_ERROR_NONE = 0, } iotjs_error_t; // # tizen app-control #include #include #include #include static iotjs_error_t tizen_send_launch_request(const char* json, void* hbridge) { DDDLOG("%s", __func__); bundle* b; int ret; ret = bundle_from_json(json, &b); if (ret != BUNDLE_ERROR_NONE) { DDLOG("bundle_from_json failed"); return IOTJS_ERROR_INVALID_PARAMETER; } app_control_h app_control = NULL; app_control_create(&app_control); app_control_import_from_bundle(app_control, b); ret = app_control_send_launch_request(app_control, NULL, NULL); if (ret != APP_CONTROL_ERROR_NONE) { DDDLOG("app_control_send_launch_request failed"); switch (ret) { case APP_CONTROL_ERROR_INVALID_PARAMETER: iotjs_bridge_set_err(hbridge, "APP_CONTROL_ERROR_INVALID_PARAMETER"); break; case APP_CONTROL_ERROR_OUT_OF_MEMORY: iotjs_bridge_set_err(hbridge, "APP_CONTROL_ERROR_OUT_OF_MEMORY"); break; case APP_CONTROL_ERROR_APP_NOT_FOUND: iotjs_bridge_set_err(hbridge, "APP_CONTROL_ERROR_APP_NOT_FOUND"); break; case APP_CONTROL_ERROR_LAUNCH_REJECTED: iotjs_bridge_set_err(hbridge, "APP_CONTROL_ERROR_LAUNCH_REJECTED"); break; case APP_CONTROL_ERROR_LAUNCH_FAILED: iotjs_bridge_set_err(hbridge, "APP_CONTROL_ERROR_LAUNCH_FAILED"); break; case APP_CONTROL_ERROR_TIMED_OUT: iotjs_bridge_set_err(hbridge, "APP_CONTROL_ERROR_TIMED_OUT"); break; case APP_CONTROL_ERROR_PERMISSION_DENIED: iotjs_bridge_set_err(hbridge, "APP_CONTROL_ERROR_PERMISSION_DENIED"); break; default: iotjs_bridge_set_err(hbridge, "APP_CONTROL_ERROR_UNKNOWN"); break; } return IOTJS_ERROR_RESULT_FAILED; } bundle_free(b); app_control_destroy(app_control); return IOTJS_ERROR_NONE; } void iotjs_tizen_app_control_cb(app_control_h app_control, void* user_data) { DDDLOG("%s", __func__); iotjs_environment_t* env = iotjs_environment_get(); if (env->state != kRunningMain && env->state != kRunningLoop) { return; } const char* event_emitter_name = IOTJS_MAGIC_STRING_TIZEN; const char* event_name = IOTJS_MAGIC_STRING_APP_CONTROL; jerry_value_t tizen = iotjs_module_get(event_emitter_name); jerry_value_t fn = iotjs_jval_get_property(tizen, IOTJS_MAGIC_STRING_EMIT); if (jerry_value_is_function(fn) == false) { DDDLOG("tizen module is not loaded"); goto exit; } // parse app control char* json = NULL; bundle* b = NULL; app_control_export_as_bundle(app_control, &b); if (BUNDLE_ERROR_NONE != bundle_to_json(b, &json)) { DDLOG("bundle_to_json failed"); bundle_free(b); return; } DDDLOG("JSON: %s", json); // call emit jerry_value_t jargv[2] = { jerry_create_string( (const jerry_char_t*)event_name), jerry_create_string((const jerry_char_t*)json) }; iotjs_invoke_callback(fn, tizen, jargv, 2); jerry_release_value(jargv[0]); jerry_release_value(jargv[1]); free(json); bundle_free(b); exit: jerry_release_value(fn); } // # tizen bridge void iotjs_tizen_func(const char* command, const char* message, void* handle) { DDDLOG("%s, cmd: %s, msg: %s", __func__, command, message); if (strncmp(command, "getResPath", strlen("getResPath")) == 0) { char* app_res_path = app_get_resource_path(); iotjs_bridge_set_msg(handle, app_res_path); if (app_res_path != NULL) { free(app_res_path); } } else if (strncmp(command, "getDataPath", strlen("getDataPath")) == 0) { char* app_data_path = app_get_data_path(); iotjs_bridge_set_msg(handle, app_data_path); if (app_data_path != NULL) { free(app_data_path); } } else if (strncmp(command, "launchAppControl", strlen("launchAppControl")) == 0) { iotjs_error_t err = tizen_send_launch_request(message, handle); if (err == IOTJS_ERROR_NONE) { iotjs_bridge_set_msg(handle, "OK"); } } else { iotjs_bridge_set_err(handle, "Can't find command"); } } // # tizen bridge-native typedef void (*user_callback_t)(int error, const char* data); typedef struct { uv_async_t async; char* module; char* fn_name; char* message; user_callback_t cb; } iotjs_call_jfunc_t; static char* create_string_buffer(const char* src, size_t size) { char* dest = IOTJS_CALLOC(size + 1, char); strncpy(dest, src, size); dest[size] = '\0'; // just for being sure return dest; } static bool bridge_native_call(const char* module_name, const char* func_name, const char* message, iotjs_string_t* output_str) { bool result = false; jerry_value_t jmodule = iotjs_module_get(module_name); jerry_value_t jfunc = iotjs_jval_get_property(jmodule, func_name); if (jerry_value_is_function(jfunc) == false) { return result; } jerry_value_t jval = jerry_create_string((const jerry_char_t*)message); jerry_value_t jres = iotjs_invoke_callback_with_result(jfunc, jmodule, &jval, 1); if (jerry_value_is_string(jres)) { IOTJS_ASSERT(output_str != NULL); *output_str = iotjs_jval_as_string(jres); result = true; } jerry_release_value(jfunc); jerry_release_value(jres); jerry_release_value(jval); return result; } static void bridge_native_async_handler(uv_async_t* handle) { DDDLOG("%s\n", __func__); iotjs_call_jfunc_t* data = (iotjs_call_jfunc_t*)handle->data; bool result; iotjs_string_t output; result = bridge_native_call(IOTJS_MAGIC_STRING_TIZEN, data->fn_name, data->message, &output); if (data->cb) { data->cb((int)!result, iotjs_string_data(&output)); } iotjs_string_destroy(&output); // release uv_close((uv_handle_t*)&data->async, NULL); IOTJS_RELEASE(data->module); IOTJS_RELEASE(data->fn_name); IOTJS_RELEASE(data->message); IOTJS_RELEASE(data); } int iotjs_tizen_bridge_native(const char* fn_name, unsigned fn_name_size, const char* message, unsigned message_size, user_callback_t cb) { iotjs_environment_t* env = iotjs_environment_get(); if (env->state != kRunningMain && env->state != kRunningLoop) { return IOTJS_ERROR_RESULT_FAILED; } iotjs_call_jfunc_t* handle = IOTJS_ALLOC(iotjs_call_jfunc_t); if (handle == NULL) { return IOTJS_ERROR_OUT_OF_MEMORY; } handle->async.data = (void*)handle; handle->fn_name = create_string_buffer(fn_name, fn_name_size); handle->message = create_string_buffer(message, message_size); handle->module = create_string_buffer(IOTJS_MAGIC_STRING_TIZEN, sizeof(IOTJS_MAGIC_STRING_TIZEN)); handle->cb = cb; uv_loop_t* loop = iotjs_environment_loop(env); uv_async_init(loop, &handle->async, bridge_native_async_handler); uv_async_send(&handle->async); return IOTJS_ERROR_NONE; } iotjs-1.0+715/src/modules/tizen/iotjs_module_uart-tizen.c000066400000000000000000000125471371177304000234410ustar00rootroot00000000000000/* Copyright 2018-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 #include "iotjs_uv_handle.h" #include "modules/iotjs_module_uart.h" struct _peripheral_uart_s { unsigned handle; int fd; }; struct iotjs_uart_platform_data_s { peripheral_uart_h uart_h; uint8_t port; }; static peripheral_uart_baud_rate_e baud_to_constant(unsigned baudRate) { switch (baudRate) { case 0: return PERIPHERAL_UART_BAUD_RATE_0; case 50: return PERIPHERAL_UART_BAUD_RATE_50; case 75: return PERIPHERAL_UART_BAUD_RATE_75; case 110: return PERIPHERAL_UART_BAUD_RATE_110; case 134: return PERIPHERAL_UART_BAUD_RATE_134; case 150: return PERIPHERAL_UART_BAUD_RATE_150; case 200: return PERIPHERAL_UART_BAUD_RATE_200; case 300: return PERIPHERAL_UART_BAUD_RATE_300; case 600: return PERIPHERAL_UART_BAUD_RATE_600; case 1200: return PERIPHERAL_UART_BAUD_RATE_1200; case 1800: return PERIPHERAL_UART_BAUD_RATE_1800; case 2400: return PERIPHERAL_UART_BAUD_RATE_2400; case 4800: return PERIPHERAL_UART_BAUD_RATE_4800; case 9600: return PERIPHERAL_UART_BAUD_RATE_9600; case 19200: return PERIPHERAL_UART_BAUD_RATE_19200; case 38400: return PERIPHERAL_UART_BAUD_RATE_38400; case 57600: return PERIPHERAL_UART_BAUD_RATE_57600; case 115200: return PERIPHERAL_UART_BAUD_RATE_115200; case 230400: return PERIPHERAL_UART_BAUD_RATE_230400; } IOTJS_ASSERT(!"Invalid baud rate"); return -1; } static peripheral_uart_byte_size_e databits_to_constant(uint8_t dataBits) { switch (dataBits) { case 8: return PERIPHERAL_UART_BYTE_SIZE_8BIT; case 7: return PERIPHERAL_UART_BYTE_SIZE_7BIT; case 6: return PERIPHERAL_UART_BYTE_SIZE_6BIT; case 5: return PERIPHERAL_UART_BYTE_SIZE_5BIT; } IOTJS_ASSERT(!"Invalid data bits"); return -1; } void iotjs_uart_create_platform_data(iotjs_uart_t* uart) { uart->platform_data = IOTJS_ALLOC(iotjs_uart_platform_data_t); uart->platform_data->uart_h = NULL; } void iotjs_uart_destroy_platform_data( iotjs_uart_platform_data_t* platform_data) { IOTJS_ASSERT(platform_data); IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_uart_set_platform_config(iotjs_uart_t* uart, const jerry_value_t jconfig) { JS_GET_REQUIRED_CONF_VALUE(jconfig, uart->platform_data->port, IOTJS_MAGIC_STRING_PORT, number); return jerry_create_undefined(); } bool iotjs_uart_open(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); iotjs_uart_platform_data_t* platform_data = uart->platform_data; IOTJS_ASSERT(platform_data); int ret = peripheral_uart_open(platform_data->port, &platform_data->uart_h); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot open(%d)", __func__, ret); return false; } // Set baud rate ret = peripheral_uart_set_baud_rate(platform_data->uart_h, baud_to_constant(uart->baud_rate)); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot set baud rate(%d)", __func__, ret); peripheral_uart_close(platform_data->uart_h); return false; } // Set data bits ret = peripheral_uart_set_byte_size(platform_data->uart_h, databits_to_constant(uart->data_bits)); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot set data bits(%d)", __func__, ret); peripheral_uart_close(platform_data->uart_h); return false; } uart->device_fd = platform_data->uart_h->fd; iotjs_uart_register_read_cb((uv_poll_t*)uart_poll_handle); return true; } bool iotjs_uart_write(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); iotjs_uart_platform_data_t* platform_data = uart->platform_data; IOTJS_ASSERT(platform_data); if (!platform_data->uart_h) { DLOG("%s: UART is not opened", __func__); return false; } const char* buf_data = iotjs_string_data(&uart->buf_data); DDDLOG("%s: data: %s", __func__, buf_data); int ret = peripheral_uart_write(platform_data->uart_h, (uint8_t*)buf_data, uart->buf_len); if (ret != PERIPHERAL_ERROR_NONE) { DLOG("%s: cannot write(%d)", __func__, ret); return false; } return true; } void iotjs_uart_handle_close_cb(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); if (peripheral_uart_close(uart->platform_data->uart_h) != PERIPHERAL_ERROR_NONE) { DLOG("%s: error(%s) ", __func__, iotjs_periph_error_str(kUartOpClose)); IOTJS_ASSERT(0); } uart->platform_data->uart_h = NULL; } iotjs-1.0+715/src/modules/tizenrt/000077500000000000000000000000001371177304000167535ustar00rootroot00000000000000iotjs-1.0+715/src/modules/tizenrt/iotjs_module_adc-tizenrt.c000066400000000000000000000071011371177304000241170ustar00rootroot00000000000000/* 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(__TIZENRT__) #error "Module __FILE__ is for TizenRT only" #endif #include #include #include #include #include #include #include "iotjs_def.h" #include "modules/iotjs_module_adc.h" #define S5J_ADC_MAX_CHANNELS 4 struct iotjs_adc_platform_data_s { int32_t device_fd; uint32_t pin; }; // There is one file for all ADC inputs so wee need one common file descriptor static int32_t device_fd; // This is simple ref counter. Each time ADC is opened, it is increased. static size_t device_fd_counter = 0; // Path of ADC device. #define TIZENRT_ADC_DEVICE "/dev/adc0" void iotjs_adc_create_platform_data(iotjs_adc_t* adc) { adc->platform_data = IOTJS_ALLOC(iotjs_adc_platform_data_t); adc->platform_data->device_fd = -1; adc->platform_data->pin = 0; } void iotjs_adc_destroy_platform_data(iotjs_adc_platform_data_t* platform_data) { IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_adc_set_platform_config(iotjs_adc_t* adc, const jerry_value_t jconfig) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; JS_GET_REQUIRED_CONF_VALUE(jconfig, platform_data->pin, IOTJS_MAGIC_STRING_PIN, number); return jerry_create_undefined(); } bool iotjs_adc_read(iotjs_adc_t* adc) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; int ret, nbytes; size_t readsize, i, nsamples; struct adc_msg_s samples[S5J_ADC_MAX_CHANNELS]; ret = ioctl(platform_data->device_fd, ANIOC_TRIGGER, 0); if (ret < 0) { adc->value = -1; return false; } readsize = sizeof(samples); while (true) { nbytes = read(platform_data->device_fd, samples, readsize); if (nbytes > 0) { nsamples = (size_t)nbytes / sizeof(struct adc_msg_s); int sample = -1; for (i = 0; i < nsamples; ++i) { if (platform_data->pin == samples[i].am_channel) { sample = samples[i].am_data; } } if (sample != -1) { adc->value = sample; return true; } } /* else { // The read function is blocking but there are events, // which can interrupt it. The function will return // non-positive number of obtained samples. We can ignore it and // wait for next samples returned from ADC. } */ } } bool iotjs_adc_close(iotjs_adc_t* adc) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; if (platform_data->device_fd > 0) { device_fd_counter--; } if (device_fd_counter == 0) { close(platform_data->device_fd); } return true; } bool iotjs_adc_open(iotjs_adc_t* adc) { iotjs_adc_platform_data_t* platform_data = adc->platform_data; if (device_fd_counter == 0) { device_fd = open(TIZENRT_ADC_DEVICE, O_RDONLY); } platform_data->device_fd = device_fd; if (platform_data->device_fd < 0) { return false; } device_fd_counter++; return true; } iotjs-1.0+715/src/modules/tizenrt/iotjs_module_gpio-tizenrt.c000066400000000000000000000055501371177304000243340ustar00rootroot00000000000000/* 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 #include #include "modules/iotjs_module_gpio.h" struct iotjs_gpio_platform_data_s { iotbus_gpio_context_h gpio_context; }; void iotjs_gpio_create_platform_data(iotjs_gpio_t* gpio) { gpio->platform_data = IOTJS_ALLOC(iotjs_gpio_platform_data_t); } void iotjs_gpio_destroy_platform_data( iotjs_gpio_platform_data_t* platform_data) { IOTJS_RELEASE(platform_data); } bool iotjs_gpio_open(iotjs_gpio_t* gpio) { DDDLOG("%s - pin: %d, direction: %d, mode: %d", __func__, gpio->pin, gpio->direction, gpio->mode); iotbus_gpio_context_h gpio_context = iotbus_gpio_open((int)gpio->pin); if (gpio_context == NULL) { iotbus_gpio_close(gpio_context); return false; } // Set direction iotbus_gpio_direction_e direction; if (gpio->direction == kGpioDirectionIn) { direction = IOTBUS_GPIO_DIRECTION_IN; } else if (gpio->direction == kGpioDirectionOut) { direction = IOTBUS_GPIO_DIRECTION_OUT; } else { direction = IOTBUS_GPIO_DIRECTION_NONE; } if (iotbus_gpio_set_direction(gpio_context, direction) < 0) { iotbus_gpio_close(gpio_context); return false; } gpio->platform_data->gpio_context = gpio_context; return true; } bool iotjs_gpio_write(iotjs_gpio_t* gpio) { if (iotbus_gpio_write(gpio->platform_data->gpio_context, gpio->value) < 0) { return false; } return true; } bool iotjs_gpio_read(iotjs_gpio_t* gpio) { int ret = iotbus_gpio_read(gpio->platform_data->gpio_context); if (ret < 0) { DLOG("%s, Cannot read value(%d).", __func__, ret); return false; } gpio->value = (bool)ret; return true; } bool iotjs_gpio_close(iotjs_gpio_t* gpio) { if (gpio->platform_data->gpio_context && iotbus_gpio_close(gpio->platform_data->gpio_context) < 0) { return false; } return true; } bool iotjs_gpio_set_direction(iotjs_gpio_t* gpio) { iotbus_gpio_direction_e direction; if (gpio->direction == kGpioDirectionIn) { direction = IOTBUS_GPIO_DIRECTION_IN; } else { direction = IOTBUS_GPIO_DIRECTION_OUT; } int ret = iotbus_gpio_set_direction(gpio->platform_data->gpio_context, direction); if (ret != 0) { DLOG("%s, Cannot set direction(%d).", __func__, ret); return false; } return true; } iotjs-1.0+715/src/modules/tizenrt/iotjs_module_i2c-tizenrt.c000066400000000000000000000072341371177304000240540ustar00rootroot00000000000000/* 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(__TIZENRT__) #error "Module __FILE__ is for TizenRT only" #endif #include #if !defined(CONFIG_I2C) #error "\n\nTizenRT CONFIG_I2C configuration flag required for I2C module\n\n" #endif #include #include "modules/iotjs_module_i2c.h" struct iotjs_i2c_platform_data_s { int bus; iotbus_i2c_context_h i2c_context; }; void iotjs_i2c_create_platform_data(iotjs_i2c_t* i2c) { i2c->platform_data = IOTJS_ALLOC(iotjs_i2c_platform_data_t); i2c->platform_data->i2c_context = NULL; } void iotjs_i2c_destroy_platform_data(iotjs_i2c_platform_data_t* platform_data) { IOTJS_ASSERT(platform_data); IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_i2c_set_platform_config(iotjs_i2c_t* i2c, const jerry_value_t jconfig) { iotjs_i2c_platform_data_t* platform_data = i2c->platform_data; JS_GET_REQUIRED_CONF_VALUE(jconfig, platform_data->bus, IOTJS_MAGIC_STRING_BUS, number); return jerry_create_undefined(); } #define I2C_METHOD_HEADER(arg) \ iotjs_i2c_platform_data_t* platform_data = arg->platform_data; \ IOTJS_ASSERT(platform_data); \ if (!platform_data->i2c_context) { \ DLOG("%s: I2C is not opened", __func__); \ return false; \ } bool iotjs_i2c_open(iotjs_i2c_t* i2c) { iotjs_i2c_platform_data_t* platform_data = i2c->platform_data; IOTJS_ASSERT(platform_data); // Init i2c context platform_data->i2c_context = iotbus_i2c_init(platform_data->bus); if (!platform_data->i2c_context) { DLOG("%s: cannot open I2C", __func__); return false; } // Set i2c frequency int ret = iotbus_i2c_set_frequency(platform_data->i2c_context, IOTBUS_I2C_STD); if (ret < 0) { DLOG("%s: cannot set frequency", __func__); return false; } if (iotbus_i2c_set_address(platform_data->i2c_context, i2c->address) < 0) { DLOG("%s: cannot set address", __func__); return false; } return true; } bool iotjs_i2c_close(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); if (iotbus_i2c_stop(platform_data->i2c_context) < 0) { DLOG("%s: cannot close I2C", __func__); return false; } return true; } bool iotjs_i2c_write(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); uint8_t len = i2c->buf_len; IOTJS_ASSERT(len > 0); uint8_t* data = (uint8_t*)i2c->buf_data; int ret = iotbus_i2c_write(platform_data->i2c_context, data, len); IOTJS_RELEASE(i2c->buf_data); if (ret < 0) { DLOG("%s: cannot write data", __func__); return false; } return true; } bool iotjs_i2c_read(iotjs_i2c_t* i2c) { I2C_METHOD_HEADER(i2c); uint8_t len = i2c->buf_len; i2c->buf_data = iotjs_buffer_allocate(len); IOTJS_ASSERT(len > 0); if (iotbus_i2c_read(platform_data->i2c_context, (uint8_t*)i2c->buf_data, len) < 0) { DLOG("%s: cannot read data", __func__); return false; } return true; } iotjs-1.0+715/src/modules/tizenrt/iotjs_module_pwm-tizenrt.c000066400000000000000000000071601371177304000242000ustar00rootroot00000000000000/* 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(__TIZENRT__) #include #include #include #include #include "modules/iotjs_module_pwm.h" struct iotjs_pwm_platform_data_s { iotbus_pwm_context_h ctx; }; void iotjs_pwm_create_platform_data(iotjs_pwm_t* pwm) { pwm->platform_data = IOTJS_ALLOC(iotjs_pwm_platform_data_t); } void iotjs_pwm_destroy_platform_data(iotjs_pwm_platform_data_t* pdata) { IOTJS_RELEASE(pdata); } jerry_value_t iotjs_pwm_set_platform_config(iotjs_pwm_t* pwm, const jerry_value_t jconfig) { return jerry_create_undefined(); } static bool pwm_set_options(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; if (platform_data->ctx == NULL) { DLOG("%s - file open failed", __func__); return false; } DDDLOG("%s - period: %d, duty: %d", __func__, (int)pwm->period, (int)(pwm->duty_cycle * 100)); return iotjs_pwm_set_dutycycle(pwm) && iotjs_pwm_set_period(pwm); } bool iotjs_pwm_open(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; platform_data->ctx = iotbus_pwm_open(0, (int)pwm->pin); if (platform_data->ctx == NULL) { DLOG("%s - file open failed", __func__); return false; } if (!pwm_set_options(pwm)) { return false; } return true; } bool iotjs_pwm_set_period(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; iotbus_pwm_context_h ctx = platform_data->ctx; if (ctx == NULL) { DLOG("%s - file open failed", __func__); return false; } uint32_t period_us = (uint32_t)(1000000 * pwm->period); return iotbus_pwm_set_period(ctx, period_us) == 0; } bool iotjs_pwm_set_dutycycle(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; iotbus_pwm_context_h ctx = platform_data->ctx; if (ctx == NULL) { DLOG("%s - file open failed", __func__); return false; } uint32_t duty_cycle_per_cent = (uint32_t)(pwm->duty_cycle * 100); return iotbus_pwm_set_duty_cycle(ctx, duty_cycle_per_cent) == 0; } bool iotjs_pwm_set_enable(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; iotbus_pwm_context_h ctx = platform_data->ctx; if (ctx == NULL) { DLOG("%s - file open failed", __func__); return false; } DDDLOG("%s - enable: %d", __func__, pwm->enable); int ret; if (pwm->enable) { ret = iotbus_pwm_set_enabled(ctx, IOTBUS_PWM_ENABLE); } else { ret = iotbus_pwm_set_enabled(ctx, IOTBUS_PWM_DISABLE); } if (ret < 0) { DLOG("%s - setEnable failed", __func__); return false; } return true; } bool iotjs_pwm_close(iotjs_pwm_t* pwm) { iotjs_pwm_platform_data_t* platform_data = pwm->platform_data; iotbus_pwm_context_h ctx = platform_data->ctx; if (ctx == NULL) { DLOG("%s - file not opened", __func__); return false; } DDDLOG("%s", __func__); iotbus_pwm_close(ctx); platform_data->ctx = NULL; return true; } #endif // __TIZENRT__ iotjs-1.0+715/src/modules/tizenrt/iotjs_module_spi-tizenrt.c000066400000000000000000000071751371177304000241760ustar00rootroot00000000000000/* 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(__TIZENRT__) #error "Module __FILE__ is for TizenRT only" #endif #include #if !defined(CONFIG_SPI) #error "\n\nTizenRT CONFIG_SPI configuration flag required for SPI module\n\n" #elif !defined(CONFIG_SPI_EXCHANGE) #error "\n\nTizenRT CONFIG_SPI_EXCHANGE flag required for SPI module\n\n" #endif #include #include #include "modules/iotjs_module_spi.h" struct iotjs_spi_platform_data_s { unsigned int bus; iotbus_spi_context_h spi_context; }; void iotjs_spi_create_platform_data(iotjs_spi_t* spi) { spi->platform_data = IOTJS_ALLOC(iotjs_spi_platform_data_t); spi->platform_data->spi_context = NULL; } void iotjs_spi_destroy_platform_data(iotjs_spi_platform_data_t* platform_data) { IOTJS_ASSERT(platform_data); IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_spi_set_platform_config(iotjs_spi_t* spi, const jerry_value_t jconfig) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; JS_GET_REQUIRED_CONF_VALUE(jconfig, platform_data->bus, IOTJS_MAGIC_STRING_BUS, number); return jerry_create_undefined(); } bool iotjs_spi_open(iotjs_spi_t* spi) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; struct iotbus_spi_config_s cfg = {.bits_per_word = spi->bits_per_word, .chip_select = spi->chip_select, .frequency = spi->max_speed }; switch (spi->mode) { case kSpiMode_0: cfg.mode = IOTBUS_SPI_MODE0; break; case kSpiMode_1: cfg.mode = IOTBUS_SPI_MODE1; break; case kSpiMode_2: cfg.mode = IOTBUS_SPI_MODE2; break; case kSpiMode_3: cfg.mode = IOTBUS_SPI_MODE3; break; default: cfg.mode = IOTBUS_SPI_MODE0; } platform_data->spi_context = iotbus_spi_open(platform_data->bus, &cfg); if (platform_data->spi_context == NULL) { return false; } DDLOG( "SPI Options \n mode: %d\n chipSelect: %d\n bitOrder: %d\n " "maxSpeed: %d\n bitPerWord: %d\n loopback: %d", spi->mode, spi->chip_select, spi->bit_order, spi->max_speed, spi->bits_per_word, spi->loopback); return true; } bool iotjs_spi_transfer(iotjs_spi_t* spi) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; int err = iotbus_spi_transfer_buf(platform_data->spi_context, (unsigned char*)spi->tx_buf_data, (unsigned char*)spi->rx_buf_data, spi->buf_len); if (err != 0) { DDLOG("%s - transfer failed: %d", __func__, err); return false; } return true; } bool iotjs_spi_close(iotjs_spi_t* spi) { iotjs_spi_platform_data_t* platform_data = spi->platform_data; if (platform_data->spi_context != NULL) { int err = iotbus_spi_close(platform_data->spi_context); if (err != 0) { DDLOG("%s - close failed: %d", __func__, err); return false; } platform_data->spi_context = NULL; } return true; } iotjs-1.0+715/src/modules/tizenrt/iotjs_module_uart-tizenrt.c000066400000000000000000000055121371177304000243470ustar00rootroot00000000000000/* 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(__TIZENRT__) #error "Module __FILE__ is for TizenRT only" #endif #include "modules/iotjs_module_uart.h" #include "iotjs_uv_handle.h" struct iotjs_uart_platform_data_s { iotjs_string_t device_path; }; void iotjs_uart_create_platform_data(iotjs_uart_t* uart) { uart->platform_data = IOTJS_ALLOC(iotjs_uart_platform_data_t); } void iotjs_uart_destroy_platform_data( iotjs_uart_platform_data_t* platform_data) { IOTJS_ASSERT(platform_data); iotjs_string_destroy(&platform_data->device_path); IOTJS_RELEASE(platform_data); } jerry_value_t iotjs_uart_set_platform_config(iotjs_uart_t* uart, const jerry_value_t jconfig) { JS_GET_REQUIRED_CONF_VALUE(jconfig, uart->platform_data->device_path, IOTJS_MAGIC_STRING_DEVICE, string); return jerry_create_undefined(); } bool iotjs_uart_open(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); int fd = open(iotjs_string_data(&uart->platform_data->device_path), O_RDWR | O_NOCTTY | O_NDELAY); if (fd < 0) { return false; } uart->device_fd = fd; iotjs_uart_register_read_cb((uv_poll_t*)uart_poll_handle); return true; } bool iotjs_uart_write(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); int bytesWritten = 0; unsigned offset = 0; int fd = uart->device_fd; const char* buf_data = iotjs_string_data(&uart->buf_data); DDDLOG("%s - data: %s", __func__, buf_data); do { errno = 0; bytesWritten = write(fd, buf_data + offset, uart->buf_len - offset); DDDLOG("%s - size: %d", __func__, uart->buf_len - offset); if (bytesWritten != -1) { offset += (unsigned)bytesWritten; continue; } if (errno == EINTR) { continue; } return false; } while (uart->buf_len > offset); return true; } void iotjs_uart_handle_close_cb(uv_handle_t* uart_poll_handle) { iotjs_uart_t* uart = (iotjs_uart_t*)IOTJS_UV_HANDLE_EXTRA_DATA(uart_poll_handle); if (close(uart->device_fd) < 0) { DLOG(iotjs_periph_error_str(kUartOpClose)); IOTJS_ASSERT(0); } } iotjs-1.0+715/src/napi/000077500000000000000000000000001371177304000145335ustar00rootroot00000000000000iotjs-1.0+715/src/napi/node_api.c000066400000000000000000000027321371177304000164610ustar00rootroot00000000000000/* Copyright 2018-present Rokid 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 "jerryscript-ext/handle-scope.h" #include "jerryscript.h" #include "internal/node_api_internal.h" static napi_node_version node_version = { .major = NODE_MAJOR_VERSION, .minor = NODE_MINOR_VERSION, .patch = NODE_PATCH_VERSION, }; napi_status napi_get_node_version(napi_env env, const napi_node_version** version) { NAPI_TRY_ENV(env); NAPI_ASSIGN(version, &node_version); NAPI_RETURN(napi_ok); } napi_status napi_get_version(napi_env env, uint32_t* result) { NAPI_TRY_ENV(env); NAPI_ASSIGN(result, NAPI_VERSION); NAPI_RETURN(napi_ok); } napi_status napi_get_uv_event_loop(napi_env env, uv_loop_t** loop) { NAPI_TRY_ENV(env); iotjs_environment_t* iotjs_env = iotjs_environment_get(); uv_loop_t* iotjs_loop = iotjs_environment_loop(iotjs_env); NAPI_ASSIGN(loop, iotjs_loop); NAPI_RETURN(napi_ok); } iotjs-1.0+715/src/napi/node_api_async.c000066400000000000000000000130201371177304000176460ustar00rootroot00000000000000/* Copyright 2019-present Samsung Electronics Co., Ltd. and other contributors * Copyright 2018-present Rokid 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 "uv.h" #include "internal/node_api_internal.h" static void iotjs_uv_work_cb(uv_work_t* req) { iotjs_async_work_t* async_work = (iotjs_async_work_t*)req->data; IOTJS_ASSERT(async_work != NULL); if (async_work->execute != NULL) { async_work->execute(async_work->env, async_work->data); } } static void iotjs_uv_work_after_cb(uv_work_t* req, int status) { iotjs_async_work_t* async_work = (iotjs_async_work_t*)req->data; IOTJS_ASSERT(async_work != NULL); napi_status cb_status; if (status == 0) { cb_status = napi_ok; } else if (status == UV_ECANCELED) { cb_status = napi_cancelled; } else { cb_status = napi_generic_failure; } napi_env env = async_work->env; napi_async_complete_callback complete = async_work->complete; void* data = async_work->data; if (complete != NULL) { jerryx_handle_scope scope; jerryx_open_handle_scope(&scope); /** * napi_async_work could be deleted by invocation of `napi_delete_asyncwork` * in its complete callback. */ complete(env, cb_status, data); jerryx_close_handle_scope(scope); if (iotjs_napi_is_exception_pending(env)) { jerry_value_t jval_err; jval_err = iotjs_napi_env_get_and_clear_exception(env); if (jval_err == (uintptr_t)NULL) { jval_err = iotjs_napi_env_get_and_clear_fatal_exception(env); } /** Argument cannot have error flag */ iotjs_uncaught_exception(jerry_get_value_from_error(jval_err, false)); jerry_release_value(jval_err); } } iotjs_process_next_tick(); } napi_status napi_create_async_work(napi_env env, napi_value async_resource, napi_value async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete, void* data, napi_async_work* result) { NAPI_TRY_ENV(env); NAPI_WEAK_ASSERT(napi_invalid_arg, result != NULL); NAPI_WEAK_ASSERT(napi_invalid_arg, execute != NULL); NAPI_WEAK_ASSERT(napi_invalid_arg, complete != NULL); iotjs_async_work_t* async_work = IOTJS_ALLOC(iotjs_async_work_t); uv_work_t* work_req = &async_work->work_req; async_work->env = env; async_work->async_resource = async_resource; async_work->async_resource_name = async_resource_name; async_work->execute = execute; async_work->complete = complete; async_work->data = data; work_req->data = async_work; NAPI_ASSIGN(result, (napi_async_work)work_req); NAPI_RETURN(napi_ok); } napi_status napi_delete_async_work(napi_env env, napi_async_work work) { NAPI_TRY_ENV(env); uv_work_t* work_req = (uv_work_t*)work; iotjs_async_work_t* async_work = (iotjs_async_work_t*)work_req->data; IOTJS_RELEASE(async_work); NAPI_RETURN(napi_ok); } napi_status napi_queue_async_work(napi_env env, napi_async_work work) { NAPI_TRY_ENV(env); iotjs_environment_t* iotjs_env = iotjs_environment_get(); uv_loop_t* loop = iotjs_environment_loop(iotjs_env); uv_work_t* work_req = (uv_work_t*)work; int status = uv_queue_work(loop, work_req, iotjs_uv_work_cb, iotjs_uv_work_after_cb); if (status != 0) { const char* err_name = uv_err_name(status); NAPI_RETURN_WITH_MSG(napi_generic_failure, err_name); } NAPI_RETURN(napi_ok); } napi_status napi_cancel_async_work(napi_env env, napi_async_work work) { NAPI_TRY_ENV(env); uv_work_t* work_req = (uv_work_t*)work; int status = uv_cancel((uv_req_t*)work_req); if (status != 0) { const char* err_name = uv_err_name(status); NAPI_RETURN_WITH_MSG(napi_generic_failure, err_name); } NAPI_RETURN(napi_ok); } napi_status napi_async_init(napi_env env, napi_value async_resource, napi_value async_resource_name, napi_async_context* result) { NAPI_TRY_ENV(env); iotjs_async_context_t* ctx = IOTJS_ALLOC(iotjs_async_context_t); ctx->env = env; ctx->async_resource = async_resource; ctx->async_resource_name = async_resource_name; NAPI_ASSIGN(result, (napi_async_context)ctx); return napi_ok; } napi_status napi_async_destroy(napi_env env, napi_async_context async_context) { NAPI_TRY_ENV(env); iotjs_async_context_t* ctx = (iotjs_async_context_t*)async_context; IOTJS_RELEASE(ctx); return napi_ok; } napi_status napi_make_callback(napi_env env, napi_async_context async_context, napi_value recv, napi_value func, size_t argc, const napi_value* argv, napi_value* result) { NAPI_TRY_ENV(env); napi_status status = napi_call_function(env, recv, func, argc, argv, result); if (!iotjs_napi_is_exception_pending(env)) { iotjs_process_next_tick(); } else { // In this case explicit napi_async_destroy calls won't be executed, so // free the context manually. IOTJS_RELEASE(async_context); } return status; } iotjs-1.0+715/src/napi/node_api_env.c000066400000000000000000000173051371177304000173330ustar00rootroot00000000000000/* Copyright 2019-present Samsung Electronics Co., Ltd. and other contributors * Copyright 2018-present Rokid 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 #include "internal/node_api_internal.h" #ifndef NAPI_FATAL_BACKTRACE_LEN #define NAPI_FATAL_BACKTRACE_LEN 10 #endif static const char* NAPI_GENERIC_ERROR_MESSAGE = "Unexpected error."; static iotjs_napi_env_t current_env = { .pending_exception = NULL, .pending_fatal_exception = NULL, }; napi_env iotjs_get_current_napi_env(void) { return (napi_env)¤t_env; } static uv_thread_t* iotjs_get_napi_env_thread(napi_env env) { return &((iotjs_napi_env_t*)env)->main_thread; } bool napi_try_env_helper(napi_env env) { uv_thread_t current = uv_thread_self(); IOTJS_ASSERT(uv_thread_equal(iotjs_get_napi_env_thread(env), ¤t)); return (env != iotjs_get_current_napi_env()); } bool iotjs_napi_is_exception_pending(napi_env env) { iotjs_napi_env_t* curr_env = (iotjs_napi_env_t*)env; return !(curr_env->pending_exception == NULL && curr_env->pending_fatal_exception == NULL); } void iotjs_napi_set_current_callback(napi_env env, iotjs_callback_info_t* callback_info) { iotjs_napi_env_t* curr_env = (iotjs_napi_env_t*)env; curr_env->current_callback_info = callback_info; } iotjs_callback_info_t* iotjs_napi_get_current_callback(napi_env env) { iotjs_napi_env_t* curr_env = (iotjs_napi_env_t*)env; return curr_env->current_callback_info; } void iotjs_napi_set_error_info(napi_env env, napi_status error_code, const char* error_message, uint32_t engine_error_code, void* engine_reserved) { iotjs_napi_env_t* cur_env = (iotjs_napi_env_t*)env; if (error_message == NULL && error_code != napi_ok) { error_message = NAPI_GENERIC_ERROR_MESSAGE; } cur_env->extended_error_info.error_code = error_code; cur_env->extended_error_info.error_message = error_message; cur_env->extended_error_info.engine_error_code = engine_error_code; cur_env->extended_error_info.engine_reserved = engine_reserved; } void iotjs_napi_clear_error_info(napi_env env) { iotjs_napi_env_t* cur_env = (iotjs_napi_env_t*)env; cur_env->extended_error_info.error_code = napi_ok; cur_env->extended_error_info.error_message = NULL; cur_env->extended_error_info.engine_error_code = 0; cur_env->extended_error_info.engine_reserved = NULL; } jerry_value_t iotjs_napi_env_get_and_clear_exception(napi_env env) { iotjs_napi_env_t* cur_env = (iotjs_napi_env_t*)env; jerry_value_t jval_ret = AS_JERRY_VALUE(cur_env->pending_exception); cur_env->pending_exception = NULL; return jval_ret; } jerry_value_t iotjs_napi_env_get_and_clear_fatal_exception(napi_env env) { iotjs_napi_env_t* cur_env = (iotjs_napi_env_t*)env; jerry_value_t jval_ret = AS_JERRY_VALUE(cur_env->pending_fatal_exception); cur_env->pending_fatal_exception = NULL; return jval_ret; } // Methods to support error handling napi_status napi_throw(napi_env env, napi_value error) { NAPI_TRY_ENV(env); iotjs_napi_env_t* curr_env = (iotjs_napi_env_t*)env; NAPI_TRY_NO_PENDING_EXCEPTION(env); jerry_value_t jval_err = AS_JERRY_VALUE(error); /** * `jerry_value_set_error_flag` creates a new error reference and its * reference count is separated from its original value, so we have to * acquire the original value before `jerry_value_set_error_flag` */ jval_err = jerry_acquire_value(jval_err); if (!jerry_value_is_error(jval_err)) { jval_err = jerry_create_error_from_value(jval_err, true); } curr_env->pending_exception = AS_NAPI_VALUE(jval_err); /** should not clear last error info */ return napi_ok; } static napi_status napi_throw_helper(jerry_error_t jerry_error_type, napi_env env, const char* code, const char* msg) { NAPI_TRY_ENV(env); NAPI_TRY_NO_PENDING_EXCEPTION(env); jerry_value_t jval_error = jerry_create_error(jerry_error_type, (jerry_char_t*)msg); if (code != NULL) { jval_error = jerry_get_value_from_error(jval_error, true); iotjs_jval_set_property_string_raw(jval_error, "code", code); jval_error = jerry_create_error_from_value(jval_error, true); } jerryx_create_handle(jval_error); return napi_throw(env, AS_NAPI_VALUE(jval_error)); } #define DEF_NAPI_THROWS(type, jerry_error_type) \ napi_status napi_throw_##type(napi_env env, const char* code, \ const char* msg) { \ return napi_throw_helper(jerry_error_type, env, code, msg); \ } DEF_NAPI_THROWS(error, JERRY_ERROR_COMMON); DEF_NAPI_THROWS(type_error, JERRY_ERROR_TYPE); DEF_NAPI_THROWS(range_error, JERRY_ERROR_RANGE); #undef DEF_NAPI_THROWS // This method invokes an 'uncaughtException', only when jerry-debugger is off napi_status napi_fatal_exception(napi_env env, napi_value err) { NAPI_TRY_ENV(env); NAPI_TRY_NO_PENDING_EXCEPTION(env); iotjs_napi_env_t* curr_env = (iotjs_napi_env_t*)env; jerry_value_t jval_err = AS_JERRY_VALUE(err); /** * `jerry_value_set_error_flag` creates a new error reference and its * reference count is separated from its original value, so we have to * acquire the original value before `jerry_value_set_error_flag` */ jval_err = jerry_acquire_value(jval_err); if (!jerry_value_is_abort(jval_err)) { jval_err = jerry_create_abort_from_value(jval_err, true); } curr_env->pending_fatal_exception = AS_NAPI_VALUE(jval_err); /** should not clear last error info */ return napi_ok; } // Methods to support catching exceptions napi_status napi_is_exception_pending(napi_env env, bool* result) { NAPI_TRY_ENV(env); NAPI_ASSIGN(result, iotjs_napi_is_exception_pending(env)); /** should not clear last error info */ return napi_ok; } napi_status napi_get_and_clear_last_exception(napi_env env, napi_value* result) { NAPI_TRY_ENV(env); iotjs_napi_env_t* curr_env = (iotjs_napi_env_t*)env; napi_value error; if (curr_env->pending_exception != NULL) { error = curr_env->pending_exception; curr_env->pending_exception = NULL; } else if (curr_env->pending_fatal_exception != NULL) { error = curr_env->pending_fatal_exception; curr_env->pending_fatal_exception = NULL; } else { error = AS_NAPI_VALUE(jerry_create_undefined()); } jerry_value_t jval_err = jerry_get_value_from_error(AS_JERRY_VALUE(error), true); NAPI_ASSIGN(result, AS_NAPI_VALUE(jval_err)); /** should not clear last error info */ return napi_ok; } napi_status napi_get_last_error_info(napi_env env, const napi_extended_error_info** result) { NAPI_TRY_ENV(env); iotjs_napi_env_t* curr_env = (iotjs_napi_env_t*)env; napi_extended_error_info* error_info = &curr_env->extended_error_info; NAPI_ASSIGN(result, error_info); return napi_ok; } void napi_fatal_error(const char* location, size_t location_len, const char* message, size_t message_len) { fprintf(stderr, "FATAL ERROR: %.*s %.*s\n", location_len, location, message_len, message); print_stacktrace(); abort(); } iotjs-1.0+715/src/napi/node_api_function.c000066400000000000000000000157711371177304000203750ustar00rootroot00000000000000/* Copyright 2019-present Samsung Electronics Co., Ltd. and other contributors * Copyright 2018-present Rokid 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 "jerryscript-ext/handle-scope.h" #include "jerryscript.h" #include #include "internal/node_api_internal.h" #include "node_api.h" static jerry_value_t iotjs_napi_function_handler( const jerry_value_t func_obj, const jerry_value_t this_val, const jerry_value_t args_p[], const jerry_length_t args_cnt) { iotjs_function_info_t* function_info = (iotjs_function_info_t*) iotjs_try_get_object_native_info(func_obj, sizeof(iotjs_function_info_t)); IOTJS_ASSERT(function_info != NULL); napi_env env = function_info->env; jerryx_handle_scope scope; jerryx_open_handle_scope(&scope); iotjs_callback_info_t* callback_info = IOTJS_ALLOC(iotjs_callback_info_t); callback_info->argc = args_cnt; callback_info->argv = (jerry_value_t*)args_p; callback_info->jval_this = this_val; callback_info->jval_func = func_obj; callback_info->function_info = function_info; callback_info->handle_scope = scope; callback_info->function_info = function_info; iotjs_napi_set_current_callback(env, callback_info); napi_value nvalue_ret = function_info->cb(env, (napi_callback_info)callback_info); iotjs_napi_set_current_callback(env, NULL); IOTJS_RELEASE(callback_info); jerry_value_t jval_ret; if (iotjs_napi_is_exception_pending(env)) { jerry_value_t jval_err = iotjs_napi_env_get_and_clear_exception(env); if (jval_err != (uintptr_t)NULL) { jval_ret = jval_err; } else { jval_err = iotjs_napi_env_get_and_clear_fatal_exception(env); IOTJS_ASSERT(jval_err != (uintptr_t)NULL); jval_ret = jval_err; } goto cleanup; } // TODO: check if nvalue_ret is escaped /** * Do not turn NULL pointer into undefined since number value `0` in * jerryscript also represented by NULL */ jval_ret = AS_JERRY_VALUE(nvalue_ret); /** * - for N-API created value: value is scoped, would be released on :cleanup * - for passed-in params: value would be automatically release on end of * invocation * - for error values: error values has been acquired on thrown */ jval_ret = jerry_acquire_value(jval_ret); cleanup: jerryx_close_handle_scope(scope); /** * Clear N-API env extended error info on end of external function * execution to prevent error info been passed to next external function. */ iotjs_napi_clear_error_info(env); return jval_ret; } napi_status napi_create_function(napi_env env, const char* utf8name, size_t length, napi_callback cb, void* data, napi_value* result) { NAPI_TRY_ENV(env); jerry_value_t jval_func = jerry_create_external_function(iotjs_napi_function_handler); jerryx_create_handle(jval_func); iotjs_function_info_t* function_info = (iotjs_function_info_t*) iotjs_get_object_native_info(jval_func, sizeof(iotjs_function_info_t)); function_info->env = env; function_info->cb = cb; function_info->data = data; return napi_assign_nvalue(jval_func, result); } napi_status napi_call_function(napi_env env, napi_value recv, napi_value func, size_t argc, const napi_value* argv, napi_value* result) { NAPI_TRY_ENV(env); NAPI_TRY_NO_PENDING_EXCEPTION(env); jerry_value_t jval_func = AS_JERRY_VALUE(func); jerry_value_t jval_this = AS_JERRY_VALUE(recv); NAPI_TRY_TYPE(function, jval_func); jerry_value_t* jval_argv = IOTJS_CALLOC(argc, jerry_value_t); for (size_t idx = 0; idx < argc; ++idx) { jval_argv[idx] = AS_JERRY_VALUE(argv[idx]); } JERRYX_CREATE(jval_ret, jerry_call_function(jval_func, jval_this, jval_argv, argc)); IOTJS_RELEASE(jval_argv); if (jerry_value_is_error(jval_ret)) { NAPI_INTERNAL_CALL(napi_throw(env, AS_NAPI_VALUE(jval_ret))); NAPI_RETURN_WITH_MSG(napi_pending_exception, "Unexpected error flag on jerry_call_function."); } return napi_assign_nvalue(jval_ret, result); } napi_status napi_get_cb_info(napi_env env, napi_callback_info cbinfo, size_t* argc, napi_value* argv, napi_value* thisArg, void** data) { NAPI_TRY_ENV(env); iotjs_callback_info_t* callback_info = (iotjs_callback_info_t*)cbinfo; size_t _argc = (argc == NULL || argv == NULL) ? 0 : *argc; for (size_t i = 0; i < _argc; ++i) { if (i < callback_info->argc) { NAPI_ASSIGN(argv + i, AS_NAPI_VALUE(callback_info->argv[i])); } else { NAPI_ASSIGN(argv + i, AS_NAPI_VALUE(jerry_create_undefined())); } } NAPI_ASSIGN(argc, callback_info->argc); if (thisArg != NULL) { NAPI_ASSIGN(thisArg, AS_NAPI_VALUE(callback_info->jval_this)); } if (data != NULL) { NAPI_ASSIGN(data, callback_info->function_info->data); } NAPI_RETURN(napi_ok); } napi_status napi_get_new_target(napi_env env, napi_callback_info cbinfo, napi_value* result) { iotjs_callback_info_t* callback_info = (iotjs_callback_info_t*)cbinfo; jerry_value_t jval_this = callback_info->jval_this; jerry_value_t jval_target = callback_info->jval_func; jerry_value_t is_instance = jerry_binary_operation(JERRY_BIN_OP_INSTANCEOF, jval_this, jval_target); if (jerry_value_is_error(is_instance)) { jerry_release_value(is_instance); NAPI_ASSIGN(result, NULL); NAPI_RETURN(napi_generic_failure); } NAPI_ASSIGN(result, jerry_get_boolean_value(is_instance) ? AS_NAPI_VALUE(jval_target) : NULL); NAPI_RETURN(napi_ok); } napi_status napi_new_instance(napi_env env, napi_value constructor, size_t argc, const napi_value* argv, napi_value* result) { NAPI_TRY_ENV(env); NAPI_TRY_NO_PENDING_EXCEPTION(env); jerry_value_t jval_cons = AS_JERRY_VALUE(constructor); NAPI_TRY_TYPE(function, jval_cons); jerry_value_t* jval_argv = IOTJS_CALLOC(argc, jerry_value_t); for (size_t idx = 0; idx < argc; ++idx) { jval_argv[idx] = AS_JERRY_VALUE(argv[idx]); } JERRYX_CREATE(jval_ret, jerry_construct_object(jval_cons, jval_argv, argc)); IOTJS_RELEASE(jval_argv); if (jerry_value_is_error(jval_ret)) { NAPI_INTERNAL_CALL(napi_throw(env, AS_NAPI_VALUE(jval_ret))); NAPI_RETURN_WITH_MSG(napi_pending_exception, "Unexpected error flag on jerry_construct_object."); } return napi_assign_nvalue(jval_ret, result); } iotjs-1.0+715/src/napi/node_api_lifetime.c000066400000000000000000000217671371177304000203500ustar00rootroot00000000000000/* Copyright 2018-present Rokid 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 "jerryscript-ext/handle-scope.h" #include #include "internal/node_api_internal.h" IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(object_info); static void iotjs_object_info_destroy(iotjs_object_info_t* info) { iotjs_reference_t* comp = info->ref_start; while (comp != NULL) { comp->jval = jerry_create_undefined(); comp = comp->next; } if (info->finalize_cb != NULL) { info->finalize_cb(info->env, info->native_object, info->finalize_hint); } IOTJS_RELEASE(info); } inline napi_status jerryx_status_to_napi_status( jerryx_handle_scope_status status) { switch (status) { case jerryx_handle_scope_mismatch: NAPI_RETURN(napi_handle_scope_mismatch); case jerryx_escape_called_twice: NAPI_RETURN(napi_escape_called_twice); default: NAPI_RETURN(napi_ok); } } iotjs_object_info_t* iotjs_get_object_native_info(jerry_value_t jval, size_t native_info_size) { void* info; if (!jerry_get_object_native_pointer(jval, &info, &this_module_native_info)) { info = iotjs_buffer_allocate(native_info_size); jerry_set_object_native_pointer(jval, info, &this_module_native_info); } return (iotjs_object_info_t*)info; } iotjs_object_info_t* iotjs_try_get_object_native_info(jerry_value_t jval, size_t native_info_size) { void* info = NULL; if (jerry_get_object_native_pointer(jval, &info, &this_module_native_info)) { return (iotjs_object_info_t*)info; } return NULL; } napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result) { NAPI_TRY_ENV(env); NAPI_WEAK_ASSERT(napi_invalid_arg, result != NULL); jerryx_handle_scope_status status; status = jerryx_open_handle_scope((jerryx_handle_scope*)result); return jerryx_status_to_napi_status(status); } napi_status napi_open_escapable_handle_scope( napi_env env, napi_escapable_handle_scope* result) { NAPI_TRY_ENV(env); NAPI_WEAK_ASSERT(napi_invalid_arg, result != NULL); jerryx_handle_scope_status status; status = jerryx_open_escapable_handle_scope( (jerryx_escapable_handle_scope*)result); return jerryx_status_to_napi_status(status); } napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) { NAPI_TRY_ENV(env); jerryx_handle_scope_status status; status = jerryx_close_handle_scope((jerryx_handle_scope)scope); return jerryx_status_to_napi_status(status); } napi_status napi_close_escapable_handle_scope( napi_env env, napi_escapable_handle_scope scope) { NAPI_TRY_ENV(env); jerryx_handle_scope_status status; status = jerryx_close_escapable_handle_scope((jerryx_escapable_handle_scope)scope); return jerryx_status_to_napi_status(status); } napi_status napi_escape_handle(napi_env env, napi_escapable_handle_scope scope, napi_value escapee, napi_value* result) { NAPI_TRY_ENV(env); NAPI_WEAK_ASSERT(napi_invalid_arg, result != NULL); jerryx_handle_scope_status status; status = jerryx_escape_handle((jerryx_escapable_handle_scope)scope, AS_JERRY_VALUE(escapee), (jerry_value_t*)result); return jerryx_status_to_napi_status(status); } napi_status napi_create_reference(napi_env env, napi_value value, uint32_t initial_refcount, napi_ref* result) { NAPI_TRY_ENV(env); NAPI_WEAK_ASSERT(napi_invalid_arg, result != NULL); jerry_value_t jval = AS_JERRY_VALUE(value); iotjs_object_info_t* info = iotjs_get_object_native_info(jval, sizeof(iotjs_object_info_t)); iotjs_reference_t* ref = IOTJS_ALLOC(iotjs_reference_t); ref->refcount = initial_refcount; ref->jval = AS_JERRY_VALUE(value); ref->next = NULL; if (info->ref_start == NULL) { ref->prev = NULL; info->ref_start = ref; info->ref_end = ref; } else { ref->prev = info->ref_end; info->ref_end->next = ref; info->ref_end = ref; } for (uint32_t i = 0; i < ref->refcount; ++i) { jerry_acquire_value(ref->jval); } NAPI_ASSIGN(result, (napi_ref)ref); NAPI_RETURN(napi_ok); } napi_status napi_delete_reference(napi_env env, napi_ref ref) { NAPI_TRY_ENV(env); iotjs_reference_t* iotjs_ref = (iotjs_reference_t*)ref; if (jerry_value_is_object(iotjs_ref->jval)) { jerry_value_t jval = iotjs_ref->jval; iotjs_object_info_t* info = iotjs_get_object_native_info(jval, sizeof(iotjs_object_info_t)); bool found = false; iotjs_reference_t* comp = info->ref_start; while (comp != NULL) { if (comp == iotjs_ref) { found = true; break; } comp = comp->next; } NAPI_WEAK_ASSERT(napi_invalid_arg, found); if (info->ref_start == iotjs_ref) { info->ref_start = iotjs_ref->next; } if (info->ref_end == iotjs_ref) { info->ref_end = iotjs_ref->prev; } if (iotjs_ref->prev != NULL) { iotjs_ref->prev->next = iotjs_ref->next; } if (iotjs_ref->next != NULL) { iotjs_ref->next->prev = iotjs_ref->prev; } } for (uint32_t i = 0; i < iotjs_ref->refcount; ++i) { jerry_release_value(iotjs_ref->jval); } IOTJS_RELEASE(iotjs_ref); NAPI_RETURN(napi_ok); } napi_status napi_reference_ref(napi_env env, napi_ref ref, uint32_t* result) { NAPI_TRY_ENV(env); iotjs_reference_t* iotjs_ref = (iotjs_reference_t*)ref; NAPI_WEAK_ASSERT(napi_invalid_arg, jerry_value_is_object(iotjs_ref->jval)); jerry_acquire_value(iotjs_ref->jval); iotjs_ref->refcount += 1; NAPI_ASSIGN(result, iotjs_ref->refcount); NAPI_RETURN(napi_ok); } napi_status napi_reference_unref(napi_env env, napi_ref ref, uint32_t* result) { NAPI_TRY_ENV(env); iotjs_reference_t* iotjs_ref = (iotjs_reference_t*)ref; NAPI_WEAK_ASSERT(napi_invalid_arg, (iotjs_ref->refcount > 0)); jerry_release_value(iotjs_ref->jval); iotjs_ref->refcount -= 1; NAPI_ASSIGN(result, iotjs_ref->refcount); NAPI_RETURN(napi_ok); } napi_status napi_get_reference_value(napi_env env, napi_ref ref, napi_value* result) { NAPI_TRY_ENV(env); iotjs_reference_t* iotjs_ref = (iotjs_reference_t*)ref; return napi_assign_nvalue(iotjs_ref->jval, result); } napi_status napi_open_callback_scope(napi_env env, napi_value resource_object, napi_async_context context, napi_callback_scope* result) { NAPI_TRY_ENV(env); return napi_open_handle_scope(env, (napi_handle_scope*)result); } napi_status napi_close_callback_scope(napi_env env, napi_callback_scope scope) { NAPI_TRY_ENV(env); return napi_close_handle_scope(env, (napi_handle_scope)scope); } napi_status napi_add_env_cleanup_hook(napi_env env, void (*fun)(void* arg), void* arg) { NAPI_TRY_ENV(env); iotjs_napi_env_t* curr_env = (iotjs_napi_env_t*)env; iotjs_cleanup_hook_t* memo = NULL; iotjs_cleanup_hook_t* hook = curr_env->cleanup_hook; while (hook != NULL) { if (fun == hook->fn) { NAPI_WEAK_ASSERT(napi_invalid_arg, arg != hook->arg); } memo = hook; hook = hook->next; } iotjs_cleanup_hook_t* new_hook = IOTJS_ALLOC(iotjs_cleanup_hook_t); new_hook->fn = fun; new_hook->arg = arg; new_hook->next = NULL; if (memo == NULL) { curr_env->cleanup_hook = new_hook; } else { memo->next = new_hook; } NAPI_RETURN(napi_ok); } napi_status napi_remove_env_cleanup_hook(napi_env env, void (*fun)(void* arg), void* arg) { NAPI_TRY_ENV(env); iotjs_napi_env_t* curr_env = (iotjs_napi_env_t*)env; iotjs_cleanup_hook_t* memo = NULL; iotjs_cleanup_hook_t* hook = curr_env->cleanup_hook; bool found = false; while (hook != NULL) { if (fun == hook->fn && arg == hook->arg) { found = true; break; } memo = hook; hook = hook->next; } NAPI_WEAK_ASSERT(napi_invalid_arg, found); if (memo == NULL) { curr_env->cleanup_hook = hook->next; } else { memo->next = hook->next; } IOTJS_RELEASE(hook); NAPI_RETURN(napi_ok); } void iotjs_setup_napi() { iotjs_napi_env_t* env = (iotjs_napi_env_t*)iotjs_get_current_napi_env(); env->main_thread = uv_thread_self(); } void iotjs_cleanup_napi() { iotjs_napi_env_t* env = (iotjs_napi_env_t*)iotjs_get_current_napi_env(); iotjs_cleanup_hook_t* hook = env->cleanup_hook; while (hook != NULL) { hook->fn(hook->arg); iotjs_cleanup_hook_t* memo = hook; hook = hook->next; IOTJS_RELEASE(memo); } } iotjs-1.0+715/src/napi/node_api_module.c000066400000000000000000000041471371177304000200300ustar00rootroot00000000000000/* Copyright 2018-present Rokid 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.h" #include "jerryscript-ext/handle-scope.h" #include "internal/node_api_internal.h" static napi_module* mod_pending; void napi_module_register(napi_module* mod) { mod_pending = mod; } int napi_module_init_pending(jerry_value_t* exports) { if (mod_pending == NULL) { return napi_module_no_pending; } napi_addon_register_func init = (napi_addon_register_func)mod_pending->nm_register_func; if (init == NULL) { return napi_module_no_nm_register_func; } napi_env env = iotjs_get_current_napi_env(); jerryx_handle_scope scope; jerryx_open_handle_scope(&scope); jerry_value_t jval_exports = jerry_create_object(); napi_value nvalue_ret = (*init)(env, AS_NAPI_VALUE(jval_exports)); if (nvalue_ret == NULL) { *exports = jerry_create_undefined(); jerry_release_value(jval_exports); } else { jerry_value_t jval_ret = AS_JERRY_VALUE(nvalue_ret); if (jval_ret != jval_exports) { jerry_release_value(jval_exports); jerryx_remove_handle(scope, jval_ret, &jval_ret); } *exports = jval_ret; } jerryx_close_handle_scope(scope); mod_pending = NULL; if (iotjs_napi_is_exception_pending(env)) { jerry_value_t jval_err; jval_err = iotjs_napi_env_get_and_clear_exception(env); if (jval_err == (uintptr_t)NULL) { jval_err = iotjs_napi_env_get_and_clear_fatal_exception(env); } jerry_release_value(jval_exports); *exports = jval_err; return napi_pending_exception; } return napi_module_load_ok; } iotjs-1.0+715/src/napi/node_api_object_wrap.c000066400000000000000000000067221371177304000210430ustar00rootroot00000000000000/* Copyright 2018-present Rokid 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 "internal/node_api_internal.h" napi_status napi_define_class(napi_env env, const char* utf8name, size_t length, napi_callback constructor, void* data, size_t property_count, const napi_property_descriptor* properties, napi_value* result) { NAPI_TRY_ENV(env); napi_value nval; NAPI_INTERNAL_CALL( napi_create_function(env, utf8name, length, constructor, data, &nval)); // `prototype` is undefined in `napi_create_function` results napi_value nval_prototype; NAPI_INTERNAL_CALL(napi_create_object(env, &nval_prototype)); NAPI_INTERNAL_CALL( napi_set_named_property(env, nval, "prototype", nval_prototype)); for (size_t i = 0; i < property_count; ++i) { napi_property_descriptor prop = properties[i]; if (prop.attributes & napi_static) { NAPI_INTERNAL_CALL(napi_define_properties(env, nval, 1, &prop)); } else { NAPI_INTERNAL_CALL(napi_define_properties(env, nval_prototype, 1, &prop)); } } NAPI_ASSIGN(result, nval); NAPI_RETURN(napi_ok); } napi_status napi_wrap(napi_env env, napi_value js_object, void* native_object, napi_finalize finalize_cb, void* finalize_hint, napi_ref* result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(js_object); NAPI_TRY_TYPE(object, jval); iotjs_object_info_t* object_info = iotjs_get_object_native_info(jval, sizeof(iotjs_object_info_t)); NAPI_WEAK_ASSERT(napi_invalid_arg, (object_info->native_object == NULL)); NAPI_WEAK_ASSERT(napi_invalid_arg, (object_info->finalize_cb == NULL)); NAPI_WEAK_ASSERT(napi_invalid_arg, (object_info->finalize_hint == NULL)); object_info->env = env; object_info->native_object = native_object; object_info->finalize_cb = finalize_cb; object_info->finalize_hint = finalize_hint; if (result != NULL) { return napi_create_reference(env, js_object, 0, result); } NAPI_RETURN(napi_ok); } napi_status napi_unwrap(napi_env env, napi_value js_object, void** result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(js_object); NAPI_TRY_TYPE(object, jval); iotjs_object_info_t* object_info = iotjs_get_object_native_info(jval, sizeof(iotjs_object_info_t)); NAPI_ASSIGN(result, object_info->native_object); NAPI_RETURN(napi_ok); } napi_status napi_remove_wrap(napi_env env, napi_value js_object, void** result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(js_object); iotjs_object_info_t* object_info = iotjs_get_object_native_info(jval, sizeof(iotjs_object_info_t)); NAPI_ASSIGN(result, object_info->native_object); object_info->native_object = NULL; object_info->finalize_cb = NULL; object_info->finalize_hint = NULL; NAPI_RETURN(napi_ok); } iotjs-1.0+715/src/napi/node_api_property.c000066400000000000000000000255461371177304000204350ustar00rootroot00000000000000/* Copyright 2019-present Samsung Electronics Co., Ltd. and other contributors * Copyright 2018-present Rokid 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 "jerryscript-ext/handle-scope.h" #include "jerryscript.h" #include "internal/node_api_internal.h" #include napi_status napi_get_property_names(napi_env env, napi_value object, napi_value* result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(object); NAPI_TRY_TYPE(object, jval); jerry_value_t jval_keys = jerry_get_object_keys(jval); jerryx_create_handle(jval_keys); if (jerry_value_is_error(jval_keys)) { jerry_release_value(jval_keys); NAPI_RETURN(napi_invalid_arg); } return napi_assign_nvalue(jval_keys, result); } napi_status napi_set_property(napi_env env, napi_value object, napi_value key, napi_value value) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); jerry_value_t jval_key = AS_JERRY_VALUE(key); jerry_value_t jval_val = AS_JERRY_VALUE(value); NAPI_TRY_TYPE(object, jval_object); NAPI_TRY_TYPE(string, jval_key); jerry_value_t ret = jerry_set_property(jval_object, jval_key, jval_val); if (jerry_value_is_error(ret)) { jerry_release_value(ret); NAPI_RETURN(napi_invalid_arg); } jerry_release_value(ret); NAPI_RETURN(napi_ok); } napi_status napi_get_property(napi_env env, napi_value object, napi_value key, napi_value* result) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); jerry_value_t jval_key = AS_JERRY_VALUE(key); NAPI_TRY_TYPE(object, jval_object); NAPI_TRY_TYPE(string, jval_key); jerry_value_t jval_ret = jerry_get_property(jval_object, jval_key); jerryx_create_handle(jval_ret); if (jerry_value_is_error(jval_ret)) { jerry_release_value(jval_ret); NAPI_RETURN(napi_invalid_arg); } return napi_assign_nvalue(jval_ret, result); } napi_status napi_has_property(napi_env env, napi_value object, napi_value key, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); jerry_value_t jval_key = AS_JERRY_VALUE(key); NAPI_TRY_TYPE(object, jval_object); NAPI_TRY_TYPE(string, jval_key); jerry_value_t has_prop = jerry_has_property(jval_object, jval_key); NAPI_TRY_TYPE(boolean, has_prop); return napi_assign_bool(jerry_get_boolean_value(has_prop), result); } napi_status napi_delete_property(napi_env env, napi_value object, napi_value key, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); jerry_value_t jval_key = AS_JERRY_VALUE(key); NAPI_TRY_TYPE(object, jval_object); NAPI_TRY_TYPE(string, jval_key); return napi_assign_bool(jerry_delete_property(jval_object, jval_key), result); } napi_status napi_has_own_property(napi_env env, napi_value object, napi_value key, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); jerry_value_t jval_key = AS_JERRY_VALUE(key); NAPI_TRY_TYPE(object, jval_object); NAPI_TRY_TYPE(string, jval_key); jerry_value_t has_prop = jerry_has_own_property(jval_object, jval_key); NAPI_TRY_TYPE(boolean, has_prop); return napi_assign_bool(jerry_get_boolean_value(has_prop), result); } napi_status napi_set_named_property(napi_env env, napi_value object, const char* utf8Name, napi_value value) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); NAPI_TRY_TYPE(object, jval_object); jerry_value_t jval_key = jerry_create_string_from_utf8((jerry_char_t*)utf8Name); napi_status status = napi_set_property(env, object, AS_NAPI_VALUE(jval_key), value); jerry_release_value(jval_key); return status; } napi_status napi_get_named_property(napi_env env, napi_value object, const char* utf8Name, napi_value* result) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); NAPI_TRY_TYPE(object, jval_object); jerry_value_t jval_key = jerry_create_string_from_utf8((jerry_char_t*)utf8Name); napi_status status = napi_get_property(env, object, AS_NAPI_VALUE(jval_key), result); jerry_release_value(jval_key); return status; } napi_status napi_has_named_property(napi_env env, napi_value object, const char* utf8Name, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); NAPI_TRY_TYPE(object, jval_object); jerry_value_t jval_key = jerry_create_string_from_utf8((jerry_char_t*)utf8Name); napi_status status = napi_has_property(env, object, AS_NAPI_VALUE(jval_key), result); jerry_release_value(jval_key); return status; } napi_status napi_set_element(napi_env env, napi_value object, uint32_t index, napi_value value) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); jerry_value_t jval_val = AS_JERRY_VALUE(value); NAPI_TRY_TYPE(object, jval_object); jerry_value_t res = jerry_set_property_by_index(jval_object, index, jval_val); if (jerry_value_is_error(res)) { jerry_release_value(res); NAPI_RETURN(napi_invalid_arg); } jerry_release_value(res); NAPI_RETURN(napi_ok); } napi_status napi_get_element(napi_env env, napi_value object, uint32_t index, napi_value* result) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); NAPI_TRY_TYPE(object, jval_object); jerry_value_t jval_ret = jerry_get_property_by_index(jval_object, index); jerryx_create_handle(jval_ret); if (jerry_value_is_error(jval_ret)) { jerry_release_value(jval_ret); NAPI_RETURN(napi_invalid_arg); } return napi_assign_nvalue(jval_ret, result); } napi_status napi_has_element(napi_env env, napi_value object, uint32_t index, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); NAPI_TRY_TYPE(object, jval_object); char idx_str[17]; sprintf(idx_str, "%d", index); jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)idx_str); jerry_value_t has_prop_val = jerry_has_own_property(jval_object, prop_name); jerry_release_value(prop_name); if (jerry_value_is_error(has_prop_val)) { jerry_release_value(has_prop_val); NAPI_RETURN(napi_generic_failure); } bool has_prop = jerry_get_boolean_value(has_prop_val); return napi_assign_bool(has_prop, result); } napi_status napi_delete_element(napi_env env, napi_value object, uint32_t index, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); NAPI_TRY_TYPE(object, jval_object); return napi_assign_bool(jerry_delete_property_by_index(jval_object, index), result); } napi_status iotjs_napi_prop_desc_to_jdesc(napi_env env, const napi_property_descriptor* ndesc, jerry_property_descriptor_t* jdesc) { napi_status status; if (ndesc->attributes & napi_configurable) { jdesc->is_configurable_defined = true; jdesc->is_configurable = true; } if (ndesc->attributes & napi_enumerable) { jdesc->is_enumerable_defined = true; jdesc->is_enumerable = true; } if (ndesc->attributes & napi_writable) { jdesc->is_writable_defined = true; jdesc->is_writable = true; } if (ndesc->value != NULL) { jdesc->is_value_defined = true; jdesc->value = AS_JERRY_VALUE(ndesc->value); NAPI_RETURN(napi_ok); } if (ndesc->method != NULL) { napi_value method; status = napi_create_function(env, "method", 6, ndesc->method, ndesc->data, &method); if (status != napi_ok) return status; jdesc->is_value_defined = true; jdesc->value = AS_JERRY_VALUE(method); NAPI_RETURN(napi_ok); } if (ndesc->getter != NULL) { napi_value getter; status = napi_create_function(env, "getter", 6, ndesc->getter, ndesc->data, &getter); if (status != napi_ok) return status; jdesc->is_get_defined = true; jdesc->getter = AS_JERRY_VALUE(getter); /** jerryscript asserts xor is_writable_defined and accessors */ jdesc->is_writable_defined = false; } if (ndesc->setter != NULL) { napi_value setter; status = napi_create_function(env, "setter", 6, ndesc->setter, ndesc->data, &setter); if (status != napi_ok) return status; jdesc->is_set_defined = true; jdesc->setter = AS_JERRY_VALUE(setter); /** jerryscript asserts xor is_writable_defined and accessors */ jdesc->is_writable_defined = false; } NAPI_RETURN(napi_ok); } napi_status napi_define_properties(napi_env env, napi_value object, size_t property_count, const napi_property_descriptor* properties) { NAPI_TRY_ENV(env); jerry_value_t jval_target = AS_JERRY_VALUE(object); NAPI_TRY_TYPE(object, jval_target); NAPI_WEAK_ASSERT(napi_invalid_arg, properties != NULL); napi_status status; jerry_property_descriptor_t prop_desc; for (size_t i = 0; i < property_count; ++i) { jerry_init_property_descriptor_fields(&prop_desc); napi_property_descriptor prop = properties[i]; jerry_value_t jval_prop_name; if (prop.utf8name != NULL) { jval_prop_name = jerry_create_string_from_utf8((jerry_char_t*)prop.utf8name); jerryx_create_handle(jval_prop_name); } else if (prop.name != NULL) { jval_prop_name = AS_JERRY_VALUE(prop.name); NAPI_TRY_TYPE(string, jval_prop_name); } else { NAPI_RETURN(napi_invalid_arg); } status = iotjs_napi_prop_desc_to_jdesc(env, &prop, &prop_desc); if (status != napi_ok) return status; jerry_value_t return_value = jerry_define_own_property(jval_target, jval_prop_name, &prop_desc); if (jerry_value_is_error(return_value)) { NAPI_RETURN(napi_invalid_arg); } jerry_release_value(return_value); /** * We don't have to call `jerry_free_property_descriptor_fields` * since most napi values are managed by handle scopes. */ // jerry_free_property_descriptor_fields(&prop_desc); } NAPI_RETURN(napi_ok); } iotjs-1.0+715/src/napi/node_api_value.c000066400000000000000000000732171371177304000176630ustar00rootroot00000000000000/* Copyright 2019-present Samsung Electronics Co., Ltd. and other contributors * Copyright 2018-present Rokid 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 "jerryscript-ext/handle-scope.h" #include "jerryscript.h" #include #include "internal/node_api_internal.h" #include "modules/iotjs_module_buffer.h" #include /* Feature missing error messages */ const char* const napi_err_no_dataview = "DataView is not supported by this build."; const char* const napi_err_no_promise = "Promise is not supported by this build."; const char* const napi_err_no_symbol = "Symbols are not supported by this build."; const char* const napi_err_no_typedarray = "TypedArray is not supported by this build."; const char* const napi_err_invalid_deferred = "Invalid deferred object. Please refer to the documentation."; static void iotjs_napi_buffer_external_free_cb(void* native_p) { iotjs_buffer_external_info_t* info = (iotjs_buffer_external_info_t*)native_p; napi_env env = info->env; void* external_data = info->external_data; void* finalize_hint = info->finalize_hint; napi_finalize finalize_cb = info->finalize_cb; if (finalize_cb != NULL) { finalize_cb(env, external_data, finalize_hint); } IOTJS_RELEASE(info); } napi_status napi_assign_bool(bool value, bool* result) { NAPI_ASSIGN(result, value); NAPI_RETURN(napi_ok); } napi_status napi_assign_nvalue(jerry_value_t jvalue, napi_value* nvalue) { NAPI_ASSIGN(nvalue, AS_NAPI_VALUE(jvalue)); NAPI_RETURN(napi_ok); } napi_status napi_create_array(napi_env env, napi_value* result) { NAPI_TRY_ENV(env); JERRYX_CREATE(jval, jerry_create_array(0)); return napi_assign_nvalue(jval, result); } napi_status napi_create_array_with_length(napi_env env, size_t length, napi_value* result) { NAPI_TRY_ENV(env); JERRYX_CREATE(jval, jerry_create_array(length)); return napi_assign_nvalue(jval, result); } napi_status napi_create_arraybuffer(napi_env env, size_t byte_length, void** data, napi_value* result) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_TYPEDARRAY)) { NAPI_ASSIGN(data, NULL); NAPI_ASSIGN(result, NULL); NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_typedarray); } JERRYX_CREATE(jval, jerry_create_arraybuffer(byte_length)); uint8_t* data_ptr = jerry_get_arraybuffer_pointer(jval); NAPI_ASSIGN(data, data_ptr); NAPI_ASSIGN(result, AS_NAPI_VALUE(jval)); NAPI_RETURN(napi_ok); } static void iotjs_napi_arraybuffer_external_free_cb(void* native_p) { IOTJS_UNUSED(native_p); } napi_status napi_create_external_arraybuffer(napi_env env, void* external_data, size_t byte_length, napi_finalize finalize_cb, void* finalize_hint, napi_value* result) { NAPI_TRY_ENV(env); NAPI_WEAK_ASSERT_WITH_MSG(napi_invalid_arg, external_data != NULL, "External data pointer could not be NULL."); NAPI_WEAK_ASSERT_WITH_MSG(napi_invalid_arg, byte_length != 0, "External data byte length could not be 0."); if (!jerry_is_feature_enabled(JERRY_FEATURE_TYPEDARRAY)) { NAPI_ASSIGN(result, NULL); NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_typedarray); } JERRYX_CREATE(jval_arrbuf, jerry_create_arraybuffer_external( byte_length, external_data, iotjs_napi_arraybuffer_external_free_cb)); iotjs_object_info_t* info = iotjs_get_object_native_info(jval_arrbuf, sizeof(iotjs_object_info_t)); info->env = env; info->native_object = external_data; info->finalize_hint = finalize_hint; info->finalize_cb = finalize_cb; NAPI_ASSIGN(result, AS_NAPI_VALUE(jval_arrbuf)); NAPI_RETURN(napi_ok); } napi_status napi_create_typedarray(napi_env env, napi_typedarray_type type, size_t length, napi_value arraybuffer, size_t byte_offset, napi_value* result) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_TYPEDARRAY)) { NAPI_ASSIGN(result, NULL); NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_typedarray); } jerry_typedarray_type_t jtype; #define CASE_NAPI_TYPEDARRAY_TYPE(type_name, jtype_name) \ case napi_##type_name##_array: \ jtype = JERRY_TYPEDARRAY_##jtype_name; \ break; switch (type) { CASE_NAPI_TYPEDARRAY_TYPE(int8, INT8); CASE_NAPI_TYPEDARRAY_TYPE(uint8, UINT8); CASE_NAPI_TYPEDARRAY_TYPE(uint8_clamped, UINT8CLAMPED); CASE_NAPI_TYPEDARRAY_TYPE(int16, INT16); CASE_NAPI_TYPEDARRAY_TYPE(uint16, UINT16); CASE_NAPI_TYPEDARRAY_TYPE(int32, INT32); CASE_NAPI_TYPEDARRAY_TYPE(uint32, UINT32); CASE_NAPI_TYPEDARRAY_TYPE(float32, FLOAT32); CASE_NAPI_TYPEDARRAY_TYPE(float64, FLOAT64); default: jtype = JERRY_TYPEDARRAY_INVALID; } #undef CASE_NAPI_TYPEDARRAY_TYPE jerry_value_t jval_arraybuffer = AS_JERRY_VALUE(arraybuffer); JERRYX_CREATE(jval, jerry_create_typedarray_for_arraybuffer_sz(jtype, jval_arraybuffer, byte_offset, length)); NAPI_ASSIGN(result, AS_NAPI_VALUE(jval)); NAPI_RETURN(napi_ok); } napi_status napi_create_buffer(napi_env env, size_t size, void** data, napi_value* result) { NAPI_TRY_ENV(env); JERRYX_CREATE(jval_buf, iotjs_bufferwrap_create_buffer(size)); iotjs_bufferwrap_t* buf_wrap = iotjs_bufferwrap_from_jbuffer(jval_buf); NAPI_ASSIGN(data, buf_wrap->buffer); return napi_assign_nvalue(jval_buf, result); } napi_status napi_create_buffer_copy(napi_env env, size_t size, const void* data, void** result_data, napi_value* result) { NAPI_TRY_ENV(env); JERRYX_CREATE(jval_buf, iotjs_bufferwrap_create_buffer(size)); iotjs_bufferwrap_t* buf_wrap = iotjs_bufferwrap_from_jbuffer(jval_buf); iotjs_bufferwrap_copy(buf_wrap, (char*)data, size); NAPI_ASSIGN(result_data, buf_wrap->buffer); return napi_assign_nvalue(jval_buf, result); } napi_status napi_create_dataview(napi_env env, size_t byte_length, napi_value arraybuffer, size_t byte_offset, napi_value* result) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_DATAVIEW)) { NAPI_ASSIGN(result, NULL); NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_dataview); } NAPI_WEAK_ASSERT_WITH_MSG(napi_invalid_arg, byte_length != 0, "External data byte length could not be 0."); jerry_value_t jval_arraybuffer = AS_JERRY_VALUE(arraybuffer); NAPI_WEAK_ASSERT_WITH_MSG(napi_invalid_arg, jerry_value_is_arraybuffer(jval_arraybuffer), "Argument must be a valid ArrayBuffer object."); JERRYX_CREATE(jval_dv, jerry_create_dataview(jval_arraybuffer, byte_offset, byte_length)); NAPI_ASSIGN(result, AS_NAPI_VALUE(jval_dv)); NAPI_RETURN(napi_ok); } static void napi_external_destroy(iotjs_object_info_t* info) { if (info->finalize_cb != NULL) { info->finalize_cb(info->env, info->native_object, info->finalize_hint); } IOTJS_RELEASE(info); } static const jerry_object_native_info_t napi_external_native_info = { .free_cb = (jerry_object_native_free_callback_t)napi_external_destroy }; napi_status napi_create_external(napi_env env, void* data, napi_finalize finalize_cb, void* finalize_hint, napi_value* result) { NAPI_TRY_ENV(env); napi_value nval; NAPI_INTERNAL_CALL(napi_create_object(env, &nval)); iotjs_object_info_t* info = (iotjs_object_info_t*)iotjs_buffer_allocate(sizeof(iotjs_object_info_t)); info->native_object = data; info->finalize_cb = finalize_cb; info->finalize_hint = finalize_hint; jerry_set_object_native_pointer(AS_JERRY_VALUE(nval), info, &napi_external_native_info); NAPI_ASSIGN(result, nval); NAPI_RETURN(napi_ok); } napi_status napi_create_external_buffer(napi_env env, size_t length, void* data, napi_finalize finalize_cb, void* finalize_hint, napi_value* result) { NAPI_TRY_ENV(env); char* nval = NULL; napi_value res; NAPI_INTERNAL_CALL( napi_create_buffer_copy(env, length, data, (void**)&nval, &res)); jerry_value_t jbuffer = AS_JERRY_VALUE(res); iotjs_bufferwrap_t* bufferwrap = iotjs_bufferwrap_from_jbuffer(jbuffer); iotjs_buffer_external_info_t* info = IOTJS_ALLOC(iotjs_buffer_external_info_t); info->env = env; info->external_data = data; info->finalize_hint = finalize_hint; info->finalize_cb = finalize_cb; iotjs_bufferwrap_set_external_callback(bufferwrap, iotjs_napi_buffer_external_free_cb, info); NAPI_ASSIGN(result, res); NAPI_RETURN(napi_ok); } napi_status napi_create_object(napi_env env, napi_value* result) { NAPI_TRY_ENV(env); JERRYX_CREATE(jval, jerry_create_object()); return napi_assign_nvalue(jval, result); } static napi_status napi_create_error_helper(jerry_error_t jerry_error_type, napi_env env, napi_value code, napi_value msg, napi_value* result) { NAPI_TRY_ENV(env); jerry_value_t jval_code = AS_JERRY_VALUE(code); jerry_value_t jval_msg = AS_JERRY_VALUE(msg); NAPI_TRY_TYPE(string, jval_msg); jerry_size_t msg_size = jerry_get_utf8_string_size(jval_msg); jerry_char_t* raw_msg = IOTJS_CALLOC(msg_size + 1, jerry_char_t); jerry_size_t written_size = jerry_string_to_utf8_char_buffer(jval_msg, raw_msg, msg_size); NAPI_WEAK_ASSERT(napi_invalid_arg, written_size == msg_size); raw_msg[msg_size] = '\0'; jerry_value_t jval_error = jerry_create_error(jerry_error_type, raw_msg); IOTJS_RELEASE(raw_msg); /** code has to be an JS string type, thus it can not be an number 0 */ if (code != NULL) { NAPI_TRY_TYPE(string, jval_code); jval_error = jerry_get_value_from_error(jval_error, true); iotjs_jval_set_property_jval(jval_error, IOTJS_MAGIC_STRING_CODE, jval_code); } jerryx_create_handle(jval_error); NAPI_ASSIGN(result, AS_NAPI_VALUE(jval_error)); NAPI_RETURN(napi_ok); } napi_status napi_create_error(napi_env env, napi_value code, napi_value msg, napi_value* result) { return napi_create_error_helper(JERRY_ERROR_COMMON, env, code, msg, result); } napi_status napi_create_range_error(napi_env env, napi_value code, napi_value msg, napi_value* result) { return napi_create_error_helper(JERRY_ERROR_RANGE, env, code, msg, result); } napi_status napi_create_type_error(napi_env env, napi_value code, napi_value msg, napi_value* result) { return napi_create_error_helper(JERRY_ERROR_TYPE, env, code, msg, result); } static napi_status napi_number_convert_from_c_type_helper(napi_env env, double value, napi_value* result) { NAPI_TRY_ENV(env); JERRYX_CREATE(jval, jerry_create_number(value)); return napi_assign_nvalue(jval, result); } #define DEF_NAPI_NUMBER_CONVERT_FROM_C_TYPE(type, name) \ napi_status napi_create_##name(napi_env env, type value, \ napi_value* result) { \ return napi_number_convert_from_c_type_helper(env, (double)value, result); \ } DEF_NAPI_NUMBER_CONVERT_FROM_C_TYPE(int32_t, int32); DEF_NAPI_NUMBER_CONVERT_FROM_C_TYPE(uint32_t, uint32); DEF_NAPI_NUMBER_CONVERT_FROM_C_TYPE(int64_t, int64); DEF_NAPI_NUMBER_CONVERT_FROM_C_TYPE(double, double); #undef DEF_NAPI_NUMBER_CONVERT_FROM_C_TYPE napi_status napi_get_value_double(napi_env env, napi_value value, double* result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(value); NAPI_TRY_TYPE(number, jval); NAPI_ASSIGN(result, jerry_get_number_value(jval)); NAPI_RETURN(napi_ok); } #define DEF_NAPI_NUMBER_CONVERT_FROM_NVALUE(type, name) \ napi_status napi_get_value_##name(napi_env env, napi_value value, \ type* result) { \ NAPI_TRY_ENV(env); \ jerry_value_t jval = AS_JERRY_VALUE(value); \ NAPI_TRY_TYPE(number, jval); \ double num = jerry_get_number_value(jval); \ if (isinf(num) || isnan(num)) { \ num = 0; \ } \ NAPI_ASSIGN(result, num); \ NAPI_RETURN(napi_ok); \ } DEF_NAPI_NUMBER_CONVERT_FROM_NVALUE(int32_t, int32); DEF_NAPI_NUMBER_CONVERT_FROM_NVALUE(int64_t, int64); DEF_NAPI_NUMBER_CONVERT_FROM_NVALUE(uint32_t, uint32); #undef DEF_NAPI_NUMBER_CONVERT_FROM_NVALUE napi_status napi_create_symbol(napi_env env, napi_value description, napi_value* result) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_SYMBOL)) { NAPI_ASSIGN(result, NULL); NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_symbol); } JERRYX_CREATE(jval, jerry_create_symbol(AS_JERRY_VALUE(description))); NAPI_ASSIGN(result, AS_NAPI_VALUE(jval)); NAPI_RETURN(napi_ok); } napi_status napi_create_string_utf8(napi_env env, const char* str, size_t length, napi_value* result) { NAPI_TRY_ENV(env); if (length == NAPI_AUTO_LENGTH) { length = strlen(str); } JERRYX_CREATE(jval, jerry_create_string_sz_from_utf8((jerry_char_t*)str, length)); return napi_assign_nvalue(jval, result); } napi_status napi_get_array_length(napi_env env, napi_value value, uint32_t* result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(value); NAPI_ASSIGN(result, jerry_get_array_length(jval)); NAPI_RETURN(napi_ok); } napi_status napi_get_arraybuffer_info(napi_env env, napi_value arraybuffer, void** data, size_t* byte_length) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_TYPEDARRAY)) { NAPI_ASSIGN(byte_length, 0); NAPI_ASSIGN(data, NULL); NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_typedarray); } jerry_value_t jval = AS_JERRY_VALUE(arraybuffer); jerry_length_t len = jerry_get_arraybuffer_byte_length(jval); /** * WARNING: if the arraybuffer is managed by js engine, * write beyond address limit may lead to an unpredictable result. */ uint8_t* ptr = jerry_get_arraybuffer_pointer(jval); NAPI_ASSIGN(byte_length, len); NAPI_ASSIGN(data, ptr); NAPI_RETURN(napi_ok); } napi_status napi_get_buffer_info(napi_env env, napi_value value, void** data, size_t* length) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(value); iotjs_bufferwrap_t* buf_wrap = iotjs_bufferwrap_from_jbuffer(jval); NAPI_ASSIGN(data, buf_wrap->buffer); NAPI_ASSIGN(length, iotjs_bufferwrap_length(buf_wrap)); NAPI_RETURN(napi_ok); } napi_status napi_get_prototype(napi_env env, napi_value object, napi_value* result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(object); JERRYX_CREATE(jval_proto, jerry_get_prototype(jval)); return napi_assign_nvalue(jval_proto, result); } napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(value); NAPI_TRY_TYPE(boolean, jval); return napi_assign_bool(jerry_get_boolean_value(jval), result); } napi_status napi_get_boolean(napi_env env, bool value, napi_value* result) { NAPI_TRY_ENV(env); JERRYX_CREATE(jval, jerry_create_boolean(value)); return napi_assign_nvalue(jval, result); } napi_status napi_get_dataview_info(napi_env env, napi_value dataview, size_t* byte_length, void** data, napi_value* arraybuffer, size_t* byte_offset) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_DATAVIEW)) { NAPI_ASSIGN(byte_length, 0); NAPI_ASSIGN(data, NULL); NAPI_ASSIGN(arraybuffer, AS_NAPI_VALUE(jerry_create_undefined())); NAPI_ASSIGN(byte_offset, 0); NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_dataview); } jerry_value_t jval = AS_JERRY_VALUE(dataview); NAPI_WEAK_ASSERT_WITH_MSG(napi_invalid_arg, jerry_value_is_dataview(jval), "Argument must be a valid DataView object."); JERRYX_CREATE(jval_arraybuffer, jerry_get_dataview_buffer(jval, (jerry_length_t*)byte_offset, (jerry_length_t*)byte_length)); uint8_t* ptr = jerry_get_arraybuffer_pointer(jval_arraybuffer); NAPI_ASSIGN(arraybuffer, AS_NAPI_VALUE(jval_arraybuffer)); NAPI_ASSIGN(data, ptr); NAPI_RETURN(napi_ok); } napi_status napi_get_typedarray_info(napi_env env, napi_value typedarray, napi_typedarray_type* type, size_t* length, void** data, napi_value* arraybuffer, size_t* byte_offset) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_TYPEDARRAY)) { NAPI_ASSIGN(type, napi_int8_array); NAPI_ASSIGN(length, 0); NAPI_ASSIGN(data, NULL); NAPI_ASSIGN(arraybuffer, AS_NAPI_VALUE(jerry_create_undefined())); NAPI_ASSIGN(byte_offset, 0); NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_typedarray); } jerry_value_t jval = AS_JERRY_VALUE(typedarray); jerry_typedarray_type_t jtype = jerry_get_typedarray_type(jval); napi_typedarray_type ntype; #define CASE_JERRY_TYPEDARRAY_TYPE(jtype_name, type_name) \ case JERRY_TYPEDARRAY_##jtype_name: { \ ntype = napi_##type_name##_array; \ break; \ } switch (jtype) { CASE_JERRY_TYPEDARRAY_TYPE(INT8, int8); CASE_JERRY_TYPEDARRAY_TYPE(UINT8, uint8); CASE_JERRY_TYPEDARRAY_TYPE(UINT8CLAMPED, uint8_clamped); CASE_JERRY_TYPEDARRAY_TYPE(INT16, int16); CASE_JERRY_TYPEDARRAY_TYPE(UINT16, uint16); CASE_JERRY_TYPEDARRAY_TYPE(INT32, int32); CASE_JERRY_TYPEDARRAY_TYPE(UINT32, uint32); CASE_JERRY_TYPEDARRAY_TYPE(FLOAT32, float32); default: { IOTJS_ASSERT(jtype == JERRY_TYPEDARRAY_FLOAT64); ntype = napi_float64_array; break; } } #undef CASE_JERRY_TYPEDARRAY_TYPE jerry_length_t jlength = jerry_get_typedarray_length(jval); jerry_length_t jbyte_offset; jerry_length_t jbyte_length; JERRYX_CREATE(jval_arraybuffer, jerry_get_typedarray_buffer(jval, &jbyte_offset, &jbyte_length)); /** * WARNING: if the arraybuffer is managed by js engine, * write beyond address limit may lead to an unpredictable result. */ uint8_t* ptr = jerry_get_arraybuffer_pointer(jval); NAPI_ASSIGN(type, ntype); NAPI_ASSIGN(length, jlength); NAPI_ASSIGN(data, ptr); NAPI_ASSIGN(arraybuffer, AS_NAPI_VALUE(jval_arraybuffer)); NAPI_ASSIGN(byte_offset, jbyte_offset); NAPI_RETURN(napi_ok); } napi_status napi_get_value_external(napi_env env, napi_value value, void** result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(value); iotjs_object_info_t* info = NULL; if (!jerry_get_object_native_pointer(jval, (void**)&info, &napi_external_native_info)) { NAPI_ASSIGN(result, NULL); NAPI_RETURN_WITH_MSG(napi_invalid_arg, "Argument must be type of 'napi_external'."); } NAPI_ASSIGN(result, info->native_object); NAPI_RETURN(napi_ok); } napi_status napi_get_value_string_utf8(napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(value); NAPI_TRY_TYPE(string, jval); size_t str_size = jerry_get_utf8_string_size(jval); if (buf == NULL) { /* null terminator is excluded */ NAPI_ASSIGN(result, str_size); NAPI_RETURN(napi_ok); } jerry_size_t written_size = jerry_string_to_utf8_char_buffer(jval, (jerry_char_t*)buf, bufsize); NAPI_WEAK_ASSERT_WITH_MSG(napi_generic_failure, str_size == 0 || (bufsize > 0 && written_size != 0), "Insufficient buffer not supported yet."); /* expects one more byte to write null terminator */ if (bufsize > written_size) { buf[written_size] = '\0'; } NAPI_ASSIGN(result, written_size); NAPI_RETURN(napi_ok); } napi_status napi_get_global(napi_env env, napi_value* result) { NAPI_TRY_ENV(env); JERRYX_CREATE(jval, jerry_get_global_object()); return napi_assign_nvalue(jval, result); } napi_status napi_get_null(napi_env env, napi_value* result) { NAPI_TRY_ENV(env); JERRYX_CREATE(jval, jerry_create_null()); return napi_assign_nvalue(jval, result); } napi_status napi_get_undefined(napi_env env, napi_value* result) { NAPI_TRY_ENV(env); JERRYX_CREATE(jval, jerry_create_undefined()); return napi_assign_nvalue(jval, result); } napi_status napi_coerce_to_bool(napi_env env, napi_value value, napi_value* result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(value); bool res = jerry_value_to_boolean(jval); JERRYX_CREATE(jval_result, jerry_create_boolean(res)); NAPI_ASSIGN(result, AS_NAPI_VALUE(jval_result)); NAPI_RETURN(napi_ok); } #define DEF_NAPI_COERCE_TO(type, alias) \ napi_status napi_coerce_to_##type(napi_env env, napi_value value, \ napi_value* result) { \ NAPI_TRY_ENV(env); \ jerry_value_t jval = AS_JERRY_VALUE(value); \ JERRYX_CREATE(jval_result, jerry_value_to_##alias(jval)); \ return napi_assign_nvalue(jval_result, result); \ } DEF_NAPI_COERCE_TO(number, number); DEF_NAPI_COERCE_TO(object, object); DEF_NAPI_COERCE_TO(string, string); napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result) { NAPI_TRY_ENV(env); jerry_value_t jval = AS_JERRY_VALUE(value); jerry_type_t type = jerry_value_get_type(jval); switch (type) { case JERRY_TYPE_UNDEFINED: { NAPI_ASSIGN(result, napi_undefined); break; } case JERRY_TYPE_NULL: { NAPI_ASSIGN(result, napi_null); break; } case JERRY_TYPE_BOOLEAN: { NAPI_ASSIGN(result, napi_boolean); break; } case JERRY_TYPE_NUMBER: { NAPI_ASSIGN(result, napi_number); break; } case JERRY_TYPE_STRING: { NAPI_ASSIGN(result, napi_string); break; } case JERRY_TYPE_SYMBOL: { NAPI_ASSIGN(result, napi_symbol); break; } case JERRY_TYPE_OBJECT: { if (jerry_get_object_native_pointer(jval, NULL, &napi_external_native_info)) { NAPI_ASSIGN(result, napi_external); } else { NAPI_ASSIGN(result, napi_object); } break; } case JERRY_TYPE_FUNCTION: { NAPI_ASSIGN(result, napi_function); break; } default: NAPI_RETURN(napi_invalid_arg); } NAPI_RETURN(napi_ok); } #define DEF_NAPI_VALUE_IS(type) \ napi_status napi_is_##type(napi_env env, napi_value value, bool* result) { \ NAPI_TRY_ENV(env); \ return napi_assign_bool(jerry_value_is_##type(AS_JERRY_VALUE(value)), \ result); \ } DEF_NAPI_VALUE_IS(array); DEF_NAPI_VALUE_IS(arraybuffer); DEF_NAPI_VALUE_IS(dataview); DEF_NAPI_VALUE_IS(typedarray); napi_status napi_is_buffer(napi_env env, napi_value value, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval_global = jerry_get_global_object(); jerry_value_t jval_buffer = iotjs_jval_get_property(jval_global, IOTJS_MAGIC_STRING_BUFFER); napi_status status = napi_instanceof(env, value, AS_NAPI_VALUE(jval_buffer), result); jerry_release_value(jval_buffer); jerry_release_value(jval_global); return status; } napi_status napi_is_error(napi_env env, napi_value value, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval_global = jerry_get_global_object(); jerry_value_t jval_error = iotjs_jval_get_property(jval_global, IOTJS_MAGIC_STRING_ERROR); napi_status status = napi_instanceof(env, value, AS_NAPI_VALUE(jval_error), result); jerry_release_value(jval_error); jerry_release_value(jval_global); return status; } napi_status napi_instanceof(napi_env env, napi_value object, napi_value constructor, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval_object = AS_JERRY_VALUE(object); jerry_value_t jval_cons = AS_JERRY_VALUE(constructor); jerry_value_t is_instance = jerry_binary_operation(JERRY_BIN_OP_INSTANCEOF, jval_object, jval_cons); if (jerry_value_is_error(is_instance)) { jerry_release_value(is_instance); NAPI_ASSIGN(result, false); } else { NAPI_ASSIGN(result, jerry_get_boolean_value(is_instance)); } NAPI_RETURN(napi_ok); } napi_status napi_strict_equals(napi_env env, napi_value lhs, napi_value rhs, bool* result) { NAPI_TRY_ENV(env); jerry_value_t jval_lhs = AS_JERRY_VALUE(lhs); jerry_value_t jval_rhs = AS_JERRY_VALUE(rhs); jerry_value_t is_equal = jerry_binary_operation(JERRY_BIN_OP_STRICT_EQUAL, jval_lhs, jval_rhs); if (jerry_value_is_error(is_equal)) { jerry_release_value(is_equal); NAPI_RETURN(napi_generic_failure); } return napi_assign_bool(jerry_get_boolean_value(is_equal), result); } napi_status napi_create_promise(napi_env env, napi_deferred* deferred, napi_value* promise) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_PROMISE)) { NAPI_ASSIGN(promise, NULL); NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_promise); } if (deferred == NULL) { NAPI_ASSIGN(promise, NULL); NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_invalid_deferred); } jerry_value_t jpromise = jerry_create_promise(); napi_assign_nvalue(jpromise, promise); *deferred = malloc(sizeof(napi_value*)); memcpy(*deferred, promise, sizeof(napi_value*)); NAPI_RETURN(napi_ok); } napi_status napi_resolve_deferred(napi_env env, napi_deferred deferred, napi_value resolution) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_PROMISE)) { NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_promise); } if (deferred == NULL) { NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_invalid_deferred); } jerry_value_t promise = AS_JERRY_VALUE(*((napi_value*)deferred)); jerry_value_t res = jerry_resolve_or_reject_promise(promise, AS_JERRY_VALUE(resolution), true); jerry_release_value(promise); free(deferred); if (jerry_value_is_error(res)) { NAPI_INTERNAL_CALL(napi_throw(env, AS_NAPI_VALUE(res))); NAPI_RETURN(napi_pending_exception); } NAPI_RETURN(napi_ok); } napi_status napi_reject_deferred(napi_env env, napi_deferred deferred, napi_value rejection) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_PROMISE)) { NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_promise); } if (deferred == NULL) { NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_invalid_deferred); } jerry_value_t promise = AS_JERRY_VALUE(*((napi_value*)deferred)); jerry_value_t res = jerry_resolve_or_reject_promise(promise, AS_JERRY_VALUE(rejection), false); jerry_release_value(promise); free(deferred); if (jerry_value_is_error(res)) { NAPI_INTERNAL_CALL(napi_throw(env, AS_NAPI_VALUE(res))); NAPI_RETURN(napi_pending_exception); } NAPI_RETURN(napi_ok); } napi_status napi_is_promise(napi_env env, napi_value promise, bool* is_promise) { NAPI_TRY_ENV(env); if (!jerry_is_feature_enabled(JERRY_FEATURE_PROMISE)) { NAPI_RETURN_WITH_MSG(napi_generic_failure, napi_err_no_promise); } *is_promise = jerry_value_is_promise(AS_JERRY_VALUE(promise)); NAPI_RETURN(napi_ok); } iotjs-1.0+715/src/napi/node_symbols.txt000066400000000000000000000044231371177304000177740ustar00rootroot00000000000000napi_add_env_cleanup_hook napi_async_destroy napi_async_init napi_call_function napi_cancel_async_work napi_close_callback_scope napi_close_escapable_handle_scope napi_close_handle_scope napi_coerce_to_bool napi_coerce_to_number napi_coerce_to_object napi_coerce_to_string napi_create_array napi_create_arraybuffer napi_create_array_with_length napi_create_async_work napi_create_buffer napi_create_buffer_copy napi_create_dataview napi_create_double napi_create_error napi_create_external napi_create_external_arraybuffer napi_create_external_buffer napi_create_function napi_create_int32 napi_create_int64 napi_create_object napi_create_promise napi_create_range_error napi_create_reference napi_create_string_utf8 napi_create_symbol napi_create_typedarray napi_create_type_error napi_create_uint32 napi_define_class napi_define_properties napi_delete_async_work napi_delete_element napi_delete_property napi_delete_reference napi_escape_handle napi_fatal_error napi_fatal_exception napi_get_and_clear_last_exception napi_get_arraybuffer_info napi_get_array_length napi_get_boolean napi_get_buffer_info napi_get_cb_info napi_get_dataview_info napi_get_element napi_get_global napi_get_last_error_info napi_get_named_property napi_get_new_target napi_get_node_version napi_get_null napi_get_property napi_get_property_names napi_get_prototype napi_get_reference_value napi_get_typedarray_info napi_get_undefined napi_get_uv_event_loop napi_get_value_bool napi_get_value_double napi_get_value_external napi_get_value_int32 napi_get_value_int64 napi_get_value_string_utf8 napi_get_value_uint32 napi_get_version napi_has_element napi_has_named_property napi_has_own_property napi_has_property napi_instanceof napi_is_array napi_is_arraybuffer napi_is_buffer napi_is_dataview napi_is_error napi_is_exception_pending napi_is_promise napi_is_typedarray napi_make_callback napi_module_register napi_new_instance napi_open_callback_scope napi_open_escapable_handle_scope napi_open_handle_scope napi_queue_async_work napi_reference_ref napi_reference_unref napi_reject_deferred napi_remove_env_cleanup_hook napi_remove_wrap napi_resolve_deferred napi_set_element napi_set_named_property napi_set_property napi_strict_equals napi_throw napi_throw_error napi_throw_range_error napi_throw_type_error napi_typeof napi_unwrap napi_wrap iotjs-1.0+715/src/platform/000077500000000000000000000000001371177304000154305ustar00rootroot00000000000000iotjs-1.0+715/src/platform/linux/000077500000000000000000000000001371177304000165675ustar00rootroot00000000000000iotjs-1.0+715/src/platform/linux/iotjs_linux.c000066400000000000000000000013331371177304000213020ustar00rootroot00000000000000/* 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.h" int main(int argc, char** argv) { return iotjs_entry(argc, argv); } iotjs-1.0+715/src/platform/linux/iotjs_systemio-linux.c000066400000000000000000000121301371177304000231510ustar00rootroot00000000000000/* 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 #include #include "iotjs_systemio-linux.h" // Checks if given directory exists. bool iotjs_systemio_check_path(const char* path) { const iotjs_environment_t* env = iotjs_environment_get(); DDDLOG("%s - path: %s", __func__, path); // stat for the path. uv_fs_t fs_req; int err = uv_fs_stat(iotjs_environment_loop(env), &fs_req, path, NULL); uv_fs_req_cleanup(&fs_req); // exist? if (err || fs_req.result) { return false; } DDDLOG("%s - path exist", __func__); return true; } bool iotjs_systemio_open_write_close(const char* path, const char* value) { const iotjs_environment_t* env = iotjs_environment_get(); uv_loop_t* loop = iotjs_environment_loop(env); DDDLOG("%s - path %s, value: %s", __func__, path, value); // Open file uv_fs_t fs_req; int fd = uv_fs_open(loop, &fs_req, path, O_WRONLY, 0666, NULL); uv_fs_req_cleanup(&fs_req); if (fd < 0) { DLOG("%s - open %s failed: %d", __func__, path, fd); return false; } // Write value // We remove const because `uv_buf_init` requires char* for only reading case. uv_buf_t uvbuf = uv_buf_init((char*)value, strlen(value)); int write_err = uv_fs_write(loop, &fs_req, fd, &uvbuf, 1, 0, NULL); uv_fs_req_cleanup(&fs_req); // Close file int close_err = uv_fs_close(loop, &fs_req, fd, NULL); uv_fs_req_cleanup(&fs_req); if (write_err < 0) { DLOG("%s - write %s %s failed: %d", __func__, path, value, write_err); return false; } if (close_err < 0) { DLOG("%s - close failed: %d", __func__, close_err); return false; } return true; } bool iotjs_systemio_open_read_close(const char* path, char* buffer, unsigned buffer_len) { const iotjs_environment_t* env = iotjs_environment_get(); uv_loop_t* loop = iotjs_environment_loop(env); DDDLOG("%s - path %s", __func__, path); // Open file uv_fs_t fs_open_req; int fd = uv_fs_open(loop, &fs_open_req, path, O_RDONLY, 0666, NULL); uv_fs_req_cleanup(&fs_open_req); if (fd < 0) { DLOG("%s - open %s failed: %d", __func__, path, fd); return false; } // Read value uv_fs_t fs_write_req; uv_buf_t uvbuf = uv_buf_init(buffer, buffer_len); int err = uv_fs_read(loop, &fs_write_req, fd, &uvbuf, 1, 0, NULL); uv_fs_req_cleanup(&fs_write_req); if (err < 0) { DLOG("%s - read failed: %d", __func__, err); return false; } DDDLOG("%s - read value: %s", __func__, buffer); // Close file uv_fs_t fs_close_req; err = uv_fs_close(loop, &fs_close_req, fd, NULL); uv_fs_req_cleanup(&fs_close_req); if (err < 0) { DLOG("%s - close failed: %d", __func__, err); return false; } return true; } // Device Open bool iotjs_systemio_device_open(const char* export_path, uint32_t value, const char* exported_path, const char** created_files, int created_files_length) { // Be already exported if (iotjs_systemio_check_path(exported_path)) { return true; } DDDLOG("%s - path: %s", __func__, export_path); // Write export pin. char buff[DEVICE_IO_PIN_BUFFER_SIZE] = { 0 }; snprintf(buff, DEVICE_IO_PIN_BUFFER_SIZE - 1, "%d", value); if (!iotjs_systemio_open_write_close(export_path, buff)) { return false; } // Wait for directory creation. int count = 0; int count_limit = created_files_length * 10; char buffer[DEVICE_IO_PIN_BUFFER_SIZE]; char path[DEVICE_IO_PATH_BUFFER_SIZE] = { 0 }; while (!iotjs_systemio_check_path(exported_path) && count < count_limit) { usleep(100 * 1000); // sleep 100 miliseconds. count++; } for (int i = 0; i < created_files_length; i++) { snprintf(path, DEVICE_IO_PATH_BUFFER_SIZE - 1, "%s%s", exported_path, created_files[i]); DDDLOG("%s - created file: %s", __func__, path); while (!iotjs_systemio_open_read_close(path, buffer, DEVICE_IO_PIN_BUFFER_SIZE) && count < count_limit) { usleep(100 * 1000); // sleep 100 miliseconds. count++; } } usleep(1000 * 100); // sleep another 1000 milisec. return count < count_limit; } // Device close bool iotjs_systemio_device_close(const char* export_path, uint32_t value) { DDDLOG("%s - path: %s", __func__, export_path); char buff[DEVICE_IO_PIN_BUFFER_SIZE]; snprintf(buff, DEVICE_IO_PIN_BUFFER_SIZE - 1, "%d", value); if (!iotjs_systemio_open_write_close(export_path, buff)) { return false; } return true; } iotjs-1.0+715/src/platform/linux/iotjs_systemio-linux.h000066400000000000000000000026201371177304000231610ustar00rootroot00000000000000/* 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_LINUX_H #define IOTJS_SYSTEMIO_LINUX_H #include "iotjs_def.h" #define DEVICE_IO_PATH_BUFFER_SIZE 64 #define DEVICE_IO_PIN_BUFFER_SIZE 10 bool iotjs_systemio_check_path(const char* path); bool iotjs_systemio_open_write_close(const char* path, const char* value); bool iotjs_systemio_open_read_close(const char* path, char* buffer, unsigned buffer_len); bool iotjs_systemio_device_open(const char* export_path, uint32_t value, const char* exported_path, const char** created_files, int created_files_length); bool iotjs_systemio_device_close(const char* export_path, uint32_t value); #endif /* IOTJS_SYSTEMIO_LINUX_H */ iotjs-1.0+715/src/platform/nuttx/000077500000000000000000000000001371177304000166125ustar00rootroot00000000000000iotjs-1.0+715/src/platform/nuttx/iotjs_systemio-nuttx.c000066400000000000000000000044131371177304000232240ustar00rootroot00000000000000/* 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__) && (defined(TARGET_BOARD_STM32F4DIS) || \ (defined(TARGET_BOARD_STM32F7NUCLEO))) #include #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 }; #if defined(TARGET_BOARD_STM32F4DIS) return stm32_adcinitialize(number, channel_list, 1); #elif defined(TARGET_BOARD_STM32F7NUCLEO) return stm32_adc_initialize(number, channel_list, 1); #endif } #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_SPI */ #endif // __NUTTX__ iotjs-1.0+715/src/platform/nuttx/iotjs_systemio-nuttx.h000066400000000000000000000041651371177304000232350ustar00rootroot00000000000000/* 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_NUTTX_H #define IOTJS_SYSTEMIO_NUTTX_H #include #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 #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 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 struct pwm_lowerhalf_s* iotjs_pwm_config_nuttx(int timer, uint32_t pin); #endif /* ENABLE_MODULE_PWM */ #if ENABLE_MODULE_SPI #include struct spi_dev_s* iotjs_spi_config_nuttx(int bus, uint32_t cs_chip); #endif /* ENABLE_MODULE_SPI */ #endif /* IOTJS_SYSTEMIO_NUTTX_H */ iotjs-1.0+715/src/platform/tizen/000077500000000000000000000000001371177304000165615ustar00rootroot00000000000000iotjs-1.0+715/src/platform/tizen/iotjs_tizen_service_app.c000066400000000000000000000131061371177304000236470ustar00rootroot00000000000000/* Copyright 2018-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 #include #include #include #include #include "iotjs_def.h" #include "iotjs.h" extern bool iotjs_initialize(iotjs_environment_t* env); extern void iotjs_run(iotjs_environment_t* env); extern void iotjs_end(iotjs_environment_t* env); extern void iotjs_terminate(iotjs_environment_t* env); static char js_absolute_path[128]; static GMainLoop* gmain_loop; static bool is_env_initialized = false; typedef struct { GSource source; iotjs_environment_t* env; } iotjs_gmain_source_t; static int console_log(int level, const char* format, ...) { va_list args; va_start(args, format); dlog_vprint(DLOG_INFO, "IOTJS", format, args); va_end(args); return 0; } static gboolean gmain_loop_check(GSource* source) { return TRUE; } static gboolean gmain_loop_dispatch(GSource* source, GSourceFunc callback, gpointer user_data) { iotjs_environment_t* env = ((iotjs_gmain_source_t*)source)->env; bool more = uv_run(iotjs_environment_loop(env), UV_RUN_NOWAIT); more |= iotjs_process_next_tick(); jerry_value_t ret_val = jerry_run_all_enqueued_jobs(); if (jerry_value_is_error(ret_val)) { DLOG("jerry_run_all_enqueued_jobs() failed"); } if (more == false) { more = uv_loop_alive(iotjs_environment_loop(env)); } if (!more || iotjs_environment_is_exiting(env)) { service_app_exit(); return false; } return true; } static void loop_method_init_cb(int argc, char** argv, void* data) { int iotjs_argc = 2; char* iotjs_argv[2] = { "iotjs", js_absolute_path }; #ifdef ENABLE_DEBUG_LOG setenv("IOTJS_DEBUG_LEVEL", "3", 0); // Enable all log. #endif // Initialize debug log and environments iotjs_debuglog_init(); iotjs_environment_t* env = iotjs_environment_get(); if (!iotjs_environment_parse_command_line_arguments(env, (uint32_t)iotjs_argc, iotjs_argv)) { service_app_exit(); return; } is_env_initialized = true; if (!iotjs_initialize(env)) { DLOG("iotjs_initialize failed"); service_app_exit(); return; } DDDLOG("%s", __func__); iotjs_conf_console_out(console_log); } static void loop_method_run_cb(void* data) { DDDLOG("%s", __func__); iotjs_environment_t* env = iotjs_environment_get(); iotjs_environment_set_state(env, kRunningMain); // Load and call iotjs.js. iotjs_run(env); if (iotjs_environment_is_exiting(env)) { service_app_exit(); return; } // Create GMain loop. gmain_loop = g_main_loop_new(g_main_context_default(), FALSE); // Add GSource in GMain context. GSourceFuncs source_funcs = { .check = gmain_loop_check, .dispatch = gmain_loop_dispatch, }; iotjs_gmain_source_t* source = (iotjs_gmain_source_t*)g_source_new(&source_funcs, sizeof(iotjs_gmain_source_t)); source->env = env; uv_loop_t* uv_loop = iotjs_environment_loop(env); g_source_add_unix_fd(&source->source, uv_loop->backend_fd, (GIOCondition)(G_IO_IN | G_IO_OUT | G_IO_ERR)); g_source_attach(&source->source, g_main_context_default()); iotjs_environment_set_state(env, kRunningLoop); g_main_loop_run(gmain_loop); // Blocks until loop is quit. if (!iotjs_environment_is_exiting(env)) { // Emit 'exit' event. iotjs_process_emit_exit(iotjs_process_exitcode()); iotjs_environment_set_state(env, kExiting); } DDDLOG("%s: Exit IoT.js(%d).", __func__, iotjs_process_exitcode()); iotjs_end(env); } static void loop_method_exit_cb(void* data) { DDDLOG("%s", __func__); if (g_main_loop_is_running(gmain_loop)) { g_main_loop_quit(gmain_loop); g_main_loop_unref(gmain_loop); } } static void loop_method_fini_cb(void) { DDDLOG("%s", __func__); iotjs_environment_t* env = iotjs_environment_get(); if (is_env_initialized) { iotjs_terminate(env); } iotjs_environment_release(); iotjs_debuglog_release(); } int iotjs_service_app_start(int argc, char** argv, char* js_path, void* event_callbacks, void* user_data) { DDDLOG("%s", __func__); char* app_res_path = app_get_resource_path(); if (!app_res_path) { DLOG("app_res_path is NULL!"); return 1; } // The JavaScript entry file is located in application res directory. snprintf(js_absolute_path, sizeof(js_absolute_path), "%s%s", app_res_path, js_path); setenv(IOTJS_MAGIC_STRING_IOTJS_WORKING_DIR_PATH_U, app_res_path, 1); IOTJS_RELEASE(app_res_path); service_app_loop_method_s loop_method = {.init = loop_method_init_cb, .run = loop_method_run_cb, .exit = loop_method_exit_cb, .fini = loop_method_fini_cb }; return service_app_main_ext(argc, argv, (service_app_lifecycle_callback_s*) event_callbacks, &loop_method, user_data); } iotjs-1.0+715/src/platform/tizen/iotjs_tizen_service_app.h000066400000000000000000000034421371177304000236560ustar00rootroot00000000000000/* Copyright 2018-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_TIZEN_SERVICE_APP_H #define IOTJS_TIZEN_SERVICE_APP_H #include #include #ifdef __cplusplus #define IOTJS_EXTERN_C extern "C" #else /* !__cplusplus */ #define IOTJS_EXTERN_C extern #endif /* !__cplusplus */ typedef void (*user_callback_t)(int error, const char* data); IOTJS_EXTERN_C int iotjs_service_app_start(int argc, char** argv, char* js_path, void* event_callbacks, void* user_data); IOTJS_EXTERN_C void iotjs_tizen_app_control_cb(app_control_h app_control, void* user_data); IOTJS_EXTERN_C int iotjs_tizen_bridge_native(const char* fn_name, unsigned fn_name_size, const char* message, unsigned message_size, user_callback_t cb); #define IOTJS_TIZEN_CALL_JFUNC(name, msg, cb) \ ({ \ if (name != NULL && (msg) != NULL) \ iotjs_tizen_bridge_native(name, strlen(name), msg, strlen(msg), cb); \ }) #endif /* IOTJS_TIZEN_SERVICE_APP_H */ iotjs-1.0+715/src/platform/tizenrt/000077500000000000000000000000001371177304000171275ustar00rootroot00000000000000iotjs-1.0+715/src/platform/tizenrt/iotjs_main_tizenrt.c000066400000000000000000000144401371177304000232110ustar00rootroot00000000000000/* 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. */ /**************************************************************************** * Included Files ****************************************************************************/ #include #include #include #include #include #include #ifdef JERRY_DEBUGGER #include #endif /* JERRY_DEBUGGER */ #include "jerryscript-port.h" #include "jerryscript.h" #define USE_IOTJS_THREAD 1 /** * 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 local time zone adjustment, in milliseconds, * for the given timestamp. */ double jerry_port_get_local_time_zone_adjustment(double unix_ms, bool is_utc) { (void)unix_ms; (void)is_utc; return 0.0; } /* jerry_port_get_local_time_zone_adjustment */ /** * Get system time * * @return milliseconds since Unix epoch */ double jerry_port_get_current_time(void) { struct timespec ts; /* Get the current time */ int ret = clock_gettime(CLOCK_REALTIME, &ts); if (ret < 0) { return 0.0; } return ((double)ts.tv_sec) * 1000.0 + ((double)ts.tv_nsec) / 1000000.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 */ /** * Determines the size of the given file. * @return size of the file */ static size_t jerry_port_get_file_size(FILE *file_p) /**< opened file */ { fseek(file_p, 0, SEEK_END); long size = ftell(file_p); fseek(file_p, 0, SEEK_SET); return (size_t)size; } /* jerry_port_get_file_size */ /** * Opens file with the given path and reads its source. * @return the source of the file */ uint8_t *jerry_port_read_source(const char *file_name_p, /**< file name */ size_t *out_size_p) /**< [out] read bytes */ { FILE *file_p = fopen(file_name_p, "rb"); if (file_p == NULL) { jerry_port_log(JERRY_LOG_LEVEL_ERROR, "Error: failed to open file: %s\n", file_name_p); return NULL; } size_t file_size = jerry_port_get_file_size(file_p); uint8_t *buffer_p = (uint8_t *)malloc(file_size); if (buffer_p == NULL) { fclose(file_p); jerry_port_log(JERRY_LOG_LEVEL_ERROR, "Error: failed to allocate memory for module"); return NULL; } size_t bytes_read = fread(buffer_p, 1u, file_size, file_p); if (!bytes_read) { fclose(file_p); free(buffer_p); jerry_port_log(JERRY_LOG_LEVEL_ERROR, "Error: failed to read file: %s\n", file_name_p); return NULL; } fclose(file_p); *out_size_p = bytes_read; return buffer_p; } /* jerry_port_read_source */ /** * Release the previously opened file's content. */ void jerry_port_release_source(uint8_t *buffer_p) /**< buffer to free */ { free(buffer_p); } /* jerry_port_release_source */ /** * Normalize a file path * * @return length of the path written to the output buffer */ size_t jerry_port_normalize_path( const char *in_path_p, /**< input file path */ char *out_buf_p, /**< output buffer */ size_t out_buf_size) /**< size of output buffer */ { size_t len = strlen(in_path_p); if (len + 1 > out_buf_size) { return 0; } /* Return the original string. */ strcpy(out_buf_p, in_path_p); return len; } /* jerry_port_normalize_path */ #ifdef JERRY_DEBUGGER void jerry_port_sleep(uint32_t sleep_time) { nanosleep( &(const struct timespec){ (time_t)sleep_time / 1000, ((long int)sleep_time % 1000) * 1000000L /* Seconds, nanoseconds */ }, NULL); } /* jerry_port_sleep */ #endif /* JERRY_DEBUGGER */ 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; #ifdef CONFIG_DEBUG_VERBOSE int ret = iotjs_entry(arg->argc, arg->argv); printf("IoT.js Result: %d\n", ret); #else iotjs_entry(arg->argc, arg->argv); #endif tuv_cleanup(); sleep(1); return NULL; } int iotjs(int argc, char *argv[]) { pthread_attr_t attr; int status; struct sched_param sparam; pthread_t tid = (pthread_t)0; 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); #ifdef CONFIG_DEBUG_VERBOSE printf("IoT.js Result: %d\n", ret); #endif tuv_cleanup(); return ret; } #endif int iotjs_register_cmds(void) { tash_cmd_install("iotjs", iotjs, TASH_EXECMD_SYNC); return 0; } iotjs-1.0+715/test/000077500000000000000000000000001371177304000137745ustar00rootroot00000000000000iotjs-1.0+715/test/external_modules/000077500000000000000000000000001371177304000173465ustar00rootroot00000000000000iotjs-1.0+715/test/external_modules/mymodule1/000077500000000000000000000000001371177304000212625ustar00rootroot00000000000000iotjs-1.0+715/test/external_modules/mymodule1/js/000077500000000000000000000000001371177304000216765ustar00rootroot00000000000000iotjs-1.0+715/test/external_modules/mymodule1/js/helloworld.js000066400000000000000000000013261371177304000244110ustar00rootroot00000000000000/* 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. */ module.exports = { foo: function() { return "Hello"; }, message: " world!" } iotjs-1.0+715/test/external_modules/mymodule1/modules.json000066400000000000000000000001741371177304000236270ustar00rootroot00000000000000{ "modules": { "mymodule1": { "js_file": "js/helloworld.js", "require": ["buffer", "console"] } } } iotjs-1.0+715/test/external_modules/mymodule2/000077500000000000000000000000001371177304000212635ustar00rootroot00000000000000iotjs-1.0+715/test/external_modules/mymodule2/modules.json000066400000000000000000000001731371177304000236270ustar00rootroot00000000000000{ "modules": { "mymodule2": { "native_files": ["my_module.c"], "init": "InitMyNativeModule" } } } iotjs-1.0+715/test/external_modules/mymodule2/my_module.c000066400000000000000000000015201371177304000234170ustar00rootroot00000000000000/* 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 "iotjs_def.h" jerry_value_t InitMyNativeModule() { jerry_value_t mymodule = jerry_create_object(); iotjs_jval_set_property_string_raw(mymodule, "message", "Hello world!"); return mymodule; } iotjs-1.0+715/test/external_modules/test-external-module1.js000066400000000000000000000014101371177304000240430ustar00rootroot00000000000000/* 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 mymodule = require('mymodule1'); assert.equal(mymodule.foo() + mymodule.message, "Hello world!"); iotjs-1.0+715/test/external_modules/test-external-module2.js000066400000000000000000000013671371177304000240570ustar00rootroot00000000000000/* 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 mymodule = require('mymodule2'); assert.equal(mymodule.message, "Hello world!"); iotjs-1.0+715/test/hello.js000066400000000000000000000012371371177304000154400ustar00rootroot00000000000000/* Copyright 2019-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. */ console.log("Hello IoT.js!"); iotjs-1.0+715/test/module_generator/000077500000000000000000000000001371177304000173275ustar00rootroot00000000000000iotjs-1.0+715/test/module_generator/test.py000077500000000000000000000072371371177304000206740ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2019-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. import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'tools')) from common_py import path from common_py.system.executor import Executor as ex from common_py.system.filesystem import FileSystem as fs module_generator_dir = fs.join(path.TOOLS_ROOT, 'module_generator') generator_script = fs.join(path.TOOLS_ROOT, 'iotjs-generate-module.py') build_script = fs.join(path.TOOLS_ROOT, 'build.py') def print_green(msg): print ('\033[1;32m{}\033[00m'.format(msg)) def print_blue(msg): print ('\033[1;34m{}\033[00m'.format(msg)) def test_c(): test_dir = fs.join(os.path.dirname(__file__), 'test_c') test_c = fs.join(test_dir, 'test.c') # Compile test.c and make a static library print_blue('Compile C test module.') ex.check_run_cmd_output('cc', ['-c', test_c, '-o', test_dir + '/test.o']) ex.check_run_cmd_output('ar', ['-cr', test_dir + '/libtest.a', test_dir + '/test.o']) # Generate test_module print_blue('Generate binding for C test module.') ex.check_run_cmd_output(generator_script, [test_dir, 'c']) # Build iotjs print_blue('Build IoT.js.') module_dir = fs.join(module_generator_dir, 'output', 'test_c_module') args = [ '--external-module=' + module_dir, '--cmake-param=-DENABLE_MODULE_TEST_C_MODULE=ON', '--jerry-profile=es2015-subset', '--clean' ] ex.check_run_cmd_output(build_script, args) run_test_js(test_dir) print_green('C test succeeded.') def test_cpp(): test_dir = fs.join(os.path.dirname(__file__), 'test_cpp') test_cpp = fs.join(test_dir, 'test.cpp') # Compile test.c and make a static library print_blue('Compile C++ test module.') ex.check_run_cmd_output('c++', ['-c', test_cpp, '-o', test_dir + '/test.o']) ex.check_run_cmd_output('ar', ['-cr', test_dir + '/libtest.a', test_dir + '/test.o']) # Generate test_module print_blue('Generate binding for C++ test module.') ex.check_run_cmd_output(generator_script, [test_dir, 'c++']) # Build iotjs print_blue('Build IoT.js.') module_dir = fs.join(module_generator_dir, 'output', 'test_cpp_module') args = [ '--external-module=' + module_dir, '--cmake-param=-DENABLE_MODULE_TEST_CPP_MODULE=ON', '--jerry-profile=es2015-subset', '--clean' ] ex.check_run_cmd_output(build_script, args) run_test_js(test_dir) print_green('C++ test succeeded.') def run_test_js(test_dir): # Run test.js print_blue('Run test.js file.') binary = fs.join(path.BUILD_ROOT, 'x86_64-linux', 'debug', 'bin', 'iotjs') test_js = fs.join(test_dir, 'test.js') ex.check_run_cmd_output(binary, [test_js]) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-x', choices=['c', 'c++'], action='append', default=[], help='Specify language.') args = parser.parse_args() if not args.x: test_c() test_cpp() if 'c' in args.x: test_c() if 'c++' in args.x: test_cpp() iotjs-1.0+715/test/module_generator/test_c/000077500000000000000000000000001371177304000206105ustar00rootroot00000000000000iotjs-1.0+715/test/module_generator/test_c/test.c000066400000000000000000000025561371177304000217430ustar00rootroot00000000000000/* Copyright 2019-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 "test.h" void f_void(void) { return; } int f_int(int a) { return a; } char f_char(char a) { return a; } e f_enum(e a) { return a; } float f_float(float a) { return a; } double f_double(double a) { return a; } _Bool f_bool(_Bool a) { return a; } S f_struct(S a) { return a; } U f_union(U a) { return a; } char* f_char_ptr(char* a) { return a; } char* f_char_arr(char a[5]) { return a; } int* f_int_ptr(int* a) { return a; } int* f_int_arr(int a[5]) { return a; } int f_func(func f) { if (f) { return f(); } return 0; } int f_func_ptr(func_ptr f) { if (f) { return f(); } return 0; } void f_struct_ptr(S* s) { s->c = 's'; s->i = 42; } void f_union_ptr(U* u) { u->i = 65; } iotjs-1.0+715/test/module_generator/test_c/test.h000066400000000000000000000033131371177304000217400ustar00rootroot00000000000000/* Copyright 2019-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 TEST_H #define TEST_H #define BIN 0b101 #define DEC 42 #define OCT 017 #define HEX 0xFF #define one_l 1l #define one_L 1L #define one_u 1u #define one_U 1U #define SIGNED -42 #define FLOAT 1.5 #define SFLOAT -1.5 #define PI 314159E-5 #define CH 'a' #define STRING "AaBb" #define ONE 1 #define TWO ONE + 1 #define THREE (ONE) | (TWO) char c; int i; typedef enum { A, B = 10 } e; float f; double d; _Bool b; char* c_ptr; char c_arr[5]; int* i_ptr; int i_arr[5]; typedef struct { int i; char c; } S; typedef struct { const int i; } const_S; typedef union { int i; char c; } U; typedef union { const int i; } const_U; S s; const_S const_s; U u; const_U const_u; typedef int(func)(void); typedef int (*func_ptr)(void); void f_void(void); int f_int(int); char f_char(char); e f_enum(e); float f_float(float); double f_double(double); _Bool f_bool(_Bool); S f_struct(S); U f_union(U); char* f_char_ptr(char*); char* f_char_arr(char[5]); int* f_int_ptr(int*); int* f_int_arr(int[5]); int f_func(func); int f_func_ptr(func_ptr); void f_struct_ptr(S*); void f_union_ptr(U*); #endif iotjs-1.0+715/test/module_generator/test_c/test.js000066400000000000000000000120411371177304000221230ustar00rootroot00000000000000/* Copyright 2019-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 lib = require("test_c_module"); // MACROS assert.equal(lib.BIN, 5); assert.equal(lib.DEC, 42); assert.equal(lib.OCT, 15); assert.equal(lib.HEX, 255); assert.equal(lib.one_l, 1); assert.equal(lib.one_L, 1); assert.equal(lib.one_u, 1); assert.equal(lib.one_U, 1); assert.equal(lib.SIGNED, -42); assert.equal(lib.FLOAT, 1.5); assert.equal(lib.SFLOAT, -1.5); assert.equal(lib.PI, 3.14159); assert.equal(lib.CH, 'a'); assert.equal(lib.STRING, 'AaBb'); assert.equal(lib.ONE, 1); assert.equal(lib.TWO, 2); assert.equal(lib.THREE, 3); // VARIABLES assert.equal(lib.c, '\u0000'); assert.equal(lib.i, 0); assert.equal(lib.A, 0); assert.equal(lib.B, 10); assert.equal(lib.f, 0); assert.equal(lib.d, 0); assert.equal(lib.b, false); assert.equal(lib.c_ptr, null); assert.equal(lib.c_arr, ''); assert.equal(lib.i_ptr, null); assert.equal(lib.i_arr.length, 5); for (var i = 0; i < 5; i++) { assert.equal(lib.i_arr[i], 0); } assert.equal(lib.s.i, 0); assert.equal(lib.s.c, '\u0000'); assert.equal(lib.u.i, 0); assert.equal(lib.u.c, '\u0000'); lib.c = 'Z'; assert.equal(lib.c, 'Z'); lib.i = 42; assert.equal(lib.i, 42); lib.A = 1; lib.B = 2; assert.equal(lib.A, 0); assert.equal(lib.B, 10); lib.f = 1.5; assert.equal(lib.f, 1.5); lib.d = 2.5; assert.equal(lib.d, 2.5); lib.b = undefined; assert(!lib.b); lib.b = null; assert(!lib.b); lib.b = true; assert(lib.b); lib.b = 0; assert(!lib.b); lib.b = 1; assert(lib.b); lib.b = ''; assert(!lib.b); lib.b = 't'; assert(lib.b); lib.b = {}; assert(lib.b); lib.c_ptr = 'abcdefghijklmnopqrstuvwxyz'; assert.equal(lib.c_ptr, 'abcdefghijklmnopqrstuvwxyz'); lib.c_ptr = ''; assert.equal(lib.c_ptr, ''); lib.c_arr = 'a'; assert.equal(lib.c_arr, 'a'); lib.c_arr = 'ab'; assert.equal(lib.c_arr, 'ab'); lib.c_arr = 'abc'; assert.equal(lib.c_arr, 'abc'); lib.c_arr = 'abcd'; assert.equal(lib.c_arr, 'abcd'); lib.c_arr = 'abcde'; assert.equal(lib.c_arr, 'abcd'); var i_ptr = new Int32Array(new ArrayBuffer(4), 0, 1); i_ptr[0] = 42; lib.i_ptr = i_ptr; assert.equal(lib.i_ptr[0], 42); assert.equal(lib.i_ptr[0], i_ptr[0]); assert(lib.i_ptr instanceof Int32Array); lib.i_ptr = null; assert.equal(lib.i_ptr, null); assert(lib.i_arr instanceof Int32Array); for (var i = 0; i < 5; i++) { lib.i_arr[i] = i*i; } for (var i = 0; i < 5; i++) { assert.equal(lib.i_arr[i], i*i); } lib.i_arr = null; assert(lib.i_arr instanceof Int32Array); var s = new lib.S(); s.i = 42; s.c = 's'; lib.s = s; assert.equal(lib.s.i, 42); assert.equal(lib.s.c, 's'); lib.s.i = 100; lib.s.c = 'c'; assert.equal(lib.s.i, 100); assert.equal(lib.s.c, 'c'); var c_s = new lib.const_S(); assert.equal(c_s.i, 0); c_s.i = 42; assert.equal(c_s.i, 0); c_s = new lib.const_S({ i : 42 }); assert.equal(c_s.i, 42); c_s.i = 0; assert.equal(c_s.i, 42); assert.equal(lib.const_s.i, 0); lib.const_s.i = 42; assert.equal(lib.const_s.i, 0); var u = new lib.U(); u.i = 65; lib.u = u; assert.equal(lib.u.i, 65); assert.equal(lib.u.c, 'A'); lib.u.i = 66; assert.equal(lib.u.c, 'B'); var c_u = new lib.const_U(); assert.equal(c_u.i, 0); c_u.i = 42; assert.equal(c_u.i, 0); c_u = new lib.const_U({ i : 42 }); assert.equal(c_u.i, 42); c_u.i = 0; assert.equal(c_u.i, 42); assert.equal(lib.const_u.i, 0); lib.const_u.i = 42; assert.equal(lib.const_u.i, 0); // FUNCTIONS assert.equal(lib.f_void(), undefined); assert.equal(lib.f_int(5), 5); assert.equal(lib.f_char('a'), 'a'); assert.equal(lib.f_enum(lib.A), 0); assert.equal(lib.f_float(1.5), 1.5); assert.equal(lib.f_double(2.5), 2.5); assert.equal(lib.f_bool(true), true); assert.equal(lib.f_struct(s).i, 42); assert.equal(lib.f_struct(s).c, 's'); assert.equal(lib.f_union(u).i, 65); assert.equal(lib.f_union(u).c, 'A'); assert.equal(lib.f_char_ptr(null), null); assert.equal(lib.f_char_ptr('string'), 'string'); assert.equal(lib.f_char_arr(null), null); assert.equal(lib.f_char_arr('string'), 'string'); assert.equal(lib.f_int_ptr(null), null); assert.equal(lib.f_int_ptr(i_ptr)[0], 42); assert.equal(lib.f_int_arr(null), null); assert.equal(lib.f_int_arr(i_ptr)[0], 42); assert.equal(lib.f_func(null), 0); assert.equal(lib.f_func(function () { return 42; }), 42); assert.equal(lib.f_func_ptr(null), 0); assert.equal(lib.f_func_ptr(function () { return 42; }), 42); s.c = '\u0000'; s.i = 0; assert.equal(s.c, '\u0000'); assert.equal(s.i, 0); lib.f_struct_ptr(s); assert.equal(s.c, 's'); assert.equal(s.i, 42); u.i = 0; assert.equal(u.c, '\u0000'); assert.equal(u.i, 0); lib.f_union_ptr(u); assert.equal(u.c, 'A'); assert.equal(u.i, 65); iotjs-1.0+715/test/module_generator/test_cpp/000077500000000000000000000000001371177304000211505ustar00rootroot00000000000000iotjs-1.0+715/test/module_generator/test_cpp/test.cpp000066400000000000000000000060351371177304000226370ustar00rootroot00000000000000/* Copyright 2019-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 "test.h" char c; int i; float f; double d; bool b; char* c_ptr; char c_arr[5]; int* i_ptr; int i_arr[5]; S s; const_S const_s = {0}; U u; const_U const_u = {0}; void f_void (void) { return; } int f_int (int a) { return a; } char f_char (char a) { return a; } e f_enum (e a) { return a; } float f_float (float a) { return a; } double f_double (double a) { return a; } bool f_bool (bool a) { return a; } S f_struct (S a) { return a; } U f_union (U a) { return a; } char* f_char_ptr (char* a) { return a; } char* f_char_arr (char a[5]) { return a; } int* f_int_ptr (int* a) { return a; } int* f_int_arr (int a[5]) { return a; } int f_func (func f) { if (f) { return f(); } return 0; } int f_func_ptr (func_ptr f) { if (f) { return f(); } return 0; } void f_struct_ptr(S* s) { s->c = 's'; s->i = 42; } void f_union_ptr(U* u) { u->i = 65; } char Test::get_c() { return _c; } void Test::set_c(char c) { _c = c; } int Test::get_i() { return _i; } void Test::set_i(int i) { _i = i; } float Test::get_f() { return _f; } void Test::set_f(float f) { _f = f; } double Test::get_d() { return _d; } void Test::set_d(double d) { _d = d; } bool Test::get_b() { return _b; } void Test::set_b(bool b) { _b = b; } char* Test::get_c_ptr() { return _c_ptr; } void Test::set_c_ptr(char* c_ptr, int size) { if (_c_ptr) { delete _c_ptr; } _c_ptr = new char[sizeof(char) * size + 1]; for (int i = 0; i < size; i++) { _c_ptr[i] = c_ptr[i]; } _c_ptr[size] = '\0'; } char* Test::get_c_arr() { return _c_arr; } void Test::set_c_arr(char c_arr[5]) { for (int i = 0; i < 4; i++) { _c_arr[i] = c_arr[i]; } } int* Test::get_i_ptr() { return _i_ptr; } void Test::set_i_ptr(int* i_ptr, int size) { if (_i_ptr) { delete _i_ptr; } _i_ptr = new int[sizeof(int) * size]; for (int i = 0; i < size; i++) { _i_ptr[i] = i_ptr[i]; } } int* Test::get_i_arr() { return _i_arr; } void Test::set_i_arr(int i_arr[5]) { for (int i = 0; i < 5; i++) { _i_arr[i] = i_arr[i]; } } S Test::get_s() { return _s; } void Test::set_s(S s) { _s.i = s.i; _s.c = s.c; } U Test::get_u() { return _u; } void Test::set_u(U u) { _u.i = u.i; _u.c = u.c; } O Test::get_o() { return _o; } void Test::set_o(O o) { _o = o; } int test_ns::A::foo() { return 1; } int test_ns::nested_ns::A::foo() { return 2; } iotjs-1.0+715/test/module_generator/test_cpp/test.h000066400000000000000000000054111371177304000223010ustar00rootroot00000000000000/* Copyright 2019-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. */ #pragma once #define BIN 0b101 #define DEC 42 #define OCT 017 #define HEX 0xFF #define one_l 1l #define one_L 1L #define one_u 1u #define one_U 1U #define SIGNED -42 #define FLOAT 1.5 #define SFLOAT -1.5 #define PI 314159E-5 #define CH 'a' #define STRING "AaBb" #define ONE 1 #define TWO ONE + 1 #define THREE (ONE) | (TWO) extern char c; extern int i; typedef enum { A, B = 10 } e; extern float f; extern double d; extern bool b; extern char* c_ptr; extern char c_arr[5]; extern int* i_ptr; extern int i_arr[5]; typedef struct { int i; char c; } S; typedef struct { const int i; } const_S; typedef union { int i; char c; } U; typedef union { const int i; } const_U; extern S s; extern const_S const_s; extern U u; extern const_U const_u; typedef int(func)(void); typedef int (*func_ptr)(void); void f_void(void); int f_int(int); char f_char(char); e f_enum(e); float f_float(float); double f_double(double); bool f_bool(bool); S f_struct(S); U f_union(U); char* f_char_ptr(char*); char* f_char_arr(char[5]); int* f_int_ptr(int*); int* f_int_arr(int[5]); int f_func(func); int f_func_ptr(func_ptr); void f_struct_ptr(S*); void f_union_ptr(U*); class O { int _i; public: O() : _i(42) { } int get_i() { return _i; } void set_i(int i) { _i = i; } }; class Test { char _c; int _i; float _f; double _d; bool _b; char* _c_ptr; char _c_arr[5]; int* _i_ptr; int _i_arr[5]; S _s; U _u; O _o; public: char c; int i; float f; double d; bool b; char* c_ptr; char c_arr[5]; int* i_ptr; int i_arr[5]; S s; U u; O o; char get_c(); void set_c(char); int get_i(); void set_i(int); float get_f(); void set_f(float); double get_d(); void set_d(double); bool get_b(); void set_b(bool); char* get_c_ptr(); void set_c_ptr(char*, int); char* get_c_arr(); void set_c_arr(char[5]); int* get_i_ptr(); void set_i_ptr(int*, int); int* get_i_arr(); void set_i_arr(int[5]); S get_s(); void set_s(S); U get_u(); void set_u(U); O get_o(); void set_o(O); }; namespace test_ns { namespace nested_ns { class A { public: int foo(); }; } class A { public: int foo(); }; } iotjs-1.0+715/test/module_generator/test_cpp/test.js000066400000000000000000000205371371177304000224740ustar00rootroot00000000000000/* Copyright 2019-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 lib = require("test_cpp_module"); // MACROS assert.equal(lib.BIN, 5); assert.equal(lib.DEC, 42); assert.equal(lib.OCT, 15); assert.equal(lib.HEX, 255); assert.equal(lib.one_l, 1); assert.equal(lib.one_L, 1); assert.equal(lib.one_u, 1); assert.equal(lib.one_U, 1); assert.equal(lib.SIGNED, -42); assert.equal(lib.FLOAT, 1.5); assert.equal(lib.SFLOAT, -1.5); assert.equal(lib.PI, 3.14159); assert.equal(lib.CH, 'a'); assert.equal(lib.STRING, 'AaBb'); assert.equal(lib.ONE, 1); assert.equal(lib.TWO, 2); assert.equal(lib.THREE, 3); // VARIABLES assert.equal(lib.c, '\u0000'); assert.equal(lib.i, 0); assert.equal(lib.A, 0); assert.equal(lib.B, 10); assert.equal(lib.f, 0); assert.equal(lib.d, 0); assert.equal(lib.b, false); assert.equal(lib.c_ptr, null); assert.equal(lib.c_arr, ''); assert.equal(lib.i_ptr, null); assert.equal(lib.i_arr.length, 5); for (var i = 0; i < 5; i++) { assert.equal(lib.i_arr[i], 0); } assert.equal(lib.s.i, 0); assert.equal(lib.s.c, '\u0000'); assert.equal(lib.u.i, 0); assert.equal(lib.u.c, '\u0000'); lib.c = 'Z'; assert.equal(lib.c, 'Z'); lib.i = 42; assert.equal(lib.i, 42); lib.A = 1; lib.B = 2; assert.equal(lib.A, 0); assert.equal(lib.B, 10); lib.f = 1.5; assert.equal(lib.f, 1.5); lib.d = 2.5; assert.equal(lib.d, 2.5); lib.b = undefined; assert(!lib.b); lib.b = null; assert(!lib.b); lib.b = true; assert(lib.b); lib.b = 0; assert(!lib.b); lib.b = 1; assert(lib.b); lib.b = ''; assert(!lib.b); lib.b = 't'; assert(lib.b); lib.b = {}; assert(lib.b); lib.c_ptr = 'abcdefghijklmnopqrstuvwxyz'; assert.equal(lib.c_ptr, 'abcdefghijklmnopqrstuvwxyz'); lib.c_ptr = ''; assert.equal(lib.c_ptr, ''); lib.c_arr = 'a'; assert.equal(lib.c_arr, 'a'); lib.c_arr = 'ab'; assert.equal(lib.c_arr, 'ab'); lib.c_arr = 'abc'; assert.equal(lib.c_arr, 'abc'); lib.c_arr = 'abcd'; assert.equal(lib.c_arr, 'abcd'); lib.c_arr = 'abcde'; assert.equal(lib.c_arr, 'abcd'); var i_ptr = new Int32Array(new ArrayBuffer(4), 0, 1); i_ptr[0] = 42; lib.i_ptr = i_ptr; assert.equal(lib.i_ptr[0], 42); assert.equal(lib.i_ptr[0], i_ptr[0]); assert(lib.i_ptr instanceof Int32Array); lib.i_ptr = null; assert.equal(lib.i_ptr, null); assert(lib.i_arr instanceof Int32Array); for (var i = 0; i < 5; i++) { lib.i_arr[i] = i*i; } for (var i = 0; i < 5; i++) { assert.equal(lib.i_arr[i], i*i); } lib.i_arr = null; assert(lib.i_arr instanceof Int32Array); var s = new lib.S(); s.i = 42; s.c = 's'; lib.s = s; assert.equal(lib.s.i, 42); assert.equal(lib.s.c, 's'); lib.s.i = 100; lib.s.c = 'c'; assert.equal(lib.s.i, 100); assert.equal(lib.s.c, 'c'); var c_s = new lib.const_S(); assert.equal(c_s.i, 0); c_s.i = 42; assert.equal(c_s.i, 0); c_s = new lib.const_S({ i : 42 }); assert.equal(c_s.i, 42); c_s.i = 0; assert.equal(c_s.i, 42); assert.equal(lib.const_s.i, 0); lib.const_s.i = 42; assert.equal(lib.const_s.i, 0); var u = new lib.U(); u.i = 65; lib.u = u; assert.equal(lib.u.i, 65); assert.equal(lib.u.c, 'A'); lib.u.i = 66; assert.equal(lib.u.c, 'B'); var c_u = new lib.const_U(); assert.equal(c_u.i, 0); c_u.i = 42; assert.equal(c_u.i, 0); c_u = new lib.const_U({ i : 42 }); assert.equal(c_u.i, 42); c_u.i = 0; assert.equal(c_u.i, 42); assert.equal(lib.const_u.i, 0); lib.const_u.i = 42; assert.equal(lib.const_u.i, 0); // FUNCTIONS assert.equal(lib.f_void(), undefined); assert.equal(lib.f_int(5), 5); assert.equal(lib.f_char('a'), 'a'); assert.equal(lib.f_enum(lib.A), 0); assert.equal(lib.f_float(1.5), 1.5); assert.equal(lib.f_double(2.5), 2.5); assert.equal(lib.f_bool(true), true); assert.equal(lib.f_struct(s).i, 42); assert.equal(lib.f_struct(s).c, 's'); assert.equal(lib.f_union(u).i, 65); assert.equal(lib.f_union(u).c, 'A'); assert.equal(lib.f_char_ptr(null), null); assert.equal(lib.f_char_ptr('string'), 'string'); assert.equal(lib.f_char_arr(null), null); assert.equal(lib.f_char_arr('string'), 'string'); assert.equal(lib.f_int_ptr(null), null); assert.equal(lib.f_int_ptr(i_ptr)[0], 42); assert.equal(lib.f_int_arr(null), null); assert.equal(lib.f_int_arr(i_ptr)[0], 42); assert.equal(lib.f_func(null), 0); assert.equal(lib.f_func(function () { return 42; }), 42); assert.equal(lib.f_func_ptr(null), 0); assert.equal(lib.f_func_ptr(function () { return 42; }), 42); s.c = '\u0000'; s.i = 0; assert.equal(s.c, '\u0000'); assert.equal(s.i, 0); lib.f_struct_ptr(s); assert.equal(s.c, 's'); assert.equal(s.i, 42); u.i = 0; assert.equal(u.c, '\u0000'); assert.equal(u.i, 0); lib.f_union_ptr(u); assert.equal(u.c, 'A'); assert.equal(u.i, 65); // CLASS test = new lib.Test(); // public members assert.equal(test.c, '\u0000'); assert.equal(test.i, 0); assert.equal(test.f, 0); assert.equal(test.d, 0); assert.equal(test.b, false); assert.equal(test.c_ptr, null); assert.equal(test.c_arr, ''); assert.equal(test.i_ptr, null); assert.equal(test.i_arr.length, 5); for (var i = 0; i < 5; i++) { assert.equal(test.i_arr[i], 0); } // char test.c = 'Z'; assert.equal(test.c, 'Z'); // int test.i = 42; assert.equal(test.i, 42); // float test.f = 1.5; assert.equal(test.f, 1.5); // double test.d = 2.5; assert.equal(test.d, 2.5); // bool test.b = true; assert(test.b); // char* test.c_ptr = 'abcdefghijklmnopqrstuvwxyz'; assert.equal(test.c_ptr, 'abcdefghijklmnopqrstuvwxyz'); test.c_ptr = ''; assert.equal(test.c_ptr, ''); // char[] test.c_arr = 'a'; assert.equal(test.c_arr, 'a'); test.c_arr = 'ab'; assert.equal(test.c_arr, 'ab'); test.c_arr = 'abc'; assert.equal(test.c_arr, 'abc'); test.c_arr = 'abcd'; assert.equal(test.c_arr, 'abcd'); test.c_arr = 'abcde'; assert.equal(test.c_arr, 'abcd'); // int* test.i_ptr = i_ptr; assert.equal(test.i_ptr[0], 42); assert.equal(test.i_ptr[0], i_ptr[0]); assert(test.i_ptr instanceof Int32Array); test.i_ptr = null; assert.equal(test.i_ptr, null); // int[] assert(test.i_arr instanceof Int32Array); for (var i = 0; i < 5; i++) { test.i_arr[i] = i*i; } for (var i = 0; i < 5; i++) { assert.equal(test.i_arr[i], i*i); } test.i_arr = null; assert(test.i_arr instanceof Int32Array); // S struct test.s = s; assert.equal(test.s.i, 42); assert.equal(test.s.c, 's'); // U union test.u = u; assert.equal(test.u.i, 65); assert.equal(test.u.c, 'A'); // O class assert.equal(test.o.get_i(), 42); var o = new lib.O(); o.set_i(100); test.o = o; assert.equal(test.o.get_i(), 100); // private members assert.equal(test.get_c(), '\u0000'); assert.equal(test.get_i(), 0); assert.equal(test.get_f(), 0); assert.equal(test.get_d(), 0); assert.equal(test.get_b(), false); assert.equal(test.get_c_ptr(), null); assert.equal(test.get_c_arr(), ''); assert.equal(test.get_i_ptr(), null); assert.equal(test.get_i_arr()[0], 0); assert(test.get_i_arr() instanceof Int32Array); // char test.set_c('Z'); assert.equal(test.get_c(), 'Z'); // int test.set_i(42); assert.equal(test.get_i(), 42); // float test.set_f(1.5); assert.equal(test.get_f(), 1.5); // double test.set_d(2.5); assert.equal(test.get_d(), 2.5); // bool test.set_b(true); assert(test.get_b()); // char* test.set_c_ptr('abcde', 5); assert.equal(test.get_c_ptr(), 'abcde'); // char[] test.set_c_arr('abcd'); assert.equal(test.get_c_arr(), 'abcd'); // int* test.set_i_ptr(i_ptr, 1); assert.equal(test.get_i_ptr()[0], 42); // int[] test.set_i_arr(i_ptr); assert.equal(test.get_i_arr()[0], 42); // S struct test.set_s(s); assert.equal(test.get_s().i, 42); assert.equal(test.get_s().c, 's'); // U union test.set_u(u); assert.equal(test.get_u().i, 65); assert.equal(test.get_u().c, 'A'); // O class assert.equal(test.get_o().get_i(), 42); test.set_o(o); assert.equal(test.get_o().get_i(), 100); // NAMESPACE test_ns_A = new lib.test_ns.A(); assert.equal(test_ns_A.foo(), 1); test_ns_nested_ns_A = new lib.test_ns.nested_ns.A(); assert.equal(test_ns_nested_ns_A.foo(), 2); with (lib.test_ns) { test_ns_A = new A(); assert.equal(test_ns_A.foo(), 1); with (nested_ns) { test_ns_nested_ns_A = new A(); assert.equal(test_ns_nested_ns_A.foo(), 2); } } iotjs-1.0+715/test/napi/000077500000000000000000000000001371177304000147235ustar00rootroot00000000000000iotjs-1.0+715/test/napi/.gitignore000066400000000000000000000000151371177304000167070ustar00rootroot00000000000000build *.node iotjs-1.0+715/test/napi/binding.gyp000066400000000000000000000042221371177304000170560ustar00rootroot00000000000000{ "targets": [ { "target_name": "test_napi_arguments", "sources": [ "test_napi_arguments.c" ] }, { "target_name": "test_napi_array", "sources": [ "test_napi_array.c" ] }, { "target_name": "test_napi_async", "sources": [ "test_napi_async.c" ] }, { "target_name": "test_napi_buffer", "sources": [ "test_napi_buffer.c" ] }, { "target_name": "test_napi_construct", "sources": [ "test_napi_construct.c" ] }, { "target_name": "test_napi_conversions", "sources": [ "test_napi_conversions.c" ] }, { "target_name": "test_napi_dataview", "sources": [ "test_napi_dataview.c" ] }, { "target_name": "test_napi_env_compare", "sources": [ "test_napi_env_compare.c" ] }, { "target_name": "test_napi_env_store", "sources": [ "test_napi_env_store.c" ] }, { "target_name": "test_napi_error_handling", "sources": [ "test_napi_error_handling.c" ] }, { "target_name": "test_napi_general", "sources": [ "test_napi_general.c" ] }, { "target_name": "test_napi_make_callback", "sources": [ "test_napi_make_callback.c" ] }, { "target_name": "test_napi_object_wrap", "sources": [ "test_napi_object_wrap.c" ] }, { "target_name": "test_napi_handle_scope", "sources": [ "test_napi_handle_scope.c" ] }, { "target_name": "test_napi_promise", "sources": [ "test_napi_promise.c" ] }, { "target_name": "test_napi_properties", "sources": [ "test_napi_properties.c" ] }, { "target_name": "test_napi_reference", "sources": [ "test_napi_reference.c" ] }, { "target_name": "test_napi_strictequal_and_instanceof", "sources": [ "test_napi_strictequal_and_instanceof.c" ] }, { "target_name": "test_napi_string", "sources": [ "test_napi_string.c" ] }, { "target_name": "test_napi_symbol", "sources": [ "test_napi_symbol.c" ] }, { "target_name": "test_napi_typedarray", "sources": [ "test_napi_typedarray.c" ] } ] } iotjs-1.0+715/test/napi/common.h000066400000000000000000000067631371177304000164000ustar00rootroot00000000000000// Empty value so that macros here are able to return NULL or void #define NAPI_RETVAL_NOTHING // Intentionally blank #define #define GET_AND_THROW_LAST_ERROR(env) \ do { \ const napi_extended_error_info* error_info; \ napi_get_last_error_info((env), &error_info); \ bool is_pending; \ napi_is_exception_pending((env), &is_pending); \ /* If an exception is already pending, don't rethrow it */ \ if (!is_pending) { \ const char* error_message = error_info->error_message != NULL \ ? error_info->error_message \ : "empty error message"; \ napi_throw_error((env), NULL, error_message); \ } \ } while (0) #define NAPI_ASSERT_BASE(env, assertion, message, ret_val) \ do { \ if (!(assertion)) { \ napi_throw_error((env), NULL, \ "assertion (" #assertion ") failed: " message); \ return ret_val; \ } \ } while (0) // Returns NULL on failed assertion. // This is meant to be used inside napi_callback methods. #define NAPI_ASSERT(env, assertion, message) \ NAPI_ASSERT_BASE(env, assertion, message, NULL) // Returns empty on failed assertion. // This is meant to be used inside functions with void return type. #define NAPI_ASSERT_RETURN_VOID(env, assertion, message) \ NAPI_ASSERT_BASE(env, assertion, message, NAPI_RETVAL_NOTHING) #define NAPI_CALL_BASE(env, the_call, ret_val) \ do { \ if ((the_call) != napi_ok) { \ GET_AND_THROW_LAST_ERROR((env)); \ return ret_val; \ } \ } while (0) // Returns NULL if the_call doesn't return napi_ok. #define NAPI_CALL(env, the_call) NAPI_CALL_BASE(env, the_call, NULL) // Returns empty if the_call doesn't return napi_ok. #define NAPI_CALL_RETURN_VOID(env, the_call) \ NAPI_CALL_BASE(env, the_call, NAPI_RETVAL_NOTHING) #define DECLARE_NAPI_PROPERTY(name, func) \ { (name), 0, (func), 0, 0, 0, napi_default, 0 } #define DECLARE_NAPI_GETTER(name, func) \ { (name), 0, 0, (func), 0, 0, napi_default, 0 } #define SET_NAMED_METHOD(env, target, prop_name, handler) \ do { \ napi_status status; \ napi_value fn; \ status = napi_create_function(env, NULL, 0, handler, NULL, &fn); \ if (status != napi_ok) \ return NULL; \ \ status = napi_set_named_property(env, target, prop_name, fn); \ if (status != napi_ok) \ return NULL; \ } while (0); iotjs-1.0+715/test/napi/common.js000066400000000000000000000026631371177304000165600ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var mustCallChecks = []; var buildTypePath = process.debug ? 'Debug' : 'Release'; function mustCall(fn, criteria) { if (typeof fn === 'number') { criteria = fn; fn = noop; } else if (fn === undefined) { fn = noop; } if (criteria === undefined) { criteria = 1; } if (typeof criteria !== 'number') throw new TypeError('Invalid value: ' + criteria); var context = { expect: criteria, actual: 0, stack: (new Error()).stack, name: fn.name || '' }; if (mustCallChecks.length === 0) process.on('exit', runCallChecks); mustCallChecks.push(context); return function() { ++context.actual; return fn.apply(this, arguments); }; } function noop() {} function runCallChecks() { mustCallChecks.forEach(function(it) { assert.strictEqual( it.actual, it.expect, 'Expect function ' + it.name + ' been called '+ it.expect + ' times, got ' + it.actual + ' ' + it.stack); }); } function expectsError(fn, exact) { // TODO:rigorous assert need! function innerFn(error) { return error instanceof Error; } if (fn) { assert.throws(fn, innerFn, exact); return; } return mustCall(innerFn, exact); } module.exports = { mustCall: mustCall, expectsError: expectsError, buildTypePath: buildTypePath, // don't use port in a parallelized test PORT: process.env.NODE_COMMON_PORT || 12306 }; iotjs-1.0+715/test/napi/test_napi_arguments.c000066400000000000000000000016651371177304000211520ustar00rootroot00000000000000#include #include "common.h" static napi_value Throw(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value argv[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_CALL(env, napi_throw(env, argv[0])); return NULL; } static napi_value Return(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value argv[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); return argv[0]; } static napi_value ReturnThis(napi_env env, napi_callback_info info) { napi_value this; NAPI_CALL(env, napi_get_cb_info(env, info, NULL, NULL, &this, NULL)); return this; } static napi_value Init(napi_env env, napi_value exports) { SET_NAMED_METHOD(env, exports, "Throw", Throw); SET_NAMED_METHOD(env, exports, "Return", Return); SET_NAMED_METHOD(env, exports, "ReturnThis", ReturnThis); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) iotjs-1.0+715/test/napi/test_napi_arguments_return.js000066400000000000000000000003641371177304000227360ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); var test = require('./build/' + common.buildTypePath + '/test_napi_arguments.node'); var obj = {}; assert.strictEqual(test.Return(obj), obj); iotjs-1.0+715/test/napi/test_napi_arguments_return_this.js000066400000000000000000000003751371177304000237670ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); var test = require('./build/' + common.buildTypePath + '/test_napi_arguments.node'); var obj = {}; assert.strictEqual(test.ReturnThis.call(obj), obj); iotjs-1.0+715/test/napi/test_napi_arguments_throw.js000066400000000000000000000005171371177304000225620ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); var test = require('./build/' + common.buildTypePath + '/test_napi_arguments.node'); try { test.Throw(new Error('foo')); assert.fail('fail path'); } catch (err) { assert(err != null); assert.strictEqual(err.message, 'foo'); } iotjs-1.0+715/test/napi/test_napi_array.c000066400000000000000000000127021371177304000202550ustar00rootroot00000000000000#include "common.h" #include "node_api.h" #include static napi_value TestGetElement(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects an array as first argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT( env, valuetype1 == napi_number, "Wrong type of arguments. Expects an integer as second argument."); napi_value array = args[0]; int32_t index; NAPI_CALL(env, napi_get_value_int32(env, args[1], &index)); NAPI_ASSERT(env, index >= 0, "Invalid index. Expects a positive integer."); bool isarray; NAPI_CALL(env, napi_is_array(env, array, &isarray)); if (!isarray) { return NULL; } uint32_t length; NAPI_CALL(env, napi_get_array_length(env, array, &length)); NAPI_ASSERT(env, ((uint32_t)index < length), "Index out of bounds!"); napi_value ret; NAPI_CALL(env, napi_get_element(env, array, index, &ret)); return ret; } static napi_value TestHasElement(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects an array as first argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT( env, valuetype1 == napi_number, "Wrong type of arguments. Expects an integer as second argument."); napi_value array = args[0]; int32_t index; NAPI_CALL(env, napi_get_value_int32(env, args[1], &index)); bool isarray; NAPI_CALL(env, napi_is_array(env, array, &isarray)); if (!isarray) { return NULL; } bool has_element; NAPI_CALL(env, napi_has_element(env, array, index, &has_element)); napi_value ret; NAPI_CALL(env, napi_get_boolean(env, has_element, &ret)); return ret; } static napi_value TestDeleteElement(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects an array as first argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT( env, valuetype1 == napi_number, "Wrong type of arguments. Expects an integer as second argument."); napi_value array = args[0]; int32_t index; bool result; napi_value ret; NAPI_CALL(env, napi_get_value_int32(env, args[1], &index)); NAPI_CALL(env, napi_is_array(env, array, &result)); if (!result) { return NULL; } NAPI_CALL(env, napi_delete_element(env, array, index, &result)); NAPI_CALL(env, napi_get_boolean(env, result, &ret)); return ret; } static napi_value New(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects an array as first argument."); napi_value ret; NAPI_CALL(env, napi_create_array(env, &ret)); uint32_t i, length; NAPI_CALL(env, napi_get_array_length(env, args[0], &length)); for (i = 0; i < length; i++) { napi_value e; NAPI_CALL(env, napi_get_element(env, args[0], i, &e)); NAPI_CALL(env, napi_set_element(env, ret, i, e)); } return ret; } static napi_value NewWithLength(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT( env, valuetype0 == napi_number, "Wrong type of arguments. Expects an integer the first argument."); int32_t array_length; NAPI_CALL(env, napi_get_value_int32(env, args[0], &array_length)); napi_value ret; NAPI_CALL(env, napi_create_array_with_length(env, array_length, &ret)); return ret; } static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("TestGetElement", TestGetElement), DECLARE_NAPI_PROPERTY("TestHasElement", TestHasElement), DECLARE_NAPI_PROPERTY("TestDeleteElement", TestDeleteElement), DECLARE_NAPI_PROPERTY("New", New), DECLARE_NAPI_PROPERTY("NewWithLength", NewWithLength), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) iotjs-1.0+715/test/napi/test_napi_array.js000066400000000000000000000025021371177304000204440ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); // Testing api calls for arrays var test_array = require('./build/' + common.buildTypePath + '/test_napi_array.node'); var array = [ 1, 9, 48, 13493, 9459324, { name: 'hello' }, [ 'world', 'node', 'abi' ] ]; assert.throws( function() { test_array.TestGetElement(array, array.length + 1); } ); assert.throws( function() { test_array.TestGetElement(array, -2); } ); array.forEach(function(element, index) { assert.strictEqual(test_array.TestGetElement(array, index), element); }); // assert.deepStrictEqual(test_array.New(array), array); assert(test_array.TestHasElement(array, 0)); assert.strictEqual(test_array.TestHasElement(array, array.length + 1), false); assert(test_array.NewWithLength(0) instanceof Array); assert(test_array.NewWithLength(1) instanceof Array); // check max allowed length for an array 2^32 -1 assert(test_array.NewWithLength(4294967295) instanceof Array); { // Verify that array elements can be deleted. var arr = ['a', 'b', 'c', 'd']; assert.strictEqual(arr.length, 4); assert.strictEqual(2 in arr, true); assert.strictEqual(test_array.TestDeleteElement(arr, 2), true); assert.strictEqual(arr.length, 4); assert.strictEqual(2 in arr, false); } iotjs-1.0+715/test/napi/test_napi_async.c000066400000000000000000000177031371177304000202620ustar00rootroot00000000000000#include #include #if defined _WIN32 #include #else #include #endif #include "common.h" // this needs to be greater than the thread pool size #define MAX_CANCEL_THREADS 6 typedef struct { int32_t _input; int32_t _output; napi_ref _callback; napi_async_work _request; } carrier; carrier the_carrier; carrier async_carrier[MAX_CANCEL_THREADS]; void Execute(napi_env env, void* data) { #if defined _WIN32 Sleep(1000); #else sleep(1); #endif carrier* c = (carrier*)data; if (c != &the_carrier) { napi_throw_type_error(env, NULL, "Wrong data parameter to Execute."); return; } c->_output = c->_input * 2; } void Complete(napi_env env, napi_status status, void* data) { carrier* c = (carrier*)data; if (c != &the_carrier) { napi_throw_type_error(env, NULL, "Wrong data parameter to Complete."); return; } if (status != napi_ok) { napi_throw_type_error(env, NULL, "Execute callback failed."); return; } napi_value argv[2]; NAPI_CALL_RETURN_VOID(env, napi_get_null(env, &argv[0])); NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, c->_output, &argv[1])); napi_value callback; NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, c->_callback, &callback)); napi_value global; NAPI_CALL_RETURN_VOID(env, napi_get_global(env, &global)); napi_value result; NAPI_CALL_RETURN_VOID(env, napi_call_function(env, global, callback, 2, argv, &result)); NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, c->_callback)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, c->_request)); } napi_value Test(napi_env env, napi_callback_info info) { size_t argc = 3; napi_value argv[3]; napi_value _this; napi_value resource_name; void* data; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &_this, &data)); NAPI_ASSERT(env, argc >= 3, "Not enough arguments, expected 2."); napi_valuetype t; NAPI_CALL(env, napi_typeof(env, argv[0], &t)); NAPI_ASSERT(env, t == napi_number, "Wrong first argument, integer expected."); NAPI_CALL(env, napi_typeof(env, argv[1], &t)); NAPI_ASSERT(env, t == napi_object, "Wrong second argument, object expected."); NAPI_CALL(env, napi_typeof(env, argv[2], &t)); NAPI_ASSERT(env, t == napi_function, "Wrong third argument, function expected."); the_carrier._output = 0; NAPI_CALL(env, napi_get_value_int32(env, argv[0], &the_carrier._input)); NAPI_CALL(env, napi_create_reference(env, argv[2], 1, &the_carrier._callback)); NAPI_CALL(env, napi_create_string_utf8(env, "TestResource", NAPI_AUTO_LENGTH, &resource_name)); NAPI_CALL(env, napi_create_async_work(env, argv[1], resource_name, Execute, Complete, &the_carrier, &the_carrier._request)); NAPI_CALL(env, napi_queue_async_work(env, the_carrier._request)); return NULL; } void BusyCancelComplete(napi_env env, napi_status status, void* data) { carrier* c = (carrier*)data; NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, c->_request)); } void CancelComplete(napi_env env, napi_status status, void* data) { carrier* c = (carrier*)data; if (status == napi_cancelled) { // ok we got the status we expected so make the callback to // indicate the cancel succeeded. napi_value callback; NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, c->_callback, &callback)); napi_value global; NAPI_CALL_RETURN_VOID(env, napi_get_global(env, &global)); napi_value result; NAPI_CALL_RETURN_VOID(env, napi_call_function(env, global, callback, 0, NULL, &result)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, c->_request)); NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, c->_callback)); } void CancelExecute(napi_env env, void* data) { #if defined _WIN32 Sleep(1000); #else sleep(1); #endif } napi_value TestCancel(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value argv[1]; napi_value _this; napi_value resource_name; void* data; NAPI_CALL(env, napi_create_string_utf8(env, "TestResource", NAPI_AUTO_LENGTH, &resource_name)); // make sure the work we are going to cancel will not be // able to start by using all the threads in the pool for (int i = 1; i < MAX_CANCEL_THREADS; i++) { NAPI_CALL(env, napi_create_async_work(env, NULL, resource_name, CancelExecute, BusyCancelComplete, &async_carrier[i], &async_carrier[i]._request)); NAPI_CALL(env, napi_queue_async_work(env, async_carrier[i]._request)); } // now queue the work we are going to cancel and then cancel it. // cancel will fail if the work has already started, but // we have prevented it from starting by consuming all of the // workers above. NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &_this, &data)); NAPI_CALL(env, napi_create_async_work(env, NULL, resource_name, CancelExecute, CancelComplete, &async_carrier[0], &async_carrier[0]._request)); NAPI_CALL(env, napi_create_reference(env, argv[0], 1, &async_carrier[0]._callback)); NAPI_CALL(env, napi_queue_async_work(env, async_carrier[0]._request)); NAPI_CALL(env, napi_cancel_async_work(env, async_carrier[0]._request)); return NULL; } struct { napi_ref ref; napi_async_work work; } repeated_work_info = { NULL, NULL }; static void RepeatedWorkerThread(napi_env env, void* data) { } static void RepeatedWorkComplete(napi_env env, napi_status status, void* data) { napi_value cb, js_status; NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, repeated_work_info.ref, &cb)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, repeated_work_info.work)); NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, repeated_work_info.ref)); repeated_work_info.work = NULL; repeated_work_info.ref = NULL; NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, (uint32_t)status, &js_status)); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, cb, cb, 1, &js_status, NULL)); } static napi_value DoRepeatedWork(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value cb, name; NAPI_ASSERT(env, repeated_work_info.ref == NULL, "Reference left over from previous work"); NAPI_ASSERT(env, repeated_work_info.work == NULL, "Work pointer left over from previous work"); NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &cb, NULL, NULL)); NAPI_CALL(env, napi_create_reference(env, cb, 1, &repeated_work_info.ref)); NAPI_CALL(env, napi_create_string_utf8(env, "Repeated Work", NAPI_AUTO_LENGTH, &name)); NAPI_CALL(env, napi_create_async_work(env, NULL, name, RepeatedWorkerThread, RepeatedWorkComplete, &repeated_work_info, &repeated_work_info.work)); NAPI_CALL(env, napi_queue_async_work(env, repeated_work_info.work)); return NULL; } napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { DECLARE_NAPI_PROPERTY("Test", Test), DECLARE_NAPI_PROPERTY("TestCancel", TestCancel), DECLARE_NAPI_PROPERTY("DoRepeatedWork", DoRepeatedWork), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) iotjs-1.0+715/test/napi/test_napi_async.js000066400000000000000000000010251371177304000204420ustar00rootroot00000000000000'use strict'; var common = require('common.js'); var assert = require('assert'); var test_async = require('./build/' + common.buildTypePath + '/test_napi_async.node'); // Successful async execution and completion callback. test_async.Test(5, {}, common.mustCall(function(err, val) { console.log(err, val); assert.strictEqual(err, null); assert.strictEqual(val, 10); process.nextTick(common.mustCall()); })); // Async work item cancellation with callback. test_async.TestCancel(common.mustCall()); iotjs-1.0+715/test/napi/test_napi_buffer.c000066400000000000000000000117261371177304000204150ustar00rootroot00000000000000#include #include #include "common.h" #include "node_api.h" static const char the_text[] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; static const unsigned int buffer_size = sizeof(the_text) - 1; static int deleterCallCount = 0; static void buffer_finalizer(napi_env env, void* data, void* finalize_hint) { NAPI_ASSERT_RETURN_VOID(env, data != NULL && strcmp(data, the_text) == 0, "invalid data"); (void)finalize_hint; free(data); deleterCallCount++; } static void noop_finilizer(napi_env env, void* data, void* finalize_hint) { NAPI_ASSERT_RETURN_VOID(env, data != NULL && strcmp(data, the_text) == 0, "invalid data"); (void)finalize_hint; deleterCallCount++; } static napi_value new_buffer(napi_env env, napi_callback_info info) { napi_value the_buffer; char* the_copy; NAPI_CALL(env, napi_create_buffer(env, buffer_size, (void**)(&the_copy), &the_buffer)); NAPI_ASSERT(env, the_copy, "Failed to copy static text for newBuffer"); memcpy(the_copy, the_text, buffer_size); return the_buffer; } static napi_value new_external_buffer(napi_env env, napi_callback_info info) { napi_value the_buffer; char* the_copy = strdup(the_text); NAPI_ASSERT(env, the_copy, "Failed to copy static text for newExternalBuffer"); NAPI_CALL(env, napi_create_external_buffer(env, buffer_size, the_copy, buffer_finalizer, NULL, // finalize_hint &the_buffer)); return the_buffer; } static napi_value get_deleter_call_count(napi_env env, napi_callback_info info) { napi_value callCount; NAPI_CALL(env, napi_create_int32(env, deleterCallCount, &callCount)); return callCount; } static napi_value copy_buffer(napi_env env, napi_callback_info info) { napi_value the_buffer; NAPI_CALL(env, napi_create_buffer_copy(env, buffer_size, the_text, NULL, &the_buffer)); return the_buffer; } static napi_value buffer_has_instance(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); napi_value the_buffer = args[0]; bool hasInstance; napi_valuetype theType; NAPI_CALL(env, napi_typeof(env, the_buffer, &theType)); NAPI_ASSERT(env, theType == napi_object, "bufferHasInstance: instance is not an object"); NAPI_CALL(env, napi_is_buffer(env, the_buffer, &hasInstance)); NAPI_ASSERT(env, hasInstance, "bufferHasInstance: instance is not a buffer"); napi_value returnValue; NAPI_CALL(env, napi_get_boolean(env, hasInstance, &returnValue)); return returnValue; } static napi_value buffer_info(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); napi_value the_buffer = args[0]; char* bufferData; napi_value returnValue; size_t bufferLength; NAPI_CALL(env, napi_get_buffer_info(env, the_buffer, (void**)(&bufferData), &bufferLength)); NAPI_CALL(env, napi_get_boolean(env, bufferLength == buffer_size && !strncmp(bufferData, the_text, bufferLength), &returnValue)); return returnValue; } static napi_value static_buffer(napi_env env, napi_callback_info info) { napi_value the_buffer; NAPI_CALL(env, napi_create_external_buffer(env, buffer_size, (void*)the_text, noop_finilizer, NULL, // finalize_hint &the_buffer)); return the_buffer; } static napi_value init(napi_env env, napi_value exports) { napi_value the_value; NAPI_CALL(env, napi_create_string_utf8(env, the_text, buffer_size, &the_value)); NAPI_CALL(env, napi_set_named_property(env, exports, "theText", the_value)); napi_property_descriptor methods[] = { DECLARE_NAPI_PROPERTY("newBuffer", new_buffer), DECLARE_NAPI_PROPERTY("newExternalBuffer", new_external_buffer), DECLARE_NAPI_PROPERTY("getDeleterCallCount", get_deleter_call_count), DECLARE_NAPI_PROPERTY("copyBuffer", copy_buffer), DECLARE_NAPI_PROPERTY("bufferHasInstance", buffer_has_instance), DECLARE_NAPI_PROPERTY("bufferInfo", buffer_info), DECLARE_NAPI_PROPERTY("staticBuffer", static_buffer), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(methods) / sizeof(methods[0]), methods)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, init) iotjs-1.0+715/test/napi/test_napi_buffer.js000066400000000000000000000014021371177304000205750ustar00rootroot00000000000000'use strict'; var global = process; var common = require('common.js'); var binding = require('./build/' + common.buildTypePath + '/test_napi_buffer.node'); var assert = require('assert'); assert.strictEqual(binding.newBuffer().toString(), binding.theText); assert.strictEqual(binding.newExternalBuffer().toString(), binding.theText); console.log('gc1'); global.gc(); assert.strictEqual(binding.getDeleterCallCount(), 1); assert.strictEqual(binding.copyBuffer().toString(), binding.theText); var buffer = binding.staticBuffer(); assert.strictEqual(binding.bufferHasInstance(buffer), true); assert.strictEqual(binding.bufferInfo(buffer), true); buffer = null; global.gc(); console.log('gc2'); assert.strictEqual(binding.getDeleterCallCount(), 2); iotjs-1.0+715/test/napi/test_napi_construct.c000066400000000000000000000024001371177304000211550ustar00rootroot00000000000000#include #include "common.h" static napi_ref ConstructRef; static void cleanup(void* data) { napi_env env = (napi_env)data; napi_delete_reference(env, ConstructRef); } napi_value Construct(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value argv[1]; napi_value this; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &this, NULL)); NAPI_CALL(env, napi_set_named_property(env, this, "value", argv[0])); return NULL; } napi_value Constructor(napi_env env, napi_callback_info info) { napi_value construct; NAPI_CALL(env, napi_get_reference_value(env, ConstructRef, &construct)); size_t argc = 1; napi_value argv[1]; napi_value result; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_CALL(env, napi_new_instance(env, construct, argc, argv, &result)); return result; } NAPI_MODULE_INIT() { napi_value construct; NAPI_CALL(env, napi_create_function(env, "Constructor", NAPI_AUTO_LENGTH, Construct, NULL, &construct)); NAPI_CALL(env, napi_create_reference(env, construct, 1, &ConstructRef)); NAPI_CALL(env, napi_add_env_cleanup_hook(env, cleanup, env)); SET_NAMED_METHOD(env, exports, "Constructor", Constructor); return exports; } iotjs-1.0+715/test/napi/test_napi_construct.js000066400000000000000000000003771371177304000213620ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); var test = require('./build/' + common.buildTypePath + '/test_napi_construct.node'); var val = test.Constructor(123); assert.strictEqual(val.value, 123); iotjs-1.0+715/test/napi/test_napi_conversions.c000066400000000000000000000103571371177304000215130ustar00rootroot00000000000000#include "common.h" #include "node_api.h" static napi_value AsBool(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); bool value; NAPI_CALL(env, napi_get_value_bool(env, args[0], &value)); napi_value output; NAPI_CALL(env, napi_get_boolean(env, value, &output)); return output; } static napi_value AsInt32(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); int32_t value; NAPI_CALL(env, napi_get_value_int32(env, args[0], &value)); napi_value output; NAPI_CALL(env, napi_create_int32(env, value, &output)); return output; } static napi_value AsUInt32(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); uint32_t value; NAPI_CALL(env, napi_get_value_uint32(env, args[0], &value)); napi_value output; NAPI_CALL(env, napi_create_uint32(env, value, &output)); return output; } static napi_value AsInt64(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); int64_t value; NAPI_CALL(env, napi_get_value_int64(env, args[0], &value)); napi_value output; NAPI_CALL(env, napi_create_int64(env, (double)value, &output)); return output; } static napi_value AsDouble(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); double value; NAPI_CALL(env, napi_get_value_double(env, args[0], &value)); napi_value output; NAPI_CALL(env, napi_create_double(env, value, &output)); return output; } static napi_value AsString(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); char value[100]; NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], value, sizeof(value), NULL)); napi_value output; NAPI_CALL(env, napi_create_string_utf8(env, value, NAPI_AUTO_LENGTH, &output)); return output; } static napi_value ToBool(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); napi_value output; NAPI_CALL(env, napi_coerce_to_bool(env, args[0], &output)); return output; } static napi_value ToNumber(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); napi_value output; NAPI_CALL(env, napi_coerce_to_number(env, args[0], &output)); return output; } static napi_value ToObject(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); napi_value output; NAPI_CALL(env, napi_coerce_to_object(env, args[0], &output)); return output; } static napi_value ToString(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); napi_value output; NAPI_CALL(env, napi_coerce_to_string(env, args[0], &output)); return output; } static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("asBool", AsBool), DECLARE_NAPI_PROPERTY("asInt32", AsInt32), DECLARE_NAPI_PROPERTY("asUInt32", AsUInt32), DECLARE_NAPI_PROPERTY("asInt64", AsInt64), DECLARE_NAPI_PROPERTY("asDouble", AsDouble), DECLARE_NAPI_PROPERTY("asString", AsString), DECLARE_NAPI_PROPERTY("toBool", ToBool), DECLARE_NAPI_PROPERTY("toNumber", ToNumber), DECLARE_NAPI_PROPERTY("toObject", ToObject), DECLARE_NAPI_PROPERTY("toString", ToString), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) iotjs-1.0+715/test/napi/test_napi_conversions.js000066400000000000000000000162771371177304000217140ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); var test = require('./build/' + common.buildTypePath + '/test_napi_conversions.node'); assert.strictEqual(false, test.asBool(false)); assert.strictEqual(true, test.asBool(true)); assert.throws(function() { test.asBool(undefined) }, Error); assert.throws(function() { test.asBool(null) }, Error); assert.throws(function() { test.asBool(Number.NaN) }, Error); assert.throws(function() { test.asBool(0) }, Error); assert.throws(function() { test.asBool('') }, Error); assert.throws(function() { test.asBool('0') }, Error); assert.throws(function() { test.asBool(1) }, Error); assert.throws(function() { test.asBool('1') }, Error); assert.throws(function() { test.asBool('true') }, Error); assert.throws(function() { test.asBool({}) }, Error); assert.throws(function() { test.asBool([]) }, Error); [test.asInt32, test.asUInt32, test.asInt64].forEach(function (asInt) { assert.strictEqual(0, asInt(0)); assert.strictEqual(1, asInt(1)); assert.strictEqual(1, asInt(1.0)); assert.strictEqual(1, asInt(1.1)); assert.strictEqual(1, asInt(1.9)); assert.strictEqual(0, asInt(0.9)); assert.strictEqual(999, asInt(999.9)); assert.strictEqual(0, asInt(Number.NaN)); assert.throws(function() { asInt(undefined) }, Error); assert.throws(function() { asInt(null) }, Error); assert.throws(function() { asInt(false) }, Error); assert.throws(function() { asInt('') }, Error); assert.throws(function() { asInt('1') }, Error); assert.throws(function() { asInt({}) }, Error); assert.throws(function() { asInt([]) }, Error); }); assert.strictEqual(-1, test.asInt32(-1)); assert.strictEqual(-1, test.asInt64(-1)); assert.strictEqual(Math.pow(2, 32) - 1, test.asUInt32(-1)); assert.strictEqual(0, test.asDouble(0)); assert.strictEqual(1, test.asDouble(1)); assert.strictEqual(1.0, test.asDouble(1.0)); assert.strictEqual(1.1, test.asDouble(1.1)); assert.strictEqual(1.9, test.asDouble(1.9)); assert.strictEqual(0.9, test.asDouble(0.9)); assert.strictEqual(999.9, test.asDouble(999.9)); assert.strictEqual(-1, test.asDouble(-1)); assert.throws(function() { test.asDouble(undefined) }, Error); assert.throws(function() { test.asDouble(null) }, Error); assert.throws(function() { test.asDouble(false) }, Error); assert.throws(function() { test.asDouble('') }, Error); assert.throws(function() { test.asDouble('1') }, Error); assert.throws(function() { test.asDouble({}) }, Error); assert.throws(function() { test.asDouble([]) }, Error); assert.strictEqual('', test.asString('')); assert.strictEqual('test', test.asString('test')); assert.throws(function() { test.asString(undefined) }, Error); assert.throws(function() { test.asString(null) }, Error); assert.throws(function() { test.asString(false) }, Error); assert.throws(function() { test.asString(1) }, Error); assert.throws(function() { test.asString(1.1) }, Error); assert.throws(function() { test.asString(Number.NaN) }, Error); assert.throws(function() { test.asString({}) }, Error); assert.throws(function() { test.asString([]) }, Error); assert.strictEqual(true, test.toBool(true)); assert.strictEqual(true, test.toBool(1)); assert.strictEqual(true, test.toBool(-1)); assert.strictEqual(true, test.toBool('true')); assert.strictEqual(true, test.toBool('false')); assert.strictEqual(true, test.toBool({})); assert.strictEqual(true, test.toBool([])); assert.strictEqual(false, test.toBool(false)); assert.strictEqual(false, test.toBool(undefined)); assert.strictEqual(false, test.toBool(null)); assert.strictEqual(false, test.toBool(0)); assert.strictEqual(false, test.toBool(Number.NaN)); assert.strictEqual(false, test.toBool('')); assert.strictEqual(0, test.toNumber(0)); assert.strictEqual(1, test.toNumber(1)); assert.strictEqual(1.1, test.toNumber(1.1)); assert.strictEqual(-1, test.toNumber(-1)); assert.strictEqual(0, test.toNumber('0')); assert.strictEqual(1, test.toNumber('1')); assert.strictEqual(1.1, test.toNumber('1.1')); assert.strictEqual(0, test.toNumber([])); assert.strictEqual(0, test.toNumber(false)); assert.strictEqual(0, test.toNumber(null)); assert.strictEqual(0, test.toNumber('')); Number.isNaN = Number.isNaN || function(value) { return value !== value; } assert(Number.isNaN(test.asDouble(Number.NaN))); assert(Number.isNaN(test.toNumber(Number.NaN))); assert(Number.isNaN(test.toNumber({}))); assert(Number.isNaN(test.toNumber(undefined))); assert.deepStrictEqual = assert.deepStrictEqual || function(expected, value) { var keys = Object.keys(value); if ((typeof expected !== typeof value) || (keys.length !== Object.keys(expected).length)) { assert(false); } if (keys.length > 0) { for (var key in keys) { if (typeof value[keys[key]] !== 'object') { assert.strictEqual(expected[keys[key]], value[keys[key]]); } else { assert.deepStrictEqual(expected[keys[key]], value[keys[key]]); } } } else if (typeof value.valueOf() !== 'object') { assert.strictEqual(expected.valueOf(), value.valueOf()); } } assert.notDeepStrictEqual = assert.notDeepStrictEqual || function(expected, value) { if ((typeof expected !== typeof value) || (Object.keys(value).length !== Object.keys(expected).length)) { return; } var keys = Object.keys(value); if (keys.length > 0) { for (var key in keys) { if (typeof value[keys[key]] !== 'object') { assert.notStrictEqual(expected[keys[key]], value[keys[key]]); } else { assert.notDeepStrictEqual(expected[keys[key]], value[keys[key]]); } } } else if (typeof value.valueOf() !== 'object') { assert.notStrictEqual(expected.valueOf(), value.valueOf()); } } assert.deepStrictEqual({}, test.toObject({})); assert.deepStrictEqual({ 'test': 1 }, test.toObject({ 'test': 1 })); assert.deepStrictEqual([], test.toObject([])); assert.deepStrictEqual([ 1, 2, 3 ], test.toObject([ 1, 2, 3 ])); assert.deepStrictEqual(new Boolean(false), test.toObject(false)); assert.deepStrictEqual(new Boolean(true), test.toObject(true)); assert.deepStrictEqual(new String(''), test.toObject('')); assert.deepStrictEqual(new Number(0), test.toObject(0)); assert.notDeepStrictEqual(new Number(Number.NaN), test.toObject(Number.NaN)); assert.notDeepStrictEqual(new Boolean(true), test.toObject(false)); assert.notDeepStrictEqual(new Boolean(false), test.toObject(true)); assert.notDeepStrictEqual(test.toObject(false), false); assert.notDeepStrictEqual(test.toObject(true), true); assert.notDeepStrictEqual(test.toObject(''), ''); assert.notDeepStrictEqual(test.toObject(0), 0); assert(!Number.isNaN(test.toObject(Number.NaN))); assert.strictEqual('', test.toString('')); assert.strictEqual('test', test.toString('test')); assert.strictEqual('undefined', test.toString(undefined)); assert.strictEqual('null', test.toString(null)); assert.strictEqual('false', test.toString(false)); assert.strictEqual('true', test.toString(true)); assert.strictEqual('0', test.toString(0)); assert.strictEqual('1.1', test.toString(1.1)); assert.strictEqual('NaN', test.toString(Number.NaN)); assert.strictEqual('[object Object]', test.toString({})); assert.strictEqual('test', test.toString({ toString: function() { return 'test' } })); assert.strictEqual('', test.toString([])); assert.strictEqual('1,2,3', test.toString([ 1, 2, 3 ])); iotjs-1.0+715/test/napi/test_napi_create_error.js000066400000000000000000000013701371177304000220040ustar00rootroot00000000000000var common = require('common.js'); var addon = require('./build/' + common.buildTypePath + '/test_napi_error_handling'); var assert = require('assert'); var ERROR_CODE = "ErrorCode"; var ERROR_MSG = "ErrorMSG" var error = addon.CreateError(ERROR_CODE, ERROR_MSG); assert(error.code == ERROR_CODE); assert(error.message == ERROR_MSG); assert(error instanceof Error); var typeError = addon.CreateTypeError(ERROR_CODE, ERROR_MSG); assert(typeError.code == ERROR_CODE); assert(typeError.message == ERROR_MSG); assert(typeError instanceof TypeError); var rangeError = addon.CreateRangeError(ERROR_CODE, ERROR_MSG); assert(rangeError.code == ERROR_CODE); assert(rangeError.message == ERROR_MSG); assert(rangeError instanceof RangeError); iotjs-1.0+715/test/napi/test_napi_dataview.c000066400000000000000000000066221371177304000207470ustar00rootroot00000000000000#include "common.h" #include "node_api.h" #include static napi_value create_dataview(napi_env env, napi_callback_info info) { size_t argc = 3; napi_value args[3]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc == 3, "Wrong number of arguments"); napi_valuetype valuetype0; napi_value arraybuffer = args[0]; NAPI_CALL(env, napi_typeof(env, arraybuffer, &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects a ArrayBuffer as the first " "argument."); bool is_arraybuffer; NAPI_CALL(env, napi_is_arraybuffer(env, arraybuffer, &is_arraybuffer)); NAPI_ASSERT(env, is_arraybuffer, "Wrong type of arguments. Expects a ArrayBuffer as the first " "argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT(env, valuetype1 == napi_number, "Wrong type of arguments. Expects a number as second argument."); size_t byte_offset = 0; NAPI_CALL(env, napi_get_value_uint32(env, args[1], (uint32_t*)(&byte_offset))); napi_valuetype valuetype2; NAPI_CALL(env, napi_typeof(env, args[2], &valuetype2)); NAPI_ASSERT(env, valuetype2 == napi_number, "Wrong type of arguments. Expects a number as third argument."); size_t length = 0; NAPI_CALL(env, napi_get_value_uint32(env, args[2], (uint32_t*)(&length))); napi_value output_dataview; NAPI_CALL(env, napi_create_dataview(env, length, arraybuffer, byte_offset, &output_dataview)); return output_dataview; } static napi_value create_data_view_from_js_dataview(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); napi_valuetype valuetype; napi_value input_dataview = args[0]; NAPI_CALL(env, napi_typeof(env, input_dataview, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong type of arguments. Expects a DataView as the first " "argument."); bool is_dataview; NAPI_CALL(env, napi_is_dataview(env, input_dataview, &is_dataview)); NAPI_ASSERT(env, is_dataview, "Wrong type of arguments. Expects a DataView as the first " "argument."); size_t byte_offset = 0; size_t length = 0; napi_value buffer; NAPI_CALL(env, napi_get_dataview_info(env, input_dataview, &length, NULL, &buffer, &byte_offset)); napi_value output_dataview; NAPI_CALL(env, napi_create_dataview(env, length, buffer, byte_offset, &output_dataview)); return output_dataview; } static napi_value init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("CreateDataView", create_dataview), DECLARE_NAPI_PROPERTY("CreateDataViewFromJSDataView", create_data_view_from_js_dataview) }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, init) iotjs-1.0+715/test/napi/test_napi_dataview.js000066400000000000000000000013051371177304000211320ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); // Testing api calls for arrays var test_dataview = require('./build/' + common.buildTypePath + '/test_napi_dataview.node'); // Test for creating dataview { var buffer = new ArrayBuffer(128); var template = new DataView(buffer); var theDataview = test_dataview.CreateDataViewFromJSDataView(template); assert(theDataview instanceof DataView, 'Expect ' + theDataview + ' to be a DataView'); } // Test for creating dataview with invalid range { var buffer = new ArrayBuffer(128); assert.throws(function() { test_dataview.CreateDataView(buffer, 10, 200); }, RangeError); } iotjs-1.0+715/test/napi/test_napi_env.js000066400000000000000000000006621371177304000201230ustar00rootroot00000000000000'use strict'; var common = require('common.js'); var storeEnv = require('./build/' + common.buildTypePath + '/test_napi_env_store.node'); var compareEnv = require('./build/' + common.buildTypePath + '/test_napi_env_compare.node'); var assert = require('assert'); // N-API environment pointers in two different modules must be different assert.strictEqual(compareEnv(storeEnv), true); iotjs-1.0+715/test/napi/test_napi_env_compare.c000066400000000000000000000012751371177304000214400ustar00rootroot00000000000000#include #include "common.h" static napi_value compare(napi_env env, napi_callback_info info) { napi_value external; size_t argc = 1; void* data; napi_value return_value; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &external, NULL, NULL)); NAPI_CALL(env, napi_get_value_external(env, external, &data)); NAPI_CALL(env, napi_get_boolean(env, ((napi_env)data) == env, &return_value)); return return_value; } static napi_value Init(napi_env env, napi_value exports) { NAPI_CALL(env, napi_create_function(env, "exports", NAPI_AUTO_LENGTH, compare, NULL, &exports)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) iotjs-1.0+715/test/napi/test_napi_env_store.c000066400000000000000000000004041371177304000211370ustar00rootroot00000000000000#include #include "common.h" static napi_value Init(napi_env env, napi_value exports) { napi_value external; NAPI_CALL(env, napi_create_external(env, env, NULL, NULL, &external)); return external; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) iotjs-1.0+715/test/napi/test_napi_error_handling.c000066400000000000000000000102671371177304000221400ustar00rootroot00000000000000#include #include #include #include "common.h" #define ERROR_CODE "ErrorCODE" #define ERROR_MSG "ErrorMSG" napi_value Throw(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value argv[1]; napi_status status; status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); assert(status == napi_ok); status = napi_throw(env, argv[0]); assert(status == napi_ok); return NULL; } napi_value ThrowError(napi_env env, napi_callback_info info) { napi_status status; status = napi_throw_error(env, ERROR_CODE, ERROR_MSG); assert(status == napi_ok); return NULL; } napi_value ThrowTypeError(napi_env env, napi_callback_info info) { napi_status status; status = napi_throw_type_error(env, ERROR_CODE, ERROR_MSG); assert(status == napi_ok); return NULL; } napi_value ThrowRangeError(napi_env env, napi_callback_info info) { napi_status status; status = napi_throw_range_error(env, ERROR_CODE, ERROR_MSG); assert(status == napi_ok); return NULL; } napi_value IsError(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value argv[1]; napi_value result; napi_status status; bool res; status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); assert(status == napi_ok); status = napi_is_error(env, argv[0], &res); assert(status == napi_ok); status = napi_get_boolean(env, res, &result); assert(status == napi_ok); return result; } napi_value CreateError(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value argv[2]; napi_value result; napi_status status; status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); assert(status == napi_ok); status = napi_create_error(env, argv[0], argv[1], &result); assert(status == napi_ok); return result; } napi_value CreateTypeError(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value argv[2]; napi_value result; napi_status status; status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); assert(status == napi_ok); status = napi_create_type_error(env, argv[0], argv[1], &result); assert(status == napi_ok); return result; } napi_value CreateRangeError(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value argv[2]; napi_value result; napi_status status; status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); assert(status == napi_ok); status = napi_create_range_error(env, argv[0], argv[1], &result); assert(status == napi_ok); return result; } napi_value GetandClearLastException(napi_env env, napi_callback_info info) { napi_status status; napi_value result; status = napi_get_and_clear_last_exception(env, &result); assert(status == napi_ok); return result; } napi_value IsExceptionPending(napi_env env, napi_callback_info info) { napi_status status; bool res; napi_value result; status = napi_is_exception_pending(env, &res); assert(status == napi_ok); status = napi_get_boolean(env, res, &result); assert(status == napi_ok); return result; } napi_value FatalException(napi_env env, napi_callback_info info) { napi_status status; size_t argc = 1; napi_value argv[1]; status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); assert(status == napi_ok); status = napi_fatal_exception(env, argv[0]); assert(status == napi_ok); return NULL; } napi_value Init(napi_env env, napi_value exports) { SET_NAMED_METHOD(env, exports, "Throw", Throw); SET_NAMED_METHOD(env, exports, "ThrowError", ThrowError); SET_NAMED_METHOD(env, exports, "ThrowTypeError", ThrowTypeError); SET_NAMED_METHOD(env, exports, "ThrowRangeError", ThrowRangeError); SET_NAMED_METHOD(env, exports, "IsError", IsError); SET_NAMED_METHOD(env, exports, "CreateError", CreateError); SET_NAMED_METHOD(env, exports, "CreateTypeError", CreateTypeError); SET_NAMED_METHOD(env, exports, "CreateRangeError", CreateRangeError); SET_NAMED_METHOD(env, exports, "GetandClearLastException", GetandClearLastException); SET_NAMED_METHOD(env, exports, "IsExceptionPending", IsExceptionPending); SET_NAMED_METHOD(env, exports, "FatalException", FatalException); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) iotjs-1.0+715/test/napi/test_napi_exception.js000066400000000000000000000006271371177304000213320ustar00rootroot00000000000000var common = require('common.js'); var addon = require('./build/' + common.buildTypePath + '/test_napi_error_handling'); var assert = require('assert'); var ERROR_MSG = "ErrorMSG"; process.on("uncaughtException", function (e) { assert(e.message === ERROR_MSG); }); assert(addon.GetandClearLastException() === undefined); var err = new Error(ERROR_MSG); addon.FatalException(err); iotjs-1.0+715/test/napi/test_napi_general.c000066400000000000000000000062601371177304000205560ustar00rootroot00000000000000/* Copyright 2019-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 "common.h" #include "node_api.h" static napi_value get_null(napi_env env, napi_callback_info info) { napi_value result; NAPI_CALL(env, napi_get_null(env, &result)); return result; } static napi_value get_undefined(napi_env env, napi_callback_info info) { napi_value result; NAPI_CALL(env, napi_get_undefined(env, &result)); return result; } static napi_value test_typeof(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); napi_valuetype argument_type; NAPI_CALL(env, napi_typeof(env, args[0], &argument_type)); napi_value result = NULL; if (argument_type == napi_number) { NAPI_CALL(env, napi_create_string_utf8(env, "number", NAPI_AUTO_LENGTH, &result)); } else if (argument_type == napi_string) { NAPI_CALL(env, napi_create_string_utf8(env, "string", NAPI_AUTO_LENGTH, &result)); } else if (argument_type == napi_function) { NAPI_CALL(env, napi_create_string_utf8(env, "function", NAPI_AUTO_LENGTH, &result)); } else if (argument_type == napi_object) { NAPI_CALL(env, napi_create_string_utf8(env, "object", NAPI_AUTO_LENGTH, &result)); } else if (argument_type == napi_boolean) { NAPI_CALL(env, napi_create_string_utf8(env, "boolean", NAPI_AUTO_LENGTH, &result)); } else if (argument_type == napi_undefined) { NAPI_CALL(env, napi_create_string_utf8(env, "undefined", NAPI_AUTO_LENGTH, &result)); } else if (argument_type == napi_symbol) { NAPI_CALL(env, napi_create_string_utf8(env, "symbol", NAPI_AUTO_LENGTH, &result)); } else if (argument_type == napi_null) { NAPI_CALL(env, napi_create_string_utf8(env, "null", NAPI_AUTO_LENGTH, &result)); } return result; } static napi_value init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("GetNull", get_null), DECLARE_NAPI_PROPERTY("GetUndefined", get_undefined), DECLARE_NAPI_PROPERTY("TypeOf", test_typeof), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, init) iotjs-1.0+715/test/napi/test_napi_general.js000066400000000000000000000021421371177304000207430ustar00rootroot00000000000000/* Copyright 2019-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 assert = require('assert'); var common = require('common.js'); var test_general = require('./build/' + common.buildTypePath + '/test_napi_general.node'); assert.strictEqual(test_general.GetUndefined(), undefined); assert.strictEqual(test_general.GetNull(), null); [ 123, 'test string', function() {}, new Object(), true, undefined ].forEach(function(val) { assert.strictEqual(test_general.TypeOf(val), typeof val); }); iotjs-1.0+715/test/napi/test_napi_general_es2015.js000066400000000000000000000025421371177304000217460ustar00rootroot00000000000000/* Copyright 2019-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 assert = require('assert'); var common = require('common.js'); var test_general = require('./build/' + common.buildTypePath + '/test_napi_general.node'); assert.strictEqual(test_general.GetUndefined(), undefined); assert.strictEqual(test_general.GetNull(), null); var buffer = new ArrayBuffer(16); [ buffer, new Int8Array(buffer), new Uint8Array(buffer), new Uint8ClampedArray(buffer), new Int16Array(buffer), new Uint16Array(buffer), new Int32Array(buffer), new Uint32Array(buffer), new Float32Array(buffer), new Float64Array(buffer), new Promise(function(){}), Symbol(), ].forEach(function(val) { assert.strictEqual(test_general.TypeOf(val), typeof val); }); iotjs-1.0+715/test/napi/test_napi_handle_scope.c000066400000000000000000000067631371177304000215750ustar00rootroot00000000000000/* Copyright 2019-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 "common.h" #include "node_api.h" #include static napi_value new_scope(napi_env env, napi_callback_info info) { napi_handle_scope scope; napi_value output = NULL; NAPI_CALL(env, napi_open_handle_scope(env, &scope)); NAPI_CALL(env, napi_create_object(env, &output)); NAPI_CALL(env, napi_close_handle_scope(env, scope)); return NULL; } static napi_value new_scope_escape(napi_env env, napi_callback_info info) { napi_escapable_handle_scope scope; napi_value output = NULL; napi_value escapee = NULL; NAPI_CALL(env, napi_open_escapable_handle_scope(env, &scope)); NAPI_CALL(env, napi_create_object(env, &output)); NAPI_CALL(env, napi_escape_handle(env, scope, output, &escapee)); NAPI_CALL(env, napi_close_escapable_handle_scope(env, scope)); return escapee; } static napi_value new_scope_escape_twice(napi_env env, napi_callback_info info) { napi_escapable_handle_scope scope; napi_value output = NULL; napi_value escapee = NULL; napi_status status; NAPI_CALL(env, napi_open_escapable_handle_scope(env, &scope)); NAPI_CALL(env, napi_create_object(env, &output)); NAPI_CALL(env, napi_escape_handle(env, scope, output, &escapee)); status = napi_escape_handle(env, scope, output, &escapee); NAPI_ASSERT(env, status == napi_escape_called_twice, "Escaping twice fails"); NAPI_CALL(env, napi_close_escapable_handle_scope(env, scope)); return NULL; } static napi_value new_scope_with_exception(napi_env env, napi_callback_info info) { napi_handle_scope scope; size_t argc; napi_value exception_function; napi_status status; napi_value output = NULL; NAPI_CALL(env, napi_open_handle_scope(env, &scope)); NAPI_CALL(env, napi_create_object(env, &output)); argc = 1; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &exception_function, NULL, NULL)); status = napi_call_function(env, output, exception_function, 0, NULL, NULL); NAPI_ASSERT(env, status == napi_pending_exception, "Function should have thrown."); // Closing a handle scope should still work while an exception is pending. NAPI_CALL(env, napi_close_handle_scope(env, scope)); return NULL; } static napi_value init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { DECLARE_NAPI_PROPERTY("NewScope", new_scope), DECLARE_NAPI_PROPERTY("NewScopeEscape", new_scope_escape), DECLARE_NAPI_PROPERTY("NewScopeEscapeTwice", new_scope_escape_twice), DECLARE_NAPI_PROPERTY("NewScopeWithException", new_scope_with_exception), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, init); iotjs-1.0+715/test/napi/test_napi_handle_scope.js000066400000000000000000000007271371177304000217610ustar00rootroot00000000000000var common = require('common.js'); var assert = require('assert'); var testHandleScope = require('./build/' + common.buildTypePath + '/test_napi_handle_scope.node'); testHandleScope.NewScope(); assert(testHandleScope.NewScopeEscape() instanceof Object); testHandleScope.NewScopeEscapeTwice(); assert.throws( function() { testHandleScope.NewScopeWithException(function() { throw new RangeError(); }); }, RangeError ); iotjs-1.0+715/test/napi/test_napi_is_error.js000066400000000000000000000005011371177304000211470ustar00rootroot00000000000000var common = require('common.js'); var addon = require('./build/' + common.buildTypePath + '/test_napi_error_handling'); var assert = require('assert'); var err = new Error("ErrorMSG"); try { var c = true; throw c } catch (e) { assert(addon.IsError(e) === false); } assert(addon.IsError(err)); iotjs-1.0+715/test/napi/test_napi_make_callback.c000066400000000000000000000031371371177304000216720ustar00rootroot00000000000000#include #include "common.h" #define MAX_ARGUMENTS 10 static napi_value MakeCallback(napi_env env, napi_callback_info info) { size_t argc = MAX_ARGUMENTS; size_t n; napi_value args[MAX_ARGUMENTS]; // NOLINTNEXTLINE (readability/null_usage) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); napi_value recv = args[0]; napi_value func = args[1]; napi_value argv[MAX_ARGUMENTS - 2]; for (n = 2; n < argc; n += 1) { argv[n - 2] = args[n]; } napi_valuetype func_type; NAPI_CALL(env, napi_typeof(env, func, &func_type)); napi_value resource_name; NAPI_CALL(env, napi_create_string_utf8(env, "test", NAPI_AUTO_LENGTH, &resource_name)); napi_async_context context; NAPI_CALL(env, napi_async_init(env, func, resource_name, &context)); napi_value result; if (func_type == napi_function) { NAPI_CALL(env, napi_make_callback(env, context, recv, func, argc - 2, argv, &result)); } else { NAPI_ASSERT(env, false, "Unexpected argument type"); } NAPI_CALL(env, napi_async_destroy(env, context)); return result; } static napi_value Init(napi_env env, napi_value exports) { napi_value fn; NAPI_CALL(env, napi_create_function( // NOLINTNEXTLINE (readability/null_usage) env, NULL, NAPI_AUTO_LENGTH, MakeCallback, NULL, &fn)); NAPI_CALL(env, napi_set_named_property(env, exports, "makeCallback", fn)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) iotjs-1.0+715/test/napi/test_napi_make_callback.js000066400000000000000000000016221371177304000220610ustar00rootroot00000000000000'use strict'; var common = require('common.js'); var assert = require('assert'); var binding = require('./build/' + common.buildTypePath + '/test_napi_make_callback.node'); var makeCallback = binding.makeCallback; function myMultiArgFunc(arg1, arg2, arg3) { assert.strictEqual(arg1, 1); assert.strictEqual(arg2, 2); assert.strictEqual(arg3, 3); return 42; } assert.strictEqual(42, makeCallback(process, common.mustCall(function() { assert.strictEqual(0, arguments.length); assert.strictEqual(this, process); return 42; }))); assert.strictEqual(42, makeCallback(process, common.mustCall(function(x) { assert.strictEqual(1, arguments.length); assert.strictEqual(this, process); assert.strictEqual(x, 1337); return 42; }), 1337)); assert.strictEqual(42, makeCallback(this, common.mustCall(myMultiArgFunc), 1, 2, 3)); iotjs-1.0+715/test/napi/test_napi_make_callback_error.js000066400000000000000000000011441371177304000232710ustar00rootroot00000000000000'use strict'; var common = require('common.js'); var assert = require('assert'); var binding = require('./build/' + common.buildTypePath + '/test_napi_make_callback.node'); var makeCallback = binding.makeCallback; var first = true; process.on('uncaughtException', function(err) { if (first) { assert.strictEqual(err.message, 'foobar'); first = false; return; } assert.strictEqual(err.message, 'tick'); }); process.nextTick(common.mustCall(function() { throw new Error('tick'); })); makeCallback(process, common.mustCall(function() { throw new Error('foobar'); })); iotjs-1.0+715/test/napi/test_napi_object_wrap.c000066400000000000000000000027411371177304000214400ustar00rootroot00000000000000#include #include #include "common.h" static size_t native_counter = 0; static size_t native_hint = 0x8888; static napi_ref weak_ref; static void finalize(napi_env env, void* finalize_data, void* finalize_hint) { size_t* f_data = (size_t*)finalize_data; size_t* f_hint = (size_t*)finalize_hint; if (*f_hint != native_hint) napi_fatal_error(__FILE__, NAPI_AUTO_LENGTH, "finalize hint not aligned.", NAPI_AUTO_LENGTH); *f_data += 1; napi_delete_reference(env, weak_ref); } static void cleanup(void* data) { if (native_counter == 0) { napi_fatal_error(__FILE__, NAPI_AUTO_LENGTH, "finalize not invoked.", NAPI_AUTO_LENGTH); } } napi_value wrap(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value argv[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_CALL(env, napi_wrap(env, argv[0], &native_counter, finalize, &native_hint, &weak_ref)); /** * `weak_ref` is a weak reference, so leave as it be. */ return argv[0]; } napi_value get_native_counter(napi_env env, napi_callback_info info) { napi_value count; NAPI_CALL(env, napi_create_uint32(env, native_counter, &count)); return count; } NAPI_MODULE_INIT() { SET_NAMED_METHOD(env, exports, "Wrap", wrap); SET_NAMED_METHOD(env, exports, "GetNativeCounter", get_native_counter); NAPI_CALL(env, napi_add_env_cleanup_hook(env, cleanup, NULL)); return exports; } iotjs-1.0+715/test/napi/test_napi_object_wrap.js000066400000000000000000000006111371177304000216240ustar00rootroot00000000000000 'use strict'; var assert = require('assert'); var common = require('common.js'); var test = require('./build/' + common.buildTypePath + '/test_napi_object_wrap.node'); function context() { var obj = {}; assert.strictEqual(test.Wrap(obj), obj); } assert.strictEqual(test.GetNativeCounter(), 0); context(); process.gc(); assert.strictEqual(test.GetNativeCounter(), 1); iotjs-1.0+715/test/napi/test_napi_promise.c000066400000000000000000000034231371177304000206150ustar00rootroot00000000000000#include #include "common.h" napi_deferred deferred = NULL; static napi_value createPromise(napi_env env, napi_callback_info info) { napi_value promise; // We do not overwrite an existing deferred. if (deferred != NULL) { return NULL; } NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); return promise; } static napi_value concludeCurrentPromise(napi_env env, napi_callback_info info) { napi_value argv[2]; size_t argc = 2; bool resolution; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_CALL(env, napi_get_value_bool(env, argv[1], &resolution)); if (resolution) { NAPI_CALL(env, napi_resolve_deferred(env, deferred, argv[0])); } else { NAPI_CALL(env, napi_reject_deferred(env, deferred, argv[0])); } deferred = NULL; return NULL; } static napi_value isPromise(napi_env env, napi_callback_info info) { napi_value promise, result; size_t argc = 1; bool is_promise; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &promise, NULL, NULL)); NAPI_CALL(env, napi_is_promise(env, promise, &is_promise)); NAPI_CALL(env, napi_get_boolean(env, is_promise, &result)); return result; } static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("createPromise", createPromise), DECLARE_NAPI_PROPERTY("concludeCurrentPromise", concludeCurrentPromise), DECLARE_NAPI_PROPERTY("isPromise", isPromise), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) iotjs-1.0+715/test/napi/test_napi_promise.js000066400000000000000000000034341371177304000210110ustar00rootroot00000000000000'use strict'; var common = require('common.js'); // This tests the promise-related n-api calls var assert = require('assert'); var test_promise = require('./build/' + common.buildTypePath + '/test_napi_promise.node'); // A resolution { var expected_result = 42; var promise = test_promise.createPromise(); promise.then( common.mustCall(function(result) { assert.strictEqual(result, expected_result); })); test_promise.concludeCurrentPromise(expected_result, true); } // A rejection { var expected_result = 'It\'s not you, it\'s me.'; var promise = test_promise.createPromise(); promise.then(function(result) { // This should never be called assert.strictEqual(true, false); }); test_promise.concludeCurrentPromise(expected_result, false); } // Chaining { var expected_result = 'chained answer'; var promise = test_promise.createPromise(); promise.then( common.mustCall(function(result) { assert.strictEqual(result, expected_result); })); test_promise.concludeCurrentPromise(Promise.resolve('chained answer'), true); } var promiseTypeTestPromise = test_promise.createPromise(); assert.strictEqual(test_promise.isPromise(promiseTypeTestPromise), true); test_promise.concludeCurrentPromise(undefined, true); var rejectPromise = Promise.reject(-1); var expected_reason = -1; assert.strictEqual(test_promise.isPromise(rejectPromise), true); rejectPromise.catch((reason) => { assert.strictEqual(reason, expected_reason); }); assert.strictEqual(test_promise.isPromise(2.4), false); assert.strictEqual(test_promise.isPromise('I promise!'), false); assert.strictEqual(test_promise.isPromise(undefined), false); assert.strictEqual(test_promise.isPromise(null), false); assert.strictEqual(test_promise.isPromise({}), false); iotjs-1.0+715/test/napi/test_napi_properties.c000066400000000000000000000142551371177304000213400ustar00rootroot00000000000000/* Copyright 2019-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 "common.h" #include "node_api.h" static napi_value get_property(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects an object as first argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT(env, valuetype1 == napi_string, "Wrong type of arguments. Expects a string as second argument."); napi_value object = args[0]; napi_value output; NAPI_CALL(env, napi_get_property(env, object, args[1], &output)); return output; } static napi_value set_property(napi_env env, napi_callback_info info) { size_t argc = 3; napi_value args[3]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 3, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects an object as first argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT(env, valuetype1 == napi_string, "Wrong type of arguments. Expects a string as second argument."); NAPI_CALL(env, napi_set_property(env, args[0], args[1], args[2])); napi_value valuetrue; NAPI_CALL(env, napi_get_boolean(env, true, &valuetrue)); return valuetrue; } static napi_value has_property(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 2, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects an object as first argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT(env, valuetype1 == napi_string, "Wrong type of arguments. Expects a string as second argument."); bool has_property; NAPI_CALL(env, napi_has_property(env, args[0], args[1], &has_property)); napi_value ret; NAPI_CALL(env, napi_get_boolean(env, has_property, &ret)); return ret; } static napi_value has_own_property(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects an object as first argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT(env, valuetype1 == napi_string, "Wrong type of arguments. Expects a string as second argument."); bool has_property; NAPI_CALL(env, napi_has_own_property(env, args[0], args[1], &has_property)); napi_value ret; NAPI_CALL(env, napi_get_boolean(env, has_property, &ret)); return ret; } static napi_value get_property_names(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects an object as first argument."); napi_value obj = args[0]; napi_value propertynames; NAPI_CALL(env, napi_get_property_names(env, obj, &propertynames)); return propertynames; } static napi_value delete_property(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, "Wrong type of arguments. Expects an object as first argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT(env, valuetype1 == napi_string, "Wrong type of arguments. Expects a string as second argument."); bool result; napi_value ret; NAPI_CALL(env, napi_delete_property(env, args[0], args[1], &result)); NAPI_CALL(env, napi_get_boolean(env, result, &ret)); return ret; } static napi_value init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("GetProperty", get_property), DECLARE_NAPI_PROPERTY("SetProperty", set_property), DECLARE_NAPI_PROPERTY("HasProperty", has_property), DECLARE_NAPI_PROPERTY("HasOwnProperty", has_own_property), DECLARE_NAPI_PROPERTY("GetNames", get_property_names), DECLARE_NAPI_PROPERTY("DeleteProperty", delete_property), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, init) iotjs-1.0+715/test/napi/test_napi_properties.js000066400000000000000000000052541371177304000215310ustar00rootroot00000000000000/* Copyright 2019-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 common = require('common.js'); var prop_module = require('./build/' + common.buildTypePath + '/test_napi_properties.node'); var obj = { array: [ 1, 94, 'str', 12.321, { test: 'obj in arr' } ], num: 123, subObj: { test: 'obj in obj' }, str: 'hello' }; var names = prop_module.GetNames(obj); var keys = Object.keys(obj); assert.strictEqual(names.length, keys.length); for (var i = 0; i < keys.length; i++) { assert(prop_module.HasProperty(obj, keys[i])); assert.strictEqual(names[i], keys[i]); } assert.strictEqual(prop_module.GetProperty(obj, 'unkown'), undefined); assert(!prop_module.HasProperty(obj, 'unkown')); assert.strictEqual(prop_module.GetProperty(obj, 'num'), 123); assert(prop_module.SetProperty(obj, 'num', 321)); assert.strictEqual(prop_module.GetProperty(obj, 'num'), 321); assert.strictEqual(prop_module.GetProperty(obj, 'str'), 'hello'); assert(!prop_module.HasProperty(obj, 'newProp')); assert(prop_module.SetProperty(obj, 'newProp', 'newValue')); assert(prop_module.HasProperty(obj, 'newProp')); assert.strictEqual(prop_module.GetProperty(obj, 'newProp'), 'newValue'); assert(prop_module.DeleteProperty(obj, 'newProp')); assert(!prop_module.HasProperty(obj, 'newProp')); /* Test prototype chain */ function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; } Person.prototype.name = function() { return this.firstName + " " + this.lastName; }; var person = new Person('John', 'Doe', 99, 'blue'); assert(prop_module.HasProperty(person, 'name')); assert(prop_module.HasProperty(person, 'firstName')); assert(prop_module.HasProperty(person, 'lastName')); assert(!prop_module.HasOwnProperty(person, 'name')); assert(prop_module.HasOwnProperty(person, 'firstName')); assert(prop_module.HasOwnProperty(person, 'lastName')); assert(prop_module.DeleteProperty(Person.prototype, 'name')); assert(!prop_module.HasProperty(person, 'name')); assert(prop_module.HasProperty(person, 'firstName')); assert(prop_module.HasProperty(person, 'lastName')); iotjs-1.0+715/test/napi/test_napi_reference.c000066400000000000000000000115711371177304000211000ustar00rootroot00000000000000#include "common.h" #include "node_api.h" static int test_value = 1; static int finalize_count = 0; static napi_ref test_reference = NULL; static napi_value get_finalize_count(napi_env env, napi_callback_info info) { napi_value result; NAPI_CALL(env, napi_create_int32(env, finalize_count, &result)); return result; } static void finalize_external(napi_env env, void* data, void* hint) { int* actual_value = data; NAPI_ASSERT_RETURN_VOID(env, actual_value == &test_value, "The correct pointer was passed to the finalizer"); finalize_count++; } static napi_value create_external(napi_env env, napi_callback_info info) { int* data = &test_value; napi_value result; NAPI_CALL(env, napi_create_external(env, data, NULL, /* finalize_cb */ NULL, /* finalize_hint */ &result)); finalize_count = 0; return result; } static napi_value create_external_with_finalize(napi_env env, napi_callback_info info) { napi_value result; NAPI_CALL(env, napi_create_external(env, &test_value, finalize_external, NULL, /* finalize_hint */ &result)); finalize_count = 0; return result; } static napi_value check_external(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value arg; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arg, NULL, NULL)); NAPI_ASSERT(env, argc == 1, "Expected one argument."); napi_valuetype argtype; NAPI_CALL(env, napi_typeof(env, arg, &argtype)); NAPI_ASSERT(env, argtype == napi_external, "Expected an external value."); void* data; NAPI_CALL(env, napi_get_value_external(env, arg, &data)); NAPI_ASSERT(env, data != NULL && *(int*)data == test_value, "An external data value of 1 was expected."); return NULL; } static napi_value create_reference(napi_env env, napi_callback_info info) { NAPI_ASSERT(env, test_reference == NULL, "The test allows only one reference at a time."); size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc == 2, "Expected two arguments."); uint32_t initial_refcount; NAPI_CALL(env, napi_get_value_uint32(env, args[1], &initial_refcount)); NAPI_CALL(env, napi_create_reference(env, args[0], initial_refcount, &test_reference)); NAPI_ASSERT(env, test_reference != NULL, "A reference should have been created."); return NULL; } static napi_value delete_reference(napi_env env, napi_callback_info info) { NAPI_ASSERT(env, test_reference != NULL, "A reference must have been created."); NAPI_CALL(env, napi_delete_reference(env, test_reference)); test_reference = NULL; return NULL; } static napi_value increment_refcount(napi_env env, napi_callback_info info) { NAPI_ASSERT(env, test_reference != NULL, "A reference must have been created."); uint32_t refcount; NAPI_CALL(env, napi_reference_ref(env, test_reference, &refcount)); napi_value result; NAPI_CALL(env, napi_create_uint32(env, refcount, &result)); return result; } static napi_value decrement_refcount(napi_env env, napi_callback_info info) { NAPI_ASSERT(env, test_reference != NULL, "A reference must have been created."); uint32_t refcount; NAPI_CALL(env, napi_reference_unref(env, test_reference, &refcount)); napi_value result; NAPI_CALL(env, napi_create_uint32(env, refcount, &result)); return result; } static napi_value get_reference_value(napi_env env, napi_callback_info info) { NAPI_ASSERT(env, test_reference != NULL, "A reference must have been created."); napi_value result; NAPI_CALL(env, napi_get_reference_value(env, test_reference, &result)); return result; } static napi_value init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_GETTER("finalizeCount", get_finalize_count), DECLARE_NAPI_PROPERTY("createExternal", create_external), DECLARE_NAPI_PROPERTY("createExternalWithFinalize", create_external_with_finalize), DECLARE_NAPI_PROPERTY("checkExternal", check_external), DECLARE_NAPI_PROPERTY("createReference", create_reference), DECLARE_NAPI_PROPERTY("deleteReference", delete_reference), DECLARE_NAPI_PROPERTY("incrementRefcount", increment_refcount), DECLARE_NAPI_PROPERTY("decrementRefcount", decrement_refcount), DECLARE_NAPI_GETTER("referenceValue", get_reference_value), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, init) iotjs-1.0+715/test/napi/test_napi_reference.js000066400000000000000000000075201371177304000212710ustar00rootroot00000000000000'use strict'; // Flags: --expose-gc var assert = require('assert'); var common = require('common.js'); var test_reference = require('./build/' + common.buildTypePath + '/test_napi_reference.node'); // This test script uses external values with finalizer callbacks // in order to track when values get garbage-collected. Each invocation // of a finalizer callback increments the finalizeCount property. assert.strictEqual(test_reference.finalizeCount, 0); // Run each test function in sequence, // with an async delay and GC call between each. function runTests(i, title, tests) { if (tests[i]) { if (typeof tests[i] === 'string') { title = tests[i]; runTests(i + 1, title, tests); } else { try { tests[i](); } catch (e) { console.error('Test failed: ' + title); throw e; } setImmediate(function() { process.gc(); runTests(i + 1, title, tests); }); } } } runTests(0, undefined, [ 'External value without a finalizer', function() { var value = test_reference.createExternal(); assert.strictEqual(test_reference.finalizeCount, 0); assert.strictEqual(typeof value, 'object'); test_reference.checkExternal(value); }, function() { assert.strictEqual(test_reference.finalizeCount, 0); }, 'External value with a finalizer', function() { var value = test_reference.createExternalWithFinalize(); assert.strictEqual(test_reference.finalizeCount, 0); assert.strictEqual(typeof value, 'object'); test_reference.checkExternal(value); }, function() { assert.strictEqual(test_reference.finalizeCount, 1); }, 'Weak reference', function() { var value = test_reference.createExternalWithFinalize(); assert.strictEqual(test_reference.finalizeCount, 0); test_reference.createReference(value, 0); assert.strictEqual(test_reference.referenceValue, value); }, function() { // Value should be GC'd because there is only a weak ref assert.strictEqual(test_reference.referenceValue, undefined); assert.strictEqual(test_reference.finalizeCount, 1); test_reference.deleteReference(); }, 'Strong reference', function() { var value = test_reference.createExternalWithFinalize(); assert.strictEqual(test_reference.finalizeCount, 0); test_reference.createReference(value, 1); assert.strictEqual(test_reference.referenceValue, value); }, function() { // Value should NOT be GC'd because there is a strong ref assert.strictEqual(test_reference.finalizeCount, 0); test_reference.deleteReference(); }, function() { // Value should be GC'd because the strong ref was deleted assert.strictEqual(test_reference.finalizeCount, 1); }, 'Strong reference, increment then decrement to weak reference', function() { var value = test_reference.createExternalWithFinalize(); assert.strictEqual(test_reference.finalizeCount, 0); test_reference.createReference(value, 1); }, function() { // Value should NOT be GC'd because there is a strong ref assert.strictEqual(test_reference.finalizeCount, 0); assert.strictEqual(test_reference.incrementRefcount(), 2); }, function() { // Value should NOT be GC'd because there is a strong ref assert.strictEqual(test_reference.finalizeCount, 0); assert.strictEqual(test_reference.decrementRefcount(), 1); }, function() { // Value should NOT be GC'd because there is a strong ref assert.strictEqual(test_reference.finalizeCount, 0); assert.strictEqual(test_reference.decrementRefcount(), 0); }, function() { // Value should be GC'd because the ref is now weak! assert.strictEqual(test_reference.finalizeCount, 1); test_reference.deleteReference(); }, function() { // Value was already GC'd assert.strictEqual(test_reference.finalizeCount, 1); }, ]); iotjs-1.0+715/test/napi/test_napi_strictequal_and_instanceof.c000066400000000000000000000034231371177304000245320ustar00rootroot00000000000000#include #include #include #include "common.h" napi_value SayHello(napi_env env, napi_callback_info info) { size_t argc = 0; // test if `napi_get_cb_info` tolerants NULL pointers. NAPI_CALL(env, napi_get_cb_info(env, info, &argc, NULL, NULL, NULL)); napi_value str; NAPI_CALL(env, napi_create_string_utf8(env, "Hello", 5, &str)); return str; } napi_value SayError(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_throw_error(env, "foo", "bar")); return NULL; } napi_value StrictEquals(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value argv[2]; napi_value thisArg; void* data; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); bool result = false; NAPI_CALL(env, napi_strict_equals(env, argv[0], argv[1], &result)); napi_value ret; NAPI_CALL(env, napi_get_boolean(env, result, &ret)); return ret; } napi_value Instanceof(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value argv[2]; napi_value thisArg; void* data; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); bool result = false; NAPI_CALL(env, napi_instanceof(env, argv[0], argv[1], &result)); napi_value ret; NAPI_CALL(env, napi_get_boolean(env, result, &ret)); return ret; } napi_value Init(napi_env env, napi_value exports) { SET_NAMED_METHOD(env, exports, "sayHello", SayHello); SET_NAMED_METHOD(env, exports, "sayError", SayError); SET_NAMED_METHOD(env, exports, "strictEquals", StrictEquals); SET_NAMED_METHOD(env, exports, "instanceof", Instanceof); napi_value id; NAPI_CALL(env, napi_create_int32(env, 321, &id)); NAPI_CALL(env, napi_set_named_property(env, exports, "id", id)); return exports; } NAPI_MODULE(napi_test, Init); iotjs-1.0+715/test/napi/test_napi_strictequal_and_instanceof.js000066400000000000000000000014741371177304000247300ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); var napi_test = require('./build/' + common.buildTypePath + '/test_napi_strictequal_and_instanceof.node'); assert(napi_test !== null); assert.strictEqual(typeof napi_test, 'object'); assert.strictEqual(napi_test.id, 321); assert.strictEqual(typeof napi_test.sayHello, 'function'); assert.strictEqual(napi_test.sayHello(), 'Hello'); assert.strictEqual(typeof napi_test.sayError, 'function'); var error; try { napi_test.sayError(); } catch (err) { error = err; } assert(error instanceof Error); assert.strictEqual(error.code, 'foo'); assert.strictEqual(error.message, 'bar'); var lhs = {}; assert.strictEqual(napi_test.strictEquals(lhs, lhs), true); assert.strictEqual(napi_test.instanceof(lhs, Object), lhs instanceof Object); iotjs-1.0+715/test/napi/test_napi_string.c000066400000000000000000000047471371177304000204570ustar00rootroot00000000000000#include #include #include #include "common.h" static napi_value TestUtf8(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong type of argment. Expects a string."); char buffer[128]; size_t buffer_size = 128; size_t copied; NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], buffer, buffer_size, &copied)); napi_value output; NAPI_CALL(env, napi_create_string_utf8(env, buffer, copied, &output)); return output; } static napi_value TestUtf8Insufficient(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong type of argment. Expects a string."); char buffer[4]; size_t buffer_size = 4; size_t copied; NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], buffer, buffer_size, &copied)); napi_value output; NAPI_CALL(env, napi_create_string_utf8(env, buffer, copied, &output)); return output; } static napi_value Utf8Length(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong type of argment. Expects a string."); size_t length; NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], NULL, 0, &length)); napi_value output; NAPI_CALL(env, napi_create_uint32(env, (uint32_t)length, &output)); return output; } napi_value Init(napi_env env, napi_value exports) { SET_NAMED_METHOD(env, exports, "TestUtf8", TestUtf8); SET_NAMED_METHOD(env, exports, "TestUtf8Insufficient", TestUtf8Insufficient); SET_NAMED_METHOD(env, exports, "Utf8Length", Utf8Length); return exports; } NAPI_MODULE(napi_test, Init); iotjs-1.0+715/test/napi/test_napi_string.js000066400000000000000000000023031371177304000206330ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); var test = require('./build/' + common.buildTypePath + '/test_napi_string.node'); var empty = ''; assert.strictEqual(test.TestUtf8(empty), empty); assert.strictEqual(test.Utf8Length(empty), 0); var str1 = 'hello world'; assert.strictEqual(test.TestUtf8(str1), str1); assert.strictEqual(test.Utf8Length(str1), 11); var str2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; assert.strictEqual(test.TestUtf8(str2), str2); assert.strictEqual(test.Utf8Length(str2), 62); var str3 = '?!@#$%^&*()_+-=[]{}/.,<>\'"\\'; assert.strictEqual(test.TestUtf8(str3), str3); assert.strictEqual(test.Utf8Length(str3), 27); var str4 = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿'; assert.strictEqual(test.TestUtf8(str4), str4); assert.strictEqual(test.Utf8Length(str4), 62); var str5 ='ÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃÃÑÒÓÔÕÖרÙÚÛÜÃÞ' + 'ßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ'; assert.strictEqual(test.TestUtf8(str5), str5); assert.strictEqual(test.Utf8Length(str5), 126); // TODO: jerry-script doesn't support copy string value to insufficient buf iotjs-1.0+715/test/napi/test_napi_symbol.c000066400000000000000000000020431371177304000204410ustar00rootroot00000000000000#include "common.h" #include "node_api.h" static napi_value create_symbol(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); napi_value description = NULL; if (argc >= 1) { napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong type of arguments. Expects a string."); description = args[0]; } napi_value symbol; NAPI_CALL(env, napi_create_symbol(env, description, &symbol)); return symbol; } static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { DECLARE_NAPI_PROPERTY("CreateSymbol", create_symbol), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) iotjs-1.0+715/test/napi/test_napi_symbol.js000066400000000000000000000027721371177304000206440ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); // testing api calls for symbol var test_symbol = require('./build/' + common.buildTypePath + '/test_napi_symbol.node'); var sym = test_symbol.CreateSymbol('test'); assert.strictEqual(sym.toString(), 'Symbol(test)'); { var myObj = {}; var fooSym = test_symbol.CreateSymbol('foo'); var otherSym = test_symbol.CreateSymbol('bar'); myObj.foo = 'bar'; myObj[fooSym] = 'baz'; myObj[otherSym] = 'bing'; assert.strictEqual(myObj.foo, 'bar'); assert.strictEqual(myObj[fooSym], 'baz'); assert.strictEqual(myObj[otherSym], 'bing'); } { var fooSym = test_symbol.CreateSymbol('foo'); var myObj = {}; myObj.foo = 'bar'; myObj[fooSym] = 'baz'; Object.keys(myObj); // -> [ 'foo' ] Object.getOwnPropertyNames(myObj); // -> [ 'foo' ] Object.getOwnPropertySymbols(myObj); // -> [ Symbol(foo) ] assert.strictEqual(Object.getOwnPropertySymbols(myObj)[0], fooSym); } { assert.notStrictEqual(test_symbol.CreateSymbol(), test_symbol.CreateSymbol()); assert.notStrictEqual(test_symbol.CreateSymbol('foo'), test_symbol.CreateSymbol('foo')); assert.notStrictEqual(test_symbol.CreateSymbol('foo'), test_symbol.CreateSymbol('bar')); var foo1 = test_symbol.CreateSymbol('foo'); var foo2 = test_symbol.CreateSymbol('foo'); var object = { [foo1]: 1, [foo2]: 2, }; assert.strictEqual(object[foo1], 1); assert.strictEqual(object[foo2], 2); } iotjs-1.0+715/test/napi/test_napi_throw.js000066400000000000000000000007761371177304000205040ustar00rootroot00000000000000var common = require('common.js'); var addon = require('./build/' + common.buildTypePath + '/test_napi_error_handling'); var assert = require('assert'); var ERROR_MSG = "ErrorMSG"; var error = new Error(ERROR_MSG); var catched; try { addon.Throw(error) } catch (e) { catched = e; } assert(catched instanceof Error) assert(catched.message === ERROR_MSG) try { addon.Throw(ERROR_MSG) } catch (e) { catched = e; } assert(typeof catched === 'string') assert(catched === ERROR_MSG) iotjs-1.0+715/test/napi/test_napi_throw_error.js000066400000000000000000000014251371177304000217050ustar00rootroot00000000000000var common = require('common.js'); var addon = require('./build/' + common.buildTypePath + '/test_napi_error_handling'); var assert = require('assert'); var error; var ERROR_CODE = "ErrorCODE"; var ERROR_MSG = "ErrorMSG"; // Error try { addon.ThrowError(); } catch (e) { error = e; } assert(error instanceof Error); assert(error.code === "ErrorCODE"); assert(error.message === "ErrorMSG"); //TypeError try { addon.ThrowTypeError(); } catch (e) { error = e; } assert(error instanceof TypeError); assert(error.code === "ErrorCODE"); assert(error.message === "ErrorMSG"); //RangeError try { addon.ThrowRangeError(); } catch (e) { error = e; } assert(error instanceof RangeError); assert(error.code === "ErrorCODE"); assert(error.message === "ErrorMSG"); iotjs-1.0+715/test/napi/test_napi_typedarray.c000066400000000000000000000141561371177304000213300ustar00rootroot00000000000000#include "common.h" #include "node_api.h" #include static napi_value multiply(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT( env, valuetype0 == napi_object, "Wrong type of arguments. Expects a typed array as first argument."); napi_value input_array = args[0]; bool is_typedarray; NAPI_CALL(env, napi_is_typedarray(env, input_array, &is_typedarray)); NAPI_ASSERT( env, is_typedarray, "Wrong type of arguments. Expects a typed array as first argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT(env, valuetype1 == napi_number, "Wrong type of arguments. Expects a number as second argument."); double multiplier; NAPI_CALL(env, napi_get_value_double(env, args[1], &multiplier)); napi_typedarray_type type; napi_value input_buffer; size_t byte_offset; size_t i, length; NAPI_CALL(env, napi_get_typedarray_info(env, input_array, &type, &length, NULL, &input_buffer, &byte_offset)); void* data; size_t byte_length; NAPI_CALL(env, napi_get_arraybuffer_info(env, input_buffer, &data, &byte_length)); napi_value output_buffer; void* output_ptr = NULL; NAPI_CALL(env, napi_create_arraybuffer(env, byte_length, &output_ptr, &output_buffer)); napi_value output_array; NAPI_CALL(env, napi_create_typedarray(env, type, length, output_buffer, byte_offset, &output_array)); if (type == napi_uint8_array) { uint8_t* input_bytes = (uint8_t*)(data) + byte_offset; uint8_t* output_bytes = (uint8_t*)(output_ptr); for (i = 0; i < length; i++) { output_bytes[i] = (uint8_t)(input_bytes[i] * multiplier); } } else if (type == napi_float64_array) { double* input_doubles = (double*)((uint8_t*)(data) + byte_offset); double* output_doubles = (double*)(output_ptr); for (i = 0; i < length; i++) { output_doubles[i] = input_doubles[i] * multiplier; } } else { napi_throw_error(env, NULL, "Typed array was of a type not expected by test."); return NULL; } return output_array; } static napi_value external(napi_env env, napi_callback_info info) { static int8_t externalData[] = { 0, 1, 2 }; napi_value output_buffer; NAPI_CALL(env, napi_create_external_arraybuffer(env, externalData, sizeof(externalData), NULL, // finalize_callback NULL, // finalize_hint &output_buffer)); napi_value output_array; NAPI_CALL(env, napi_create_typedarray(env, napi_int8_array, sizeof(externalData) / sizeof(int8_t), output_buffer, 0, &output_array)); return output_array; } static napi_value create_typed_array(napi_env env, napi_callback_info info) { size_t argc = 4; napi_value args[4]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); NAPI_ASSERT(env, argc == 2 || argc == 4, "Wrong number of arguments"); napi_value input_array = args[0]; napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, input_array, &valuetype0)); NAPI_ASSERT( env, valuetype0 == napi_object, "Wrong type of arguments. Expects a typed array as first argument."); bool is_typedarray; NAPI_CALL(env, napi_is_typedarray(env, input_array, &is_typedarray)); NAPI_ASSERT( env, is_typedarray, "Wrong type of arguments. Expects a typed array as first argument."); napi_valuetype valuetype1; napi_value input_buffer = args[1]; NAPI_CALL(env, napi_typeof(env, input_buffer, &valuetype1)); NAPI_ASSERT( env, valuetype1 == napi_object, "Wrong type of arguments. Expects an array buffer as second argument."); bool is_arraybuffer; NAPI_CALL(env, napi_is_arraybuffer(env, input_buffer, &is_arraybuffer)); NAPI_ASSERT( env, is_arraybuffer, "Wrong type of arguments. Expects an array buffer as second argument."); napi_typedarray_type type; napi_value in_array_buffer; size_t byte_offset; size_t length; NAPI_CALL(env, napi_get_typedarray_info(env, input_array, &type, &length, NULL, &in_array_buffer, &byte_offset)); if (argc == 4) { napi_valuetype valuetype2; NAPI_CALL(env, napi_typeof(env, args[2], &valuetype2)); NAPI_ASSERT(env, valuetype2 == napi_number, "Wrong type of arguments. Expects a number as third argument."); uint32_t uint32_length; NAPI_CALL(env, napi_get_value_uint32(env, args[2], &uint32_length)); length = uint32_length; napi_valuetype valuetype3; NAPI_CALL(env, napi_typeof(env, args[3], &valuetype3)); NAPI_ASSERT(env, valuetype3 == napi_number, "Wrong type of arguments. Expects a number as third argument."); uint32_t uint32_byte_offset; NAPI_CALL(env, napi_get_value_uint32(env, args[3], &uint32_byte_offset)); byte_offset = uint32_byte_offset; } napi_value output_array; NAPI_CALL(env, napi_create_typedarray(env, type, length, input_buffer, byte_offset, &output_array)); return output_array; } static napi_value init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("Multiply", multiply), DECLARE_NAPI_PROPERTY("External", external), DECLARE_NAPI_PROPERTY("CreateTypedArray", create_typed_array), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, init) iotjs-1.0+715/test/napi/test_napi_typedarray.js000066400000000000000000000053221371177304000215150ustar00rootroot00000000000000'use strict'; var assert = require('assert'); var common = require('common.js'); // Testing api calls for arrays var test_typedarray = require('./build/' + common.buildTypePath + '/test_napi_typedarray.node'); var byteArray = new Uint8Array(3); byteArray[0] = 0; byteArray[1] = 1; byteArray[2] = 2; assert.strictEqual(byteArray.length, 3); var doubleArray = new Float64Array(3); doubleArray[0] = 0.0; doubleArray[1] = 1.1; doubleArray[2] = 2.2; assert.strictEqual(doubleArray.length, 3); var byteResult = test_typedarray.Multiply(byteArray, 3); assert(byteResult instanceof Uint8Array); assert.strictEqual(byteResult.length, 3); assert.strictEqual(byteResult[0], 0); assert.strictEqual(byteResult[1], 3); assert.strictEqual(byteResult[2], 6); var doubleResult = test_typedarray.Multiply(doubleArray, -3); assert(doubleResult instanceof Float64Array); assert.strictEqual(doubleResult.length, 3); assert.strictEqual(doubleResult[0], -0); assert.strictEqual(Math.round(10 * doubleResult[1]) / 10, -3.3); assert.strictEqual(Math.round(10 * doubleResult[2]) / 10, -6.6); var externalResult = test_typedarray.External(); assert(externalResult instanceof Int8Array); assert.strictEqual(externalResult.length, 3); assert.strictEqual(externalResult[0], 0); assert.strictEqual(externalResult[1], 1); assert.strictEqual(externalResult[2], 2); // validate creation of all kinds of TypedArrays var buffer = new ArrayBuffer(128); var arrayTypes = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ]; arrayTypes.forEach(function(currentType) { var template = new currentType(buffer); var theArray = test_typedarray.CreateTypedArray(template, buffer); assert(theArray instanceof currentType, 'Type of new array should match that of the template. ' + 'Expected type: ' + currentType.name + 'actual type: ' + template.constructor.name); assert.notStrictEqual(theArray, template); assert.strictEqual(theArray.buffer, buffer); }); arrayTypes.forEach(function(currentType) { var template = new currentType(buffer); assert.throws(function() { test_typedarray.CreateTypedArray(template, buffer, 0, 136); }, RangeError); }); var nonByteArrayTypes = [ Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ]; nonByteArrayTypes.forEach(function(currentType) { var template = new currentType(buffer); assert.throws(function() { test_typedarray.CreateTypedArray(template, buffer, currentType.BYTES_PER_ELEMENT + 1, 1); console.log('start of offset ' + currentType); }, RangeError); }); iotjs-1.0+715/test/node/000077500000000000000000000000001371177304000147215ustar00rootroot00000000000000iotjs-1.0+715/test/node/common.js000066400000000000000000000367471371177304000165700ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. /* eslint-disable required-modules */ 'use strict'; var fs = require('fs'); var assert = require('assert'); var stream = require('stream'); var util = require('util'); var __dirname = process.cwd(); var testRoot = __dirname; // PORT should match the definition in test/testpy/__init__.py. exports.PORT = +process.env.NODE_COMMON_PORT || 12346; exports.isWindows = process.platform === 'windows'; exports.isWOW64 = exports.isWindows && (process.env.PROCESSOR_ARCHITEW6432 !== undefined); exports.isAix = process.platform === 'aix'; exports.isLinuxPPCBE = (process.platform === 'linux') && (process.arch === 'ppc64') && (os.endianness() === 'BE'); exports.isSunOS = process.platform === 'sunos'; exports.isFreeBSD = process.platform === 'freebsd'; exports.isLinux = process.platform === 'linux'; exports.isNuttX = process.platform === 'nuttx'; exports.isTizen = process.platform === 'tizen'; exports.isOSX = process.platform === 'darwin'; exports.enoughTestMem = false; exports.enoughTestCpu = false; exports.rootDir = exports.isWindows ? 'c:\\' : '/'; var dirsep = exports.isWindows ? '\\' : '/'; exports.fixturesDir = __dirname + dirsep + 'fixtures'; exports.tmpDirName = 'tmp'; function rimrafSync(p) { var st; try { st = fs.lstatSync(p); } catch (e) { if (e.code === 'ENOENT') return; } try { if (st && st.isDirectory()) rmdirSync(p, null); else fs.unlinkSync(p); } catch (e) { if (e.code === 'ENOENT') return; if (e.code === 'EPERM') return rmdirSync(p, e); if (e.code !== 'EISDIR') throw e; rmdirSync(p, e); } } function rmdirSync(p, originalEr) { try { fs.rmdirSync(p); } catch (e) { if (e.code === 'ENOTDIR') throw originalEr; if (e.code === 'ENOTEMPTY' || e.code === 'EEXIST' || e.code === 'EPERM') { var enc = (exports.isLinux || exports.isTizen) ? 'buffer' : 'utf8'; fs.readdirSync(p, enc).forEach(function(f) { if (f instanceof Buffer) { var buf = Buffer.concat([Buffer.from(p), Buffer.from(path.sep), f]); rimrafSync(buf); } else { rimrafSync(path.join(p, f)); } }); fs.rmdirSync(p); } } } exports.refreshTmpDir = function() { rimrafSync(exports.tmpDir); fs.mkdirSync(exports.tmpDir); }; if (process.env.TEST_THREAD_ID) { exports.PORT += process.env.TEST_THREAD_ID * 100; exports.tmpDirName += '.' + process.env.TEST_THREAD_ID; } exports.tmpDir = testRoot + dirsep + exports.tmpDirName; var opensslCli = null; var inFreeBSDJail = null; var localhostIPv4 = null; exports.localIPv6Hosts = ['localhost']; if (exports.isLinux || exports.isTizen) { exports.localIPv6Hosts = [ // Debian/Ubuntu 'ip6-localhost', 'ip6-loopback', // SUSE 'ipv6-localhost', 'ipv6-loopback', // Typically universal 'localhost', ]; } Object.defineProperty(exports, 'inFreeBSDJail', { get: function() { if (inFreeBSDJail !== null) return inFreeBSDJail; if (exports.isFreeBSD && child_process.execSync('sysctl -n security.jail.jailed').toString() === '1\n') { inFreeBSDJail = true; } else { inFreeBSDJail = false; } return inFreeBSDJail; } }); Object.defineProperty(exports, 'localhostIPv4', { get: function() { if (localhostIPv4 !== null) return localhostIPv4; if (exports.inFreeBSDJail) { // Jailed network interfaces are a bit special - since we need to jump // through loops, as well as this being an exception case, assume the // user will provide this instead. if (process.env.LOCALHOST) { localhostIPv4 = process.env.LOCALHOST; } else { console.error('Looks like we\'re in a FreeBSD Jail. ' + 'Please provide your default interface address ' + 'as LOCALHOST or expect some tests to fail.'); } } if (localhostIPv4 === null) localhostIPv4 = '127.0.0.1'; return localhostIPv4; } }); Object.defineProperty(exports, 'hasCrypto', { get: function() { return process.versions.openssl ? true : false; } }); Object.defineProperty(exports, 'hasFipsCrypto', { get: function() { return exports.hasCrypto && require('crypto').fips; } }); if (exports.isWindows) { exports.PIPE = '\\\\.\\pipe\\libuv-test'; if (process.env.TEST_THREAD_ID) { exports.PIPE += '.' + process.env.TEST_THREAD_ID; } } else { exports.PIPE = exports.tmpDir + '/test.sock'; } exports.hasIPv6 = false; /* * Check that when running a test with * `$node --abort-on-uncaught-exception $file child` * the process aborts. */ exports.childShouldThrowAndAbort = function() { var testCmd = ''; if (!exports.isWindows) { // Do not create core files, as it can take a lot of disk space on // continuous testing and developers' machines testCmd += 'ulimit -c 0 && '; } testCmd += process.argv[0] + ' --abort-on-uncaught-exception '; testCmd += process.argv[1] + ' child'; var child = child_process.exec(testCmd); child.on('exit', function onExit(exitCode, signal) { var errMsg = 'Test should have aborted ' + 'but instead exited with exit code ' + exitCode + ' and signal ' + signal; assert(exports.nodeProcessAborted(exitCode, signal), errMsg); }); }; exports.ddCommand = function(filename, kilobytes) { if (exports.isWindows) { var p = path.resolve(exports.fixturesDir, 'create-file.js'); return '"' + process.argv[0] + '" "' + p + '" "' + filename + '" ' + (kilobytes * 1024); } else { return 'dd if=/dev/zero of="' + filename + '" bs=1024 count=' + kilobytes; } }; exports.spawnCat = function(options) { var spawn = require('child_process').spawn; if (exports.isWindows) { return spawn('more', [], options); } else { return spawn('cat', [], options); } }; exports.spawnSyncCat = function(options) { var spawnSync = require('child_process').spawnSync; if (exports.isWindows) { return spawnSync('more', [], options); } else { return spawnSync('cat', [], options); } }; exports.spawnPwd = function(options) { var spawn = require('child_process').spawn; if (exports.isWindows) { return spawn('cmd.exe', ['/c', 'cd'], options); } else { return spawn('pwd', [], options); } }; exports.spawnSyncPwd = function(options) { var spawnSync = require('child_process').spawnSync; if (exports.isWindows) { return spawnSync('cmd.exe', ['/c', 'cd'], options); } else { return spawnSync('pwd', [], options); } }; exports.platformTimeout = function(ms) { if (process.config.target_defaults.default_configuration === 'Debug') ms = 2 * ms; if (exports.isAix) return 2 * ms; // default localhost speed is slower on AIX if (process.arch !== 'arm') return ms; var armv = process.config.variables.arm_version; if (armv === '6') return 7 * ms; // ARMv6 if (armv === '7') return 2 * ms; // ARMv7 return ms; // ARMv8+ }; var knownGlobals = [ Buffer, clearInterval, clearTimeout, console, constructor, // Enumerable in V8 3.21. global, process, setInterval, setTimeout ]; if (global.gc) { knownGlobals.push(global.gc); } if (global.DTRACE_HTTP_SERVER_RESPONSE) { knownGlobals.push(DTRACE_HTTP_SERVER_RESPONSE); knownGlobals.push(DTRACE_HTTP_SERVER_REQUEST); knownGlobals.push(DTRACE_HTTP_CLIENT_RESPONSE); knownGlobals.push(DTRACE_HTTP_CLIENT_REQUEST); knownGlobals.push(DTRACE_NET_STREAM_END); knownGlobals.push(DTRACE_NET_SERVER_CONNECTION); } if (global.COUNTER_NET_SERVER_CONNECTION) { knownGlobals.push(COUNTER_NET_SERVER_CONNECTION); knownGlobals.push(COUNTER_NET_SERVER_CONNECTION_CLOSE); knownGlobals.push(COUNTER_HTTP_SERVER_REQUEST); knownGlobals.push(COUNTER_HTTP_SERVER_RESPONSE); knownGlobals.push(COUNTER_HTTP_CLIENT_REQUEST); knownGlobals.push(COUNTER_HTTP_CLIENT_RESPONSE); } if (global.LTTNG_HTTP_SERVER_RESPONSE) { knownGlobals.push(LTTNG_HTTP_SERVER_RESPONSE); knownGlobals.push(LTTNG_HTTP_SERVER_REQUEST); knownGlobals.push(LTTNG_HTTP_CLIENT_RESPONSE); knownGlobals.push(LTTNG_HTTP_CLIENT_REQUEST); knownGlobals.push(LTTNG_NET_STREAM_END); knownGlobals.push(LTTNG_NET_SERVER_CONNECTION); } if (global.ArrayBuffer) { knownGlobals.push(ArrayBuffer); knownGlobals.push(Int8Array); knownGlobals.push(Uint8Array); knownGlobals.push(Uint8ClampedArray); knownGlobals.push(Int16Array); knownGlobals.push(Uint16Array); knownGlobals.push(Int32Array); knownGlobals.push(Uint32Array); knownGlobals.push(Float32Array); knownGlobals.push(Float64Array); // knownGlobals.push(DataView); } // Harmony features. if (global.Proxy) { knownGlobals.push(Proxy); } if (global.Symbol) { knownGlobals.push(Symbol); } function allowGlobals() { knownGlobals = knownGlobals.concat(arguments); } exports.allowGlobals = allowGlobals; function leakedGlobals() { var leaked = []; for (var val in global) { if (knownGlobals.indexOf(global[val]) == -1) leaked.push(val); } return leaked; } exports.leakedGlobals = leakedGlobals; // TODO: fix the knownGlobal list // Turn this on if the test should check for global leaks. exports.globalCheck = false; process.on('exit', function() { if (!exports.globalCheck) return; var leaked = leakedGlobals(); if (leaked.length > 0) { console.error('Unexpected global(s) found: ' + leaked.join(', ')); } }); var mustCallChecks = []; function runCallChecks(exitCode) { if (exitCode !== 0) return; var failed = mustCallChecks.filter(function(context) { return context.actual !== context.expected; }); failed.forEach(function(context) { console.log('Mismatched %s function calls. Expected %d, actual %d.', context.name, context.expected, context.actual); console.log(context.stack.split('\n').slice(2).join('\n')); }); if (failed.length) process.exit(1); } exports.mustCall = function(fn, expected) { if (expected === undefined) expected = 1; else if (typeof expected !== 'number') throw new TypeError('Invalid expected value: ' + expected); var context = { expected: expected, actual: 0, stack: (new Error()).stack, name: fn.name || '' }; // add the exit listener only once to avoid listener leak warnings if (mustCallChecks.length === 0) process.on('exit', runCallChecks); mustCallChecks.push(context); return function() { context.actual++; return fn.apply(this, arguments); }; }; exports.hasMultiLocalhost = function hasMultiLocalhost() { var TCP = process.binding('tcp_wrap').TCP; var t = new TCP(); var ret = t.bind('127.0.0.2', exports.PORT); t.close(); return ret === 0; }; exports.fileExists = function(pathname) { try { fs.accessSync(pathname); return true; } catch (err) { return false; } }; function fail(msg) { assert.fail(null, null, msg); } exports.fail = fail; exports.skip = function(msg) { console.log('1..0 # Skipped: ' + msg); }; // A stream to push an array into a REPL function ArrayStream() { this.run = function(data) { data.forEach(function(line) { this.emit('data', line + '\n'); }); }; } util.inherits(ArrayStream, stream.Stream); exports.ArrayStream = ArrayStream; ArrayStream.prototype.readable = true; ArrayStream.prototype.writable = true; ArrayStream.prototype.pause = function() {}; ArrayStream.prototype.resume = function() {}; ArrayStream.prototype.write = function() {}; // Returns true if the exit code "exitCode" and/or signal name "signal" // represent the exit code and/or signal name of a node process that aborted, // false otherwise. exports.nodeProcessAborted = function nodeProcessAborted(exitCode, signal) { // Depending on the compiler used, node will exit with either // exit code 132 (SIGILL), 133 (SIGTRAP) or 134 (SIGABRT). var expectedExitCodes = [132, 133, 134]; // On platforms using KSH as the default shell (like SmartOS), // when a process aborts, KSH exits with an exit code that is // greater than 256, and thus the exit code emitted with the 'exit' // event is null and the signal is set to either SIGILL, SIGTRAP, // or SIGABRT (depending on the compiler). var expectedSignals = ['SIGILL', 'SIGTRAP', 'SIGABRT']; // On Windows, v8's base::OS::Abort triggers an access violation, // which corresponds to exit code 3221225477 (0xC0000005) if (exports.isWindows) expectedExitCodes = [3221225477]; // When using --abort-on-uncaught-exception, V8 will use // base::OS::Abort to terminate the process. // Depending on the compiler used, the shell or other aspects of // the platform used to build the node binary, this will actually // make V8 exit by aborting or by raising a signal. In any case, // one of them (exit code or signal) needs to be set to one of // the expected exit codes or signals. if (signal !== null) { return expectedSignals.includes(signal); } else { return expectedExitCodes.includes(exitCode); } }; exports.busyLoop = function busyLoop(time) { var startTime = Date.now(); var stopTime = startTime + time; while (Date.now() < stopTime) {} }; exports.isAlive = function isAlive(pid) { try { process.kill(pid, 'SIGCONT'); return true; } catch (e) { return false; } }; exports.expectWarning = function(name, expected) { if (typeof expected === 'string') expected = [expected]; process.on('warning', exports.mustCall(function(warning) { assert.strictEqual(warning.name, name); assert.ok(expected.includes(warning.message), 'unexpected error message: "' + warning.message + '"'); // Remove a warning message after it is seen so that we guarantee that we // get each message only once. expected.splice(expected.indexOf(warning.message), 1); }, expected.length)); }; // IoT.js extensions assert.ok = function(value, message) { assert.equal(!!value, true, message); } iotjs-1.0+715/test/node/parallel/000077500000000000000000000000001371177304000165155ustar00rootroot00000000000000iotjs-1.0+715/test/node/parallel/test-assert.js000066400000000000000000000142721371177304000213370ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; require('node/common'); var assert = require('assert'); var a = require('assert'); // Test starts here function makeBlock(f) { var args = Array.prototype.slice.call(arguments, 1); return function() { return f.apply(this, args); }; } assert.ok(a.AssertionError.prototype instanceof Error, 'a.AssertionError instanceof Error'); assert.throws(makeBlock(a, false), a.AssertionError, 'ok(false)'); assert.doesNotThrow(makeBlock(a, true), a.AssertionError, 'ok(true)'); assert.doesNotThrow(makeBlock(a, 'test', 'ok(\'test\')')); assert.throws(makeBlock(a.ok, false), a.AssertionError, 'ok(false)'); assert.doesNotThrow(makeBlock(a.ok, true), a.AssertionError, 'ok(true)'); assert.doesNotThrow(makeBlock(a.ok, 'test'), 'ok(\'test\')'); assert.throws(makeBlock(a.equal, true, false), a.AssertionError, 'equal(true, false)'); assert.doesNotThrow(makeBlock(a.equal, null, null), 'equal(null, null)'); assert.doesNotThrow(makeBlock(a.equal, undefined, undefined), 'equal(undefined, undefined)'); assert.doesNotThrow(makeBlock(a.equal, null, undefined), 'equal(null, undefined)'); assert.doesNotThrow(makeBlock(a.equal, true, true), 'equal(true, true)'); assert.doesNotThrow(makeBlock(a.equal, 2, '2'), 'equal(2, \'2\')'); assert.doesNotThrow(makeBlock(a.notEqual, true, false), 'notEqual(true, false)'); assert.throws(makeBlock(a.notEqual, true, true), a.AssertionError, 'notEqual(true, true)'); assert.throws(makeBlock(a.strictEqual, 2, '2'), a.AssertionError, 'strictEqual(2, \'2\')'); assert.throws(makeBlock(a.strictEqual, null, undefined), a.AssertionError, 'strictEqual(null, undefined)'); assert.throws(makeBlock(a.notStrictEqual, 2, 2), a.AssertionError, 'notStrictEqual(2, 2)'); assert.doesNotThrow(makeBlock(a.notStrictEqual, 2, '2'), 'notStrictEqual(2, \'2\')'); // Testing the throwing function thrower(errorConstructor) { throw new errorConstructor('test'); } // the basic calls work assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError, 'message'); assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError); assert.throws(makeBlock(thrower, a.AssertionError)); // if not passing an error, catch all. assert.throws(makeBlock(thrower, TypeError)); // when passing a type, only catch errors of the appropriate type var threw = false; try { a.throws(makeBlock(thrower, TypeError), a.AssertionError); } catch (e) { threw = true; assert.ok(e instanceof TypeError, 'type'); } assert.strictEqual(true, threw, 'a.throws with an explicit error is eating extra errors', a.AssertionError); threw = false; // key difference is that throwing our correct error makes an assertion error try { a.doesNotThrow(makeBlock(thrower, TypeError), TypeError); } catch (e) { threw = true; assert.ok(e instanceof a.AssertionError); } assert.strictEqual(true, threw, 'a.doesNotThrow is not catching type matching errors'); var circular = {y: 1}; circular.x = circular; function testAssertionMessage(actual, expected) { try { assert.strictEqual(actual, ''); } catch (e) { assert.ok(e.toString()); } } testAssertionMessage(undefined, 'undefined'); testAssertionMessage(null, 'null'); testAssertionMessage(true, 'true'); testAssertionMessage(false, 'false'); testAssertionMessage(0, '0'); testAssertionMessage(100, '100'); testAssertionMessage(NaN, 'NaN'); testAssertionMessage(Infinity, 'Infinity'); testAssertionMessage(-Infinity, '-Infinity'); testAssertionMessage('', '""'); testAssertionMessage('foo', '\'foo\''); testAssertionMessage([], '[]'); testAssertionMessage([1, 2, 3], '[ 1, 2, 3 ]'); testAssertionMessage(/a/, '/a/'); testAssertionMessage(/abc/gim, '/abc/gim'); testAssertionMessage(function f() {}, '[Function: f]'); testAssertionMessage(function() {}, '[Function]'); testAssertionMessage({}, '{}'); testAssertionMessage(circular, '{ y: 1, x: [Circular] }'); testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }'); testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, '{ a: NaN, b: Infinity, c: -Infinity }'); // #2893 try { assert.throws(function() { assert.ifError(null); }); } catch (e) { threw = true; assert.strictEqual(e.message, 'Missing expected exception..'); } assert.ok(threw); console.log('All OK'); iotjs-1.0+715/test/node/parallel/test-http-catch-uncaughtexception.js000066400000000000000000000045101371177304000256220ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; var common = require('node/common'); var assert = require('assert'); var http = require('http'); var uncaughtCallback = common.mustCall(function(er) { assert.strictEqual(er.message, 'get did fail'); }); process.on('uncaughtException', uncaughtCallback); var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('bye'); }).listen(0, function() { http.get({ port: this.address().port }, function(res) { res.resume(); throw new Error('get did fail'); }).on('close', function() { server.close(); }); }); iotjs-1.0+715/test/node/parallel/test-http-status-message.js000066400000000000000000000046741371177304000237650ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; require('node/common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var s = http.createServer(function (req, res) { res.statusCode = 200; res.statusMessage = 'Custom Message'; res.end(''); }); s.listen(0, test); function test() { var bufs = []; var client = net.connect(this.address().port, function () { client.write('GET / HTTP/1.1\r\nConnection: close\r\n\r\n'); }); client.on('data', function (chunk) { bufs.push(chunk); }); client.on('end', function () { var head = Buffer.concat(bufs).toString().split('\r\n')[0]; assert.strictEqual('HTTP/1.1 200 Custom Message', head); console.log('ok'); s.close(); }); } iotjs-1.0+715/test/node/parallel/test-http-write-head.js000066400000000000000000000062021371177304000230360ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; var common = require('node/common'); var assert = require('assert'); var http = require('http'); // Verify that ServerResponse.writeHead() works as setHeader. // Issue 5036 on github. var s = http.createServer(common.mustCall(function (req, res) { res.setHeader('test', '1'); // toLowerCase() is used on the name argument, so it must be a string. var threw = false; try { res.setHeader(0xf00, 'bar'); } catch (e) { assert.ok(e instanceof TypeError); threw = true; } assert.ok(threw, 'Non-string names should throw'); // undefined value should throw, via 979d0ca8 threw = false; try { res.setHeader('foo', undefined); } catch (e) { assert.ok(e instanceof Error); assert.strictEqual(e.message, 'value required in setHeader(foo, value)'); threw = true; } assert.ok(threw, 'Undefined value should throw'); res.writeHead(200, { Test: '2' }); // assert.throws(function () { assert.doesNotThrow(function () { res.writeHead(100, {}); }); res.end(); })); s.listen(0, common.mustCall(runTest)); function runTest() { http.get({ port: this.address().port }, common.mustCall(function (response) { response.on('end', common.mustCall(function () { assert.strictEqual(response.headers['test'], '1' /*'2'*/); // assert.notStrictEqual(response.rawHeaders.indexOf('Test'), -1); s.close(); })); response.resume(); })); } iotjs-1.0+715/test/node/parallel/test-module-circular-b.js000066400000000000000000000034421371177304000233410ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; require('./test-module-circular'); iotjs-1.0+715/test/node/parallel/test-module-circular.js000066400000000000000000000035551371177304000231270ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; require('node/common'); var assert = require('assert'); require('./test-module-circular-b'); assert.ok(true); iotjs-1.0+715/test/node/parallel/test-net-after-close.js000066400000000000000000000045531371177304000230270ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; var common = require('node/common'); var assert = require('assert'); var net = require('net'); var server = net.createServer(function(s) { console.error('SERVER: got connection'); s.end(); }); server.listen(0, common.mustCall(function() { var c = net.createConnection(this.address().port); c.on('close', common.mustCall(function() { console.error('connection closed'); assert.strictEqual(c._handle, null); assert.doesNotThrow(function() { c.setKeepAlive(); c.pause(); c.resume(); c.address(); c.remoteAddress; c.remotePort; }); server.close(); })); })); iotjs-1.0+715/test/node/parallel/test-net-bind-twice.js000066400000000000000000000047031371177304000226450ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; var common = require('node/common'); var assert = require('assert'); var net = require('net'); var server1 = net.createServer(common.fail); server1.listen(0, '127.0.0.1', common.mustCall(function() { var server2 = net.createServer(common.fail); server2.on('error', common.mustCall(function(e) { // EADDRINUSE has different values on OSX and NuttX. if (common.isOSX) { assert.strictEqual(e, -48); } else if (common.isNuttX) { assert.strictEqual(e, -112); } else if (common.isWindows) { assert.strictEqual(e, -4091); } else { assert.strictEqual(e, -98); } server1.close(); })); server2.listen(this.address().port, '127.0.0.1', common.fail); })); iotjs-1.0+715/test/node/parallel/test-net-end-without-connect.js000066400000000000000000000035561371177304000245230ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; require('node/common'); var net = require('net'); var sock = new net.Socket(); sock.end(); // Should not throw. iotjs-1.0+715/test/node/parallel/test-net-keepalive.js000066400000000000000000000047511371177304000225700ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; var common = require('node/common'); var assert = require('assert'); var net = require('net'); var serverConnection; var clientConnection; var echoServer = net.createServer(function(connection) { serverConnection = connection; setTimeout(function() { serverConnection.end(); clientConnection.end(); echoServer.close(); }, 100); connection.setTimeout(0); assert.notStrictEqual(connection.setKeepAlive, undefined); // send a keepalive packet after 50 ms connection.setKeepAlive(true, 50); connection.on('end', function() { connection.end(); }); }); echoServer.listen(0); echoServer.on('listening', function() { clientConnection = net.createConnection(this.address().port); clientConnection.setTimeout(0); }); iotjs-1.0+715/test/node/parallel/test-timers-clear-null-does-not-throw-error.js000066400000000000000000000043441371177304000274120ustar00rootroot00000000000000/* 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. */ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; require('node/common'); var assert = require('assert'); // This test makes sure clearing timers with // 'null' or no input does not throw error assert.doesNotThrow(function() { clearInterval(null) }); assert.doesNotThrow(function() { clearInterval() }); assert.doesNotThrow(function() { clearTimeout(null) }); assert.doesNotThrow(function() { clearTimeout() }); // assert.doesNotThrow(function() { clearImmediate(null) }); // assert.doesNotThrow(function() { clearImmediate() }); iotjs-1.0+715/test/profiles/000077500000000000000000000000001371177304000156175ustar00rootroot00000000000000iotjs-1.0+715/test/profiles/host-darwin.profile000066400000000000000000000001271371177304000214400ustar00rootroot00000000000000ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_IOTJS_CORE_MODULES ENABLE_MODULE_HTTPS iotjs-1.0+715/test/profiles/host-linux.profile000066400000000000000000000005101371177304000213070ustar00rootroot00000000000000ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_IOTJS_CORE_MODULES ENABLE_MODULE_ADC ENABLE_MODULE_BLE ENABLE_MODULE_CRYPTO ENABLE_MODULE_DGRAM ENABLE_MODULE_GPIO ENABLE_MODULE_HTTP_SIGNATURE ENABLE_MODULE_HTTPS ENABLE_MODULE_I2C ENABLE_MODULE_MQTT ENABLE_MODULE_PWM ENABLE_MODULE_SPI ENABLE_MODULE_UART ENABLE_MODULE_WEBSOCKET iotjs-1.0+715/test/profiles/mock-linux.profile000066400000000000000000000001721371177304000212670ustar00rootroot00000000000000ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_IOTJS_CORE_MODULES ENABLE_MODULE_GPIO ENABLE_MODULE_I2C ENABLE_MODULE_PWM iotjs-1.0+715/test/profiles/nuttx.profile000066400000000000000000000003631371177304000203650ustar00rootroot00000000000000ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_IOTJS_CORE_MODULES ENABLE_MODULE_ADC ENABLE_MODULE_CRYPTO ENABLE_MODULE_DGRAM ENABLE_MODULE_GPIO ENABLE_MODULE_I2C ENABLE_MODULE_PWM ENABLE_MODULE_SPI ENABLE_MODULE_STM32F4DIS ENABLE_MODULE_UART iotjs-1.0+715/test/profiles/rpi2-linux.profile000066400000000000000000000004661371177304000212200ustar00rootroot00000000000000ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_IOTJS_CORE_MODULES ENABLE_MODULE_BLE ENABLE_MODULE_CRYPTO ENABLE_MODULE_DGRAM ENABLE_MODULE_GPIO ENABLE_MODULE_HTTP_SIGNATURE ENABLE_MODULE_HTTPS ENABLE_MODULE_MQTT ENABLE_MODULE_I2C ENABLE_MODULE_PWM ENABLE_MODULE_SPI ENABLE_MODULE_UART ENABLE_MODULE_WEBSOCKET iotjs-1.0+715/test/profiles/tizen-jerry.profile000066400000000000000000000000171371177304000214610ustar00rootroot00000000000000JERRY_ES2015=0 iotjs-1.0+715/test/profiles/tizen.profile000066400000000000000000000005151371177304000203330ustar00rootroot00000000000000ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_IOTJS_CORE_MODULES ENABLE_MODULE_BRIDGE ENABLE_MODULE_CRYPTO ENABLE_MODULE_DGRAM ENABLE_MODULE_GPIO ENABLE_MODULE_HTTP_SIGNATURE ENABLE_MODULE_HTTPS ENABLE_MODULE_MQTT ENABLE_MODULE_I2C ENABLE_MODULE_PWM ENABLE_MODULE_SPI ENABLE_MODULE_TIZEN ENABLE_MODULE_UART ENABLE_MODULE_WEBSOCKET iotjs-1.0+715/test/profiles/tizenrt.profile000066400000000000000000000004661371177304000207060ustar00rootroot00000000000000ENABLE_MODULE_IOTJS_BASIC_MODULES ENABLE_MODULE_IOTJS_CORE_MODULES ENABLE_MODULE_ADC ENABLE_MODULE_CRYPTO ENABLE_MODULE_DGRAM ENABLE_MODULE_GPIO ENABLE_MODULE_HTTP_SIGNATURE ENABLE_MODULE_HTTPS ENABLE_MODULE_MQTT ENABLE_MODULE_I2C ENABLE_MODULE_PWM ENABLE_MODULE_SPI ENABLE_MODULE_UART ENABLE_MODULE_WEBSOCKET iotjs-1.0+715/test/resources/000077500000000000000000000000001371177304000160065ustar00rootroot00000000000000iotjs-1.0+715/test/resources/crypto_public.pem000066400000000000000000000007031371177304000213670ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsHbJBfgc4tPdH0bkuVoL AAhN6rxk7RaD73thMVP1KtlyomXdydWT9CEBR/MBepyQaokHHYt430tqbOYeeYss +SJUp2mU0C+XCcuD27T5lcwbUOFhN8pkerUKvuqM8u+ndYwgEbn8XHXSM+x62qWd wM6CO/kJx5CtzQaJ+2jPfdPnUYB3BpZvRL4ymzvGa3lUpwmtns3jfyZjJMz7Bd3A kH9gJTREhTLM3A4LNocgvIFLJNadlTbB5OgMMHxH3EEmXn1Wq+LeC57E4f2PuhmX vSRLbT85NpGC1U1AmuG2IVitwFkw1Hx23lZG8Zld/ZeV3kLBwJ2o002U3rs+H1aP 8QIDAQAB -----END PUBLIC KEY----- iotjs-1.0+715/test/resources/greeting.txt000066400000000000000000000000161371177304000203500ustar00rootroot00000000000000Hello IoT.js!!iotjs-1.0+715/test/resources/http_signature_key.key000066400000000000000000000007021371177304000224270ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv5B5QBJx+XGoK8xbY2Q9L5pJyv0Ddlzx pwWSz6q049b/+7YzVsFLt7S+O7soW7upfwTxFkCcpWWTKIoRac6vCYY14lTmWK/M1cntho8BiFoL cvDAx7dXgH2OfIsr6VgJMFl4DZebcN2fvhsZBo2lTyhJt8lSw8esTDHFZ8App6ilvVXJ4p6uKWJp 1bzJQxvwHuNa4itN6GKyMR5kqklDwTa359JXXZf5LO7kFwO7ULCrtliaCUEUvG4xTgZfctD4gKMb WScMzx2U4ksSFhlmGyxcED2FH+fUn98Qo5KFflu01RaHScodXUZo6VMV5oY466Yq7y7z2R4KdpL4 vC4v4wIDAQAB -----END PUBLIC KEY----- iotjs-1.0+715/test/resources/my_ca.crt000066400000000000000000000025121371177304000176100ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIDuzCCAqOgAwIBAgIJAMeGQlu8r9jlMA0GCSqGSIb3DQEBCwUAMHQxCzAJBgNV BAYTAkhVMRMwEQYDVQQIDApTb21lLVN0YXRlMQ8wDQYDVQQHDAZTemVnZWQxDjAM BgNVBAoMBU15IENBMREwDwYDVQQDDAhteWNhLm9yZzEcMBoGCSqGSIb3DQEJARYN bXljYUBteWNhLm9yZzAeFw0xODA2MjgxMDQzMThaFw0yODA2MjUxMDQzMThaMHQx CzAJBgNVBAYTAkhVMRMwEQYDVQQIDApTb21lLVN0YXRlMQ8wDQYDVQQHDAZTemVn ZWQxDjAMBgNVBAoMBU15IENBMREwDwYDVQQDDAhteWNhLm9yZzEcMBoGCSqGSIb3 DQEJARYNbXljYUBteWNhLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBALCPKzrZoSVHjswF0W/5pn0ElmAjO3GmYH1rHbTdSfQ9fXWiXWHREcGXeGXJ Vs/OIr6hxrghuPehYxERW2RhZESosOZgtifLC5hpg5guHzls0p8ix1gZ/olNBhzV /1qO5J7MSxx87DldDvoVTNyUzp/FEL5U45N4B8ECrY5+41BN1SPgAs5xc+LJLiag JjrsUxrpzngqsfpf15zcFsXcknB3VZKLQStkbmZB2RNWJm2dulSwr1tdXeZhBs1M seKh7MZ86ay/8/LJPedBUNUnIm/ZlinFYC5dxRpfA4RFL7Q91PZbAIRMphpXfE2x SSeOnkB2InXXwaPi+PlQnDzzSIMCAwEAAaNQME4wHQYDVR0OBBYEFNm9NQ9P2i35 oCIFHQmft53GXlCNMB8GA1UdIwQYMBaAFNm9NQ9P2i35oCIFHQmft53GXlCNMAwG A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAIurYWyw/AkMlNeW7PIu7zsh 6mknQ0RCI8h05CgJ6SlSlVQSB6Tu9BiLT0DNc0PTIQxHoqgVofATndLLn7a6G0Lc iy8mcYDbfAEcXiXFlo58gyWCa+/azJ/hslOVKvCs66BieHOiDhaBVzqWwUYaVMYA EocmusQmx44qrSsMfNPqq4b15b9sn0WximHtc76Czibnj35Nkhr/x2Cd07vnoU/2 5fpiu8PfrSAjOw6oaAINwP6pXskl1+wtJ9NpqvEJVl4aEUWpSJoGtIJGOtM0zbNF /IPITiGuLri8FzYqfvYBxRR2Wuq94Vcmwh8r2mysuPC1dHtjg5l1hm8vqiBW3p4= -----END CERTIFICATE----- iotjs-1.0+715/test/resources/my_ca.key000066400000000000000000000032171371177304000176130ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAsI8rOtmhJUeOzAXRb/mmfQSWYCM7caZgfWsdtN1J9D19daJd YdERwZd4ZclWz84ivqHGuCG496FjERFbZGFkRKiw5mC2J8sLmGmDmC4fOWzSnyLH WBn+iU0GHNX/Wo7knsxLHHzsOV0O+hVM3JTOn8UQvlTjk3gHwQKtjn7jUE3VI+AC znFz4skuJqAmOuxTGunOeCqx+l/XnNwWxdyScHdVkotBK2RuZkHZE1YmbZ26VLCv W11d5mEGzUyx4qHsxnzprL/z8sk950FQ1Scib9mWKcVgLl3FGl8DhEUvtD3U9lsA hEymGld8TbFJJ46eQHYiddfBo+L4+VCcPPNIgwIDAQABAoIBAGeShOyP8B07XgRH QXYrgEQEZeZdpKhlzmKkbJfF3HU/gRJ5vcf86iqjnYgwVRGwPeeQZU9s0OHLNZ80 jGVVUImKX8O1ZgXv8YxmEUE7hSudr+yUbVY8YXnPyk8uJg7MlkalV0aN7dE0yu1f g2g+jvtgkhLlH19J4VqTJJbbzqMzG+2m9htQqG2vM2spkYtSw3DbsmJS4zklkr/n g6VvIzLDzGq6KdIqE0LWvSiPm4pYTXQFk4j+J7UjY+ZmTXZIKedmk3a4vTpppiYu HAy1I8a5tZtgPYEOnRaZ2sPGuLcOgcBWa9iPx8JelRDcVB/51KcICsYZU/EOzoDc QHtqswECgYEA1ifEjpF4fTdAnXdrmj5ln3wIBjLd/YNAaOJW6ZWCFJ5Rcper7QYK 2hUG9TvkJ/oq3m4v8X0gdxnOASpHZ5k04JMS58M85ptc4st0wvOvX36qdU9juRz4 ClnCZDDndc1E7JMkqHl1uJHvDYWLFUYogkk042HIvkTwddNbp1tJL4ECgYEA0w7Q Dq6YIc+AHUisE0uVtli8kHZu/pQHv2XFZ3zRkwsYOLB5xwJU5uoXRZJcc6yF2EF+ /kulJDLTwKi2b9UO491Fl071VqlGW086+gPmSDao0RzTGbfhqc3dAtn6fGHp1Vgf xpsxYTWpoiiexljHfa3NkDIYmgZtElRRR4iUugMCgYEAtol9E5xRHEHdNJsWv4lR 64e3+zieWTjnzL6oID+MefCcMdWv+L8+vrZPkPY0uhKVObSn7umdo4b+PaYA6QAA vy79XUjf/xwMJ1AOPSGiqP35YzaBJMbZcVEizW2VzKZjila9V1D4E5NoNJlQfJip bKvjhbDSf8OZRoUaSWMY1YECgYApQqAR/rfnBDW7g9WAACrIdxiF9WFFi5LoK/En hhNCd8zIaFemPCJ08haSl0ZTpsqTuFonRIqIRRd4doMT4ccDbOKJ7fmwc285soeJ EPIX8/eUydnLEVOgaopmYE7DujCIcK3lmblRk7gR53cCt6BoRW4GXoTIt7DjAHDT VzQcGQKBgQDIsplosD3lXeRKA2agTozOROlUbJjYFlPLfztiXVPk3+QvGN1s4NIZ IzoJX/sufinHYzajRFK+IyAyusmnwHkwZz7WUmgJk0L6K+/T93nQhhwjSue6NMZK egpitIY58FY1J6Y67MR4+3h0/o4LCYQN5vOcrCAkczsNtAuVO0OnWA== -----END RSA PRIVATE KEY----- iotjs-1.0+715/test/resources/my_ca.srl000066400000000000000000000000211371177304000176110ustar00rootroot0000000000000094825A52EA8A27F1 iotjs-1.0+715/test/resources/my_crt.crt000066400000000000000000000030721371177304000200170ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIEazCCA1MCCQCUglpS6oon8TANBgkqhkiG9w0BAQsFADB0MQswCQYDVQQGEwJI VTETMBEGA1UECAwKU29tZS1TdGF0ZTEPMA0GA1UEBwwGU3plZ2VkMQ4wDAYDVQQK DAVNeSBDQTERMA8GA1UEAwwIbXljYS5vcmcxHDAaBgkqhkiG9w0BCQEWDW15Y2FA bXljYS5vcmcwHhcNMTgwNjI4MTA0NjA3WhcNMjgwNjI1MTA0NjA3WjB7MQswCQYD VQQGEwJIVTETMBEGA1UECAwKU29tZS1TdGF0ZTEPMA0GA1UEBwwGU3plZ2VkMRAw DgYDVQQKDAdUcnVzdGVkMRIwEAYDVQQDDAlsb2NhbGhvc3QxIDAeBgkqhkiG9w0B CQEWEXRydXN0ZWRAbG9jYWxob3N0MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC CgKCAgEApd/5D3T9EWTLcJLTk8ayjc+GdSZBiRNYo4JSACf4LSrTBOif4UN/3PZi 02wmPesPFyPY86cqJGi/7IVxaXX2stKLBRa+ZE7Pp7T9tIjkxx/Rw1GMEHLSjJM4 JMBUJ2Vb6a0jLPAvNqO9jiXeaw6XJVtvXJrE71zVOj0R1Ttq0b3VQ10oQgZVfaRy xjMFD2sTMFo7ADkGw+XUqvp0ZMleeOk2yKuflvQkr/BUHzncepBtsMdxGb8Xm58Z QbVodLlbCD+NAoRpTnVphVxSpGsYRfLNfEHWYA8CD+1J3nPTAYU9t7AxZYPsqcHW GHc2A6badnwLsg4jNbUGx4bOS2Jwtf5uVQxPLHobI4lMFAZXBBHHuySP3O9WTPB8 m/SHRFP2TBLARJX4DCpisaeZ2f0kshdUCZaxKCKoiiQ0Eo826iRJItiAOx+Uo3E4 VP9+qkphOjPW23ERw8EDY5Cm///Pp4q/vlGICTn3peoxDnYcy+FDPvbw+dakQPtK IxurQC80RqV3f+W6LhVx3uZQYN2FkfOhQaMbfdq+jB6dcrXbh1FUPwa00eaPdfXz Fq1xWpfzE6GrjThijC0HkGrUT6ThQVG0nrHDhzbKw+27FUDkhwnOrNtCJy1GgS9m TUD1CvoDfdRSvqP4N1zrxNK4PNnYuN8m/xcycn8i7aMroQFEGSECAwEAATANBgkq hkiG9w0BAQsFAAOCAQEAd5MuhS49EtJo/dYnLS6MdHQ9Afwc5dlE7375hx1++cDg rV2XD1RuMovZpwCi58RPTsD+lp9QB/60SkW/85Dvbh7Xmh/u5Cr6J0/drVQpBj7U ++9dVFPs0nHmxkYxC7ZYM+NX1cwbcfLYf9dpjA88tIcVatnFjVoGqaJpZzyd7vRv UESF9EG1rLAtla36absMwg/rGxH+Rl0If662lCiHHu7jN+lu2uBP8tQ4tWlIxybp wcEpJqpqN7WnMwFuuriUL3p8zcglsWwIqccKi3M/lYS2uLvHBhF/44W06RM0zwxg oFr+K2SlC17Xr+A29kL+OmtFdgrVIQAhVZX02v3IkA== -----END CERTIFICATE----- iotjs-1.0+715/test/resources/my_csr.csr000066400000000000000000000032741371177304000200210ustar00rootroot00000000000000-----BEGIN CERTIFICATE REQUEST----- MIIEwDCCAqgCAQAwezELMAkGA1UEBhMCSFUxEzARBgNVBAgMClNvbWUtU3RhdGUx DzANBgNVBAcMBlN6ZWdlZDEQMA4GA1UECgwHVHJ1c3RlZDESMBAGA1UEAwwJbG9j YWxob3N0MSAwHgYJKoZIhvcNAQkBFhF0cnVzdGVkQGxvY2FsaG9zdDCCAiIwDQYJ KoZIhvcNAQEBBQADggIPADCCAgoCggIBAKXf+Q90/RFky3CS05PGso3PhnUmQYkT WKOCUgAn+C0q0wTon+FDf9z2YtNsJj3rDxcj2POnKiRov+yFcWl19rLSiwUWvmRO z6e0/bSI5Mcf0cNRjBBy0oyTOCTAVCdlW+mtIyzwLzajvY4l3msOlyVbb1yaxO9c 1To9EdU7atG91UNdKEIGVX2kcsYzBQ9rEzBaOwA5BsPl1Kr6dGTJXnjpNsirn5b0 JK/wVB853HqQbbDHcRm/F5ufGUG1aHS5Wwg/jQKEaU51aYVcUqRrGEXyzXxB1mAP Ag/tSd5z0wGFPbewMWWD7KnB1hh3NgOm2nZ8C7IOIzW1BseGzkticLX+blUMTyx6 GyOJTBQGVwQRx7skj9zvVkzwfJv0h0RT9kwSwESV+AwqYrGnmdn9JLIXVAmWsSgi qIokNBKPNuokSSLYgDsflKNxOFT/fqpKYToz1ttxEcPBA2OQpv//z6eKv75RiAk5 96XqMQ52HMvhQz728PnWpED7SiMbq0AvNEald3/lui4Vcd7mUGDdhZHzoUGjG33a vowenXK124dRVD8GtNHmj3X18xatcVqX8xOhq404YowtB5Bq1E+k4UFRtJ6xw4c2 ysPtuxVA5IcJzqzbQictRoEvZk1A9Qr6A33UUr6j+Ddc68TSuDzZ2LjfJv8XMnJ/ Iu2jK6EBRBkhAgMBAAGgADANBgkqhkiG9w0BAQsFAAOCAgEAd88r+jJGHsPmBfhy ucNhCIK9VOh+kjlbfSnX0m6VJkNoqxJFx8mZ/fWlwUUW7Ff3WsmeDWEs/s5N6A3+ NRAwPsuBrFImN/CeCbq0u4SU4+KJObZjmJjWhbXBgzYZQrtG/LvwOUceesDzgSj1 qKfwSpafEYNeGtRWMcv02ypG7+h9Hbpqr2RpEe0Jgi3LAgW11wJzve/rLpDU3PKP DsZzx7GvkcWAuqxv3jTH68vJOEmHxUKNSybnvCGHCDcA/f5k0bROOO7RSJ1TQOKr dYLEMssil69gd/n2GpmXHmYjWx2LRlwuJp7Hm4GOjdmketu6bLotWH+R8lwBFuvH kDRGaBA2uHmFhtgokKult5zpCiIDw4FHfbC43dg63jGD3k6LrzrxbGbxZUb7tpFZ z9XJxdFPgzI6eOiiHD3SJikZoeox5AmUDCZOmsrF6Ex2iiTXxbIWfSqaImK8xZp4 fUx6fDKy24SU+rrGqX8oxABOootPwdT/lsCVB4b/IdtzAugPf1dRDIHYWteohlc8 4CVebKr0QyaQxH7fBRcTQmVNlJhzYfE6GcXa49G1AzXpEs6Eb3iPPRKRTNTssmZv ycHkTmWjoWLK1b1wEKK7jY17EXuIbxozIYCVoMXTEeUJtcB8lwt2gBDlASxfQYtB J8BmS9FN25iWTk5xW52UnpniwDk= -----END CERTIFICATE REQUEST----- iotjs-1.0+715/test/resources/my_key.key000066400000000000000000000062531371177304000200230ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIIJJwIBAAKCAgEApd/5D3T9EWTLcJLTk8ayjc+GdSZBiRNYo4JSACf4LSrTBOif 4UN/3PZi02wmPesPFyPY86cqJGi/7IVxaXX2stKLBRa+ZE7Pp7T9tIjkxx/Rw1GM EHLSjJM4JMBUJ2Vb6a0jLPAvNqO9jiXeaw6XJVtvXJrE71zVOj0R1Ttq0b3VQ10o QgZVfaRyxjMFD2sTMFo7ADkGw+XUqvp0ZMleeOk2yKuflvQkr/BUHzncepBtsMdx Gb8Xm58ZQbVodLlbCD+NAoRpTnVphVxSpGsYRfLNfEHWYA8CD+1J3nPTAYU9t7Ax ZYPsqcHWGHc2A6badnwLsg4jNbUGx4bOS2Jwtf5uVQxPLHobI4lMFAZXBBHHuySP 3O9WTPB8m/SHRFP2TBLARJX4DCpisaeZ2f0kshdUCZaxKCKoiiQ0Eo826iRJItiA Ox+Uo3E4VP9+qkphOjPW23ERw8EDY5Cm///Pp4q/vlGICTn3peoxDnYcy+FDPvbw +dakQPtKIxurQC80RqV3f+W6LhVx3uZQYN2FkfOhQaMbfdq+jB6dcrXbh1FUPwa0 0eaPdfXzFq1xWpfzE6GrjThijC0HkGrUT6ThQVG0nrHDhzbKw+27FUDkhwnOrNtC Jy1GgS9mTUD1CvoDfdRSvqP4N1zrxNK4PNnYuN8m/xcycn8i7aMroQFEGSECAwEA AQKCAgBU1Z3dx+l+MdzScGWBWMgNOyv7UluGLbzRs18Y8Vg+UX6nLgpG/Wyxp9mX Y+KTHFsVbKISy1YEVQaDgyQj2c8YWhH7wkwRpTUTAsAWy0SmiqGPkW9fIjqI5up5 8VuY4oAFnSU2YIjlGw1hXADLJCUtV/w2knlSKlprdLxgIAlbyAkAcO6cBf1HSwng UEuwPQUNX7h5PrE1E6CW6Y0J1utYT35TV2NBow/4Y6PCbKdUj/VpyjcQAemjD9Wt A4iu2fWy3D3UIcBx/h6/tB4YNSWu8KUjfdCURFi7qJJ1ESvDxU9xWM2Kq9QoZhiH XsDjUTy+CGc643wihbk35rwvVeNqfN2GfkrrdyTzqIszJAqKtImoXv8BuEf+kgeX 0s9Wtl8BF4Hv6jAZ28NI1DwXXjEFkuqG6Z1yn5UTAxcmKqAudZFVoI5dgeGu8c6x LVkudR7QOkeSuHTrn4ILYiWMsuP8No/qmnQBCHbfJT4xp2dBHdZ0vDml7LFZjzg1 If1ZGStOBB7uZqDXyx4wdYdMdV05dvUelWwJqI0KLWF8doX6fr+Huh1Q3owYoOQ5 MZOoXbHMegu5fOrkDFfaYeATTnCeE1RjoYjT9zf4rYjX3IOryj66b0DadXpYdNhk 5vSAA+NRj3fLGFScdCFxwJjwPbw1Xsn0uSwRHHEQnF9H5hmsoQKCAQEA5poLkJ1s 1ZeEWVr5CDU0js8QsEbeRGpXsm+Aj9X9gf4+D3HQ573lnXO8wiB+PoikETWp45Jf yq1XK2dcbygcxrSo6Zr+GtzE6grCztn8jE4omkqduJhViAr4hdg59R4UdNG1Qpgg Z9cFBYwnI/IWMJJBTiqKIVwD3RKQM75WKDT/ccDtUp2MxxNjUKAsVHpmOHW2ZC4T A2vwbqp+egQ5SfSUBcGkD034PjG2uOJGmHXcKnnG4Dm+9SeutvTF9JZwMJmg3WlG 5AdVUnl4qN2g4t3TYasV4Y8i00EJPcQW5v4UV9sq4dAQ0GXfu/r/TXwMKkQp/cN1 95I+xXsBjKQDdQKCAQEAuCTqVZJMZ5uovPzyPmnMOBqdtac5Hd7/eglN945sAK7n ssg3X1hRsHCf8Dx1X95lxCDVn97ac9C2uIEeiLy/+JDFQcOxcgj1vDeF6IaGzaFh Dc9qIDo4b0bhhD1kMxtowOAkI4YR/+iSIuGOJXq7wu71a6+dIm4meb+4d3L+O5Jq sOsOBLClL7Ymv1iZ3fol0XPQsuSv1eGoDqDdiNNXOBJHgKy0zMEXs4hpjL2vCGDN m8MbtqpMg4jCuesy/zh/b+CCkrX0AdW/fkw/euZ/ZTMEageqH5RfitX9CGOw2CuS +78XmWeFqbr2YVbAZFo09I8Ytv40yO1ZyVQkyKSlfQKCAQA1ooCsGyF0MHCVA+bG NPHLgXfFOEZ8LSvGkc6aJdB3yrWOjA9lxzI/w+qUUFBspQVcB1pDVwk2r8iFjN3f 8Ll4sg5Tfzw47T5TnTsgN21ZCNjCwjYa+Dt0j/Cr2NXqIBvr69a37YAkBsvhNW7p GmZ015+e2aAVEDzJz4aAsnWBlooPYCsSuxhCOU0xNH/7Chj6as6IUHsVoaZjZv5R zOeyPtOq3xYUhTMG7DMun1qCHW+e5YIPJv82MAuf/CCKue7QLvtOZC0b3mTG8P/S bvH7slJ29f753nvgHNFUb2ZQRapfoNdBfE5c2kUGiOOWlxKRRhdqMWsfsQEul2SN 3Jv9AoIBAASuW46lU2/m0xlKzNWtVtWuR4gQojESNChkCClc43349EblNBMmaZ00 n7w5rTosqyWbOBMCVUdQbPSvw5jyQ2cMNxd+5AnkFGsedjb9BHxBt/fj5+y9ziV2 BdGYxe1OqxEMIZ8Nj3OT8/MTDMwDHLbN4EtGgZYYer3pk8TllXTqOfAZaZfQ7cIS vVVr6S1taHy0lv+VNKsZO25zxG3wAW2ZeVvaCBaUagfUVeqP/90UqOVmxlOUbLGD Tn/vbLJ0Ozka2fbkzTkmt+F8CrkTFvX5oAkZ/MckvHEJE4+dCSfVo7zmlLD/orQ3 3n+G9wkWCfaVlKlCORFKh1fI3c6D8PkCggEAI/zEfC6+CndqrmehoCGgHZMP7B+a rytCeG3Qyoqjta0sKGC8/LUe85PSWDR9xHrrWgEriRF9gHvYxF8YCBXhfInIHDd+ pdcsWEaoUWlvBqhbKaPhVF/0difpjogWH388sdVXT6PefHEO5maYii9EaPjWckKf 314Eh0KW/oUiSo5rwAgdnu1J84qBOxXqMI2eDZaKLphueytHjt7QRnZW91zeYwrP 3E7MbkKVJPaViIm3MvXUUsL8Gpqji9MY0wHjZAq1PXtZ5WP+K3wHUOte6OGkBcSQ 7oUxhOoMlN0VC4FGtSHu1LLTvmWeYrHk9J6mpfNAj1/TfA/VvVKpNQVlaw== -----END RSA PRIVATE KEY----- iotjs-1.0+715/test/resources/process/000077500000000000000000000000001371177304000174645ustar00rootroot00000000000000iotjs-1.0+715/test/resources/process/package.json000066400000000000000000000012311371177304000217470ustar00rootroot00000000000000{ "version": "2.9.1", "name": "npm", "description": "a package manager for JavaScript", "config": { "publishtest": false }, "homepage": "https://docs.npmjs.com/", "repository": { "type": "git", "url": "https://github.com/npm/npm" }, "bugs": { "url": "http://github.com/npm/npm/issues" }, "directories": { "doc": "./doc", "man": "./man", "lib": "./lib", "bin": "./bin" }, "main": "./lib/npm.js", "bin": "./bin/npm-cli.js", "scripts": { "test-legacy": "node ./test/run.js", "test": "tap --timeout 240 test/tap/*.js", "tap": "tap --timeout 240 test/tap/*.js" }, "license": "Artistic-2.0" } iotjs-1.0+715/test/resources/promise_chain_calls/000077500000000000000000000000001371177304000220045ustar00rootroot00000000000000iotjs-1.0+715/test/resources/promise_chain_calls/1.txt000066400000000000000000000000211371177304000226760ustar00rootroot00000000000000Content of 1.txt iotjs-1.0+715/test/resources/promise_chain_calls/2.txt000066400000000000000000000000211371177304000226770ustar00rootroot00000000000000Content of 2.txt iotjs-1.0+715/test/resources/promise_chain_calls/3.txt000066400000000000000000000000211371177304000227000ustar00rootroot00000000000000Content of 3.txt iotjs-1.0+715/test/resources/promise_chain_calls/4.txt000066400000000000000000000000211371177304000227010ustar00rootroot00000000000000Content of 4.txt iotjs-1.0+715/test/resources/readdir/000077500000000000000000000000001371177304000174205ustar00rootroot00000000000000iotjs-1.0+715/test/resources/readdir/DO_NOT_MODIFY_THIS_FOLDER000066400000000000000000000000001371177304000233040ustar00rootroot00000000000000iotjs-1.0+715/test/resources/readdir/This_is_a_directory/000077500000000000000000000000001371177304000234065ustar00rootroot00000000000000iotjs-1.0+715/test/resources/readdir/This_is_a_directory/.gitkeep000066400000000000000000000000001371177304000250250ustar00rootroot00000000000000iotjs-1.0+715/test/resources/readdir/This_is_another_directory/000077500000000000000000000000001371177304000246265ustar00rootroot00000000000000iotjs-1.0+715/test/resources/readdir/This_is_another_directory/.gitkeep000066400000000000000000000000001371177304000262450ustar00rootroot00000000000000iotjs-1.0+715/test/resources/readdir/regular.txt000066400000000000000000000000161371177304000216170ustar00rootroot00000000000000Hello IoT.js!!iotjs-1.0+715/test/resources/rename.txt000066400000000000000000000000161371177304000200130ustar00rootroot00000000000000Hello IoT.js!!iotjs-1.0+715/test/resources/test.json000066400000000000000000000003121371177304000176540ustar00rootroot00000000000000{ "name": "IoT.js", "description": "Platform for Internet of Things with JavaScript", "author": "Samsung Electronics Co., Ltd.", "license": "Apache-2.0", "number": 123, "array": [1,2,3,4] } iotjs-1.0+715/test/resources/test1.txt000066400000000000000000000000271371177304000176060ustar00rootroot00000000000000TEST File Read & Write iotjs-1.0+715/test/resources/test2.txt000066400000000000000000000000001371177304000175760ustar00rootroot00000000000000iotjs-1.0+715/test/resources/test_console_stdout.txt000066400000000000000000000000601371177304000226460ustar00rootroot00000000000000Hello IoT.js!! 1 2 3 13 1,2,3 1 2 3 a 1 b 2 c 3 iotjs-1.0+715/test/resources/tobeornottobe.txt000066400000000000000000000030141371177304000214320ustar00rootroot00000000000000To be, or not to be, that is the Question: Whether ’tis Nobler in the mind to Å¿uffer The Slings and Arrows of outragious Fortune, Or to take Armes against a Sea of troubles, And by opposing end them: to dye, to Å¿leepe No more; and by a sleep, to say we end The Heart-ake, and the thouÅ¿and Naturall Å¿hockes That Flesh is there too? "Tis a consummation Deuoutly to be wiÅ¿h'd. To dye to sleepe, To sleep, perchance to Dream; I, there's the rub, For in that sleep of death, what dreams may come, When we haue Å¿hufflel’d off this mortall coile, MuÅ¿t giue us pause. There's the respect That makes Calamity of long life: For who would beare the Whips and Scornes of time, The Oppreſſors wrong, the poore mans Contumely, The pangs of diÅ¿priz’d Loue, the Lawes delay, The inÅ¿olence of Office, and the Spurnes That patient merit of the vnworthy takes, When he himÅ¿elfe might his Quietus make With a bare Bodkin? Who would theÅ¿e Fardles beare To grunt and Å¿weat vnder a weary life, But that the dread of Å¿omething after death, The vndiÅ¿couered Countrey, from whoÅ¿e Borne No Traueller returnes, Puzels the will, And makes vs rather beare those illes we haue, Then flye to others that we know not of. Thus ConÅ¿cience does make Cowards of vs all, And thus the Natiue hew of Resolution Is Å¿icklied o’re, with the pale caÅ¿t of Thought, And enterprizes of great pith and moment, With this regard their Currants turne away, And looÅ¿e the name of Action. Soft you now, The faire Ophelia? Nimph, in thy Orizons Be all my Å¿innes remembred.iotjs-1.0+715/test/run_fail/000077500000000000000000000000001371177304000155735ustar00rootroot00000000000000iotjs-1.0+715/test/run_fail/test-issue-1349.js000066400000000000000000000014031371177304000206320ustar00rootroot00000000000000/* 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 dns = require( 'dns' ); var assert = require( 'assert' ); assert.throws(function ( ) { dns.lookup ('localhost', require) } ); iotjs-1.0+715/test/run_fail/test-issue-1360.js000066400000000000000000000013421371177304000206250ustar00rootroot00000000000000/* 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. */ process.on('exit', function() {}); setTimeout(function() { Array.prototype.slice += 'B' }, 500); iotjs-1.0+715/test/run_fail/test-issue-1570.js000066400000000000000000000012701371177304000206300ustar00rootroot00000000000000/* Copyright 2018-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. */ Object.freeze(process); throw new Error("Some error"); iotjs-1.0+715/test/run_fail/test-issue-1915.js000066400000000000000000000012561371177304000206370ustar00rootroot00000000000000/* Copyright 2019-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 uart = require('uart'); uart.open(this); iotjs-1.0+715/test/run_fail/test-issue-1917.js000066400000000000000000000013001371177304000206270ustar00rootroot00000000000000/* Copyright 2019-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') setInterval(fs.fstatSync(1).isFile, 1); iotjs-1.0+715/test/run_fail/test_assert_equal.js000066400000000000000000000012671371177304000216660ustar00rootroot00000000000000/* 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 assert = require('assert'); assert.equal(1, 2); iotjs-1.0+715/test/run_fail/test_assert_fail.js000066400000000000000000000012621371177304000214650ustar00rootroot00000000000000/* 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 assert = require('assert'); assert.fail(); iotjs-1.0+715/test/run_fail/test_assert_notequal.js000066400000000000000000000012721371177304000224030ustar00rootroot00000000000000/* 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 assert = require('assert'); assert.notEqual(1, 1); iotjs-1.0+715/test/run_fail/test_events_emit_error.js000066400000000000000000000013461371177304000227270ustar00rootroot00000000000000/* 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 EventEmitter = require('events').EventEmitter; var ee = new EventEmitter(); ee.emit('error'); iotjs-1.0+715/test/run_fail/test_fs_callbacks_called.js000066400000000000000000000023721371177304000231070ustar00rootroot00000000000000/* 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 assert = require('assert') var invocation_count = 0; var callback_count = 13; var callback = function () { if (++invocation_count == callback_count) { assert.fail("pass") // All the callbacks were called } } var fs = require('fs'); fs.open("", "r", callback); fs.close(0, callback); fs.read(0, Buffer(1), 0, 0, 0, callback); fs.write(0, Buffer(1), 0, 0, 0, callback); fs.readFile("", callback); fs.writeFile("", Buffer(1), callback); fs.rename("", "", callback); fs.stat("", callback); fs.exists("", callback); fs.unlink("", callback); fs.mkdir("", callback); fs.rmdir("", callback); fs.readdir("", callback); iotjs-1.0+715/test/run_fail/test_iotjs_runtime_error.js000066400000000000000000000012501371177304000232720ustar00rootroot00000000000000/* 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 a = null; a.no_exist_function(); iotjs-1.0+715/test/run_fail/test_iotjs_syntax_error.js000066400000000000000000000012221371177304000231340ustar00rootroot00000000000000/* 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. */ for syntax error iotjs-1.0+715/test/run_fail/test_module_require_invalid_file.js000066400000000000000000000012411371177304000247140ustar00rootroot00000000000000/* 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. */ require('no exist file path'); iotjs-1.0+715/test/run_fail/test_module_require_path_below_root.js000066400000000000000000000030461371177304000254630ustar00rootroot00000000000000/* 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. */ require('../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../../../../../../../../../../../../../' + '../../../../../../../../../../../../file path below root'); iotjs-1.0+715/test/run_fail/test_process_exitcode_arg.js000066400000000000000000000014071371177304000233650ustar00rootroot00000000000000/* 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 assert = require('assert'); process.on('exit', function(code) { assert.equal(1, code); assert.fail(); }); process.exit(1); iotjs-1.0+715/test/run_fail/test_process_exitcode_var.js000066400000000000000000000014401371177304000234010ustar00rootroot00000000000000/* 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 assert = require('assert'); process.on('exit', function(code) { assert.equal(2, code); assert.fail(); }); process.exitCode = 2; process.exit(); iotjs-1.0+715/test/run_fail/test_process_explicit_exit.js000066400000000000000000000013511371177304000236000ustar00rootroot00000000000000/* 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 assert = require('assert'); process.on('exit', function() { assert.fail(); }); process.exit(); iotjs-1.0+715/test/run_fail/test_process_implicit_exit.js000066400000000000000000000013301371177304000235660ustar00rootroot00000000000000/* 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 assert = require('assert'); process.on('exit', function() { assert.fail(); }); iotjs-1.0+715/test/run_fail/test_timers_issue_1353.js000066400000000000000000000012601371177304000223550ustar00rootroot00000000000000/* 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. */ setTimeout(function() { throw "error" }, 100); iotjs-1.0+715/test/run_pass/000077500000000000000000000000001371177304000156265ustar00rootroot00000000000000iotjs-1.0+715/test/run_pass/issue/000077500000000000000000000000001371177304000167565ustar00rootroot00000000000000iotjs-1.0+715/test/run_pass/issue/issue-1046.js000066400000000000000000000013661371177304000210420ustar00rootroot00000000000000/* 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 Buffer = require('buffer'); var assert = require('assert'); assert.equal(Buffer("").readUInt16LE(10, true), 0); iotjs-1.0+715/test/run_pass/issue/issue-1077.js000066400000000000000000000014561371177304000210460ustar00rootroot00000000000000/* 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'); try { var m = require('issue-1077'); } catch (e) { assert(e.name === 'Error'); assert(e.message == 'Module not found: issue-1077'); } iotjs-1.0+715/test/run_pass/issue/issue-1101.js000066400000000000000000000021731371177304000210270ustar00rootroot00000000000000/* 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 uart = require('uart'); var res = uart.open({ device: '/dev/ttyS1', baudRate: 115200, dataBits: 8 }, function(err) { if (err) { console.error(err); } else { console.log('opened'); res.close(function(err) { if (err) { console.error(err); } else { console.log('closed'); } }); var c = 0; var p = function() { c++; console.log('this should still run'); if (c < 10) { setTimeout(p, 250); } }; p(); } }); iotjs-1.0+715/test/run_pass/issue/issue-1165.js000066400000000000000000000014201371177304000210330ustar00rootroot00000000000000/* 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 s1 = Buffer('737263', 'hex').toString(); var s2 = new Buffer('737263', 'hex').toString() assert(s1 === s2); iotjs-1.0+715/test/run_pass/issue/issue-133.js000066400000000000000000000012471371177304000207540ustar00rootroot00000000000000/* 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. */ // FIX: issue #133. console.log(""); iotjs-1.0+715/test/run_pass/issue/issue-1348.js000066400000000000000000000013221371177304000210370ustar00rootroot00000000000000/* 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. */ process.on('uncaughtException', function(err) { } ); process.exit('callback'); iotjs-1.0+715/test/run_pass/issue/issue-1350.js000066400000000000000000000013001371177304000210240ustar00rootroot00000000000000/* 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. */ process.on('exit', function() { process.exit("callback"); } ); iotjs-1.0+715/test/run_pass/issue/issue-137.js000066400000000000000000000022571371177304000207620ustar00rootroot00000000000000/* 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. */ // FIX: issue #137. console.log('hello world'); console.log(1); console.log(9 + 10); console.log(null); console.log(true); console.log(false); console.log(undefined); console.log(0.09); console.log(NaN); console.log(function () {}); console.log(function f() { return 0; }); console.log({}); console.log({a:1, b:2}); console.log([]); console.log([1,2,3]); console.log("%s=%d", "1+10", 1 + 10); console.log("%s+%s=%d", 2, 10, 2 + 10); console.log("%d+%d=%d", 3, 10, 3 + 10); console.log("%s+%s=%s", 4, 10, 4 + 10); console.log("%d+%d=%d", "5", "10", 5 + 10); iotjs-1.0+715/test/run_pass/issue/issue-1463.js000066400000000000000000000017101371177304000210360ustar00rootroot00000000000000/* Copyright 2018-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'); function readfile(fileName) { return new Promise(function(resolve, reject) { throw function() {}(), Buffer; }); }; try { readfile(readfile).then(function(value) { loadfi([], 0); }).prototype(function(e) {}); assert(false); } catch (ex) { assert(ex instanceof TypeError); } iotjs-1.0+715/test/run_pass/issue/issue-1485.js000066400000000000000000000012271371177304000210450ustar00rootroot00000000000000/* Copyright 2018-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. */ process.emitExit = 1; iotjs-1.0+715/test/run_pass/issue/issue-1507.js000066400000000000000000000012701371177304000210360ustar00rootroot00000000000000/* Copyright 2018-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 x = require("console"); process.exitCode = x.id_0; iotjs-1.0+715/test/run_pass/issue/issue-1557.js000066400000000000000000000015451371177304000210500ustar00rootroot00000000000000/* Copyright 2018-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 fz_globalObject = Function("return this")( ) var prop_names = Object.getOwnPropertyNames(fz_globalObject) console.log(prop_names) for (var i = 0; i < 10; i++) { var prop_name = prop_names[i] console.log(prop_name) } iotjs-1.0+715/test/run_pass/issue/issue-1897.js000066400000000000000000000020151371177304000210500ustar00rootroot00000000000000/* Copyright 2019-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 websocket = require('websocket'); var client = new websocket.Websocket(); var client2 = new websocket.Websocket(); var wss = new websocket.Server({port: 8081}, function () {}); client.connect('ws://localhost', 8081, '/', function() { client2.connect('ws://localhost', 8081, '/'); client2.on('open', function() { wss.broadcast('a'); // prevent blocking wss.close(); }); }); iotjs-1.0+715/test/run_pass/issue/issue-1904.js000066400000000000000000000015651371177304000210460ustar00rootroot00000000000000/* Copyright 2019-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 module = require('module'); var dgram = require('dgram'); var assert = require('assert'); try { dgram.createSocket('udp4')._handle.send(this, 0, '', new module()); assert(false); } catch (e) { assert(e instanceof TypeError); } iotjs-1.0+715/test/run_pass/issue/issue-198.js000066400000000000000000000013741371177304000207700ustar00rootroot00000000000000/* 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 assert = require('assert'); assert.throws( function() { process.binding("builtin not exist"); } , Error ); iotjs-1.0+715/test/run_pass/issue/issue-223.js000066400000000000000000000014261371177304000207530ustar00rootroot00000000000000/* 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 assert = require('assert'); var net = require("net"); assert.throws( function() { net.Server.prototype._createTCP(375); }, Error ); iotjs-1.0+715/test/run_pass/issue/issue-266.js000066400000000000000000000022041371177304000207550ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var server = net.createServer(); var port = 30266; server.listen(port); server.on('connection', function(socket) { socket.on('data', function(data) { server.close() }); socket.on('finish', function() { socket.destroy(); socket.destroy(); socket.destroy(); }); }); var socket = new net.Socket(); socket.connect(port, "127.0.0.1"); socket.end('test'); process.on('exit', function() { assert.equal(server._socketCount, 0); }); iotjs-1.0+715/test/run_pass/issue/issue-323.js000066400000000000000000000016071371177304000207550ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var fileName = ""; assert.throws( function() { var stats1 = fs.statSync(fileName); }, Error ); assert.throws( function() { var open1 = fs.openSync(fileName, 'r'); }, Error ); iotjs-1.0+715/test/run_pass/issue/issue-816.js000066400000000000000000000016701371177304000207640ustar00rootroot00000000000000/* 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 Buffer = require('buffer'); var assert = require('assert'); assert.throws(function () { var buf = new Buffer("ABCDEF"); var o = { _builtin: { compare: function () { buf._builtin.compare.call(this, arguments); } }, compare: buf.compare }; o.compare(buf); }, Error); iotjs-1.0+715/test/run_pass/require1/000077500000000000000000000000001371177304000173635ustar00rootroot00000000000000iotjs-1.0+715/test/run_pass/require1/module_cache.js000066400000000000000000000012451371177304000223330ustar00rootroot00000000000000/* 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. */ /** @NOTEST */ exports.i = -100; iotjs-1.0+715/test/run_pass/require1/require_add.js000066400000000000000000000013041371177304000222030ustar00rootroot00000000000000/* 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. */ /* @NOTEST */ exports.add = function(a, b) { return a + b; }; iotjs-1.0+715/test/run_pass/require1/test_index/000077500000000000000000000000001371177304000215315ustar00rootroot00000000000000iotjs-1.0+715/test/run_pass/require1/test_index/add2.js000066400000000000000000000013041371177304000226770ustar00rootroot00000000000000/* 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. */ /* @NOTEST */ exports.add2 = function(a, b) { return a + b; } iotjs-1.0+715/test/run_pass/require1/test_index/index.js000066400000000000000000000014261371177304000232010ustar00rootroot00000000000000/* 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. */ /* @NOTEST */ exports.add = function(a, b) { return a + b; }; var x = require("lib/multi.js"); exports.multi = x.multi; exports.add2 = x.add2; iotjs-1.0+715/test/run_pass/require1/test_index/lib/000077500000000000000000000000001371177304000222775ustar00rootroot00000000000000iotjs-1.0+715/test/run_pass/require1/test_index/lib/multi.js000066400000000000000000000013571371177304000237750ustar00rootroot00000000000000/* 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. */ /* @NOTEST */ exports.multi = function(a, b) { return a * b; }; exports.add2 = require('../add2').add2; iotjs-1.0+715/test/run_pass/require1/test_index/package.json000066400000000000000000000000331371177304000240130ustar00rootroot00000000000000{ "main": "index_test" } iotjs-1.0+715/test/run_pass/require1/test_index2/000077500000000000000000000000001371177304000216135ustar00rootroot00000000000000iotjs-1.0+715/test/run_pass/require1/test_index2/add2.js000066400000000000000000000012631371177304000227650ustar00rootroot00000000000000/* 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. */ exports.add2 = function(a, b) { return a + b; } iotjs-1.0+715/test/run_pass/require1/test_index2/index_test.js000066400000000000000000000014061371177304000243200ustar00rootroot00000000000000/* 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. */ exports.add = function(a, b) { return a + b; }; var x = require("lib/multi.js"); exports.multi = x.multi; exports.add2 = x.add2; iotjs-1.0+715/test/run_pass/require1/test_index2/lib/000077500000000000000000000000001371177304000223615ustar00rootroot00000000000000iotjs-1.0+715/test/run_pass/require1/test_index2/lib/multi.js000066400000000000000000000013361371177304000240540ustar00rootroot00000000000000/* 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. */ exports.multi = function(a, b) { return a * b; }; exports.add2 = require('../add2').add2; iotjs-1.0+715/test/run_pass/require1/test_index2/package.json000066400000000000000000000000331371177304000240750ustar00rootroot00000000000000{ "main": "index_test" } iotjs-1.0+715/test/run_pass/require1/test_pkg/000077500000000000000000000000001371177304000212035ustar00rootroot00000000000000iotjs-1.0+715/test/run_pass/require1/test_pkg/add2.js000066400000000000000000000013041371177304000223510ustar00rootroot00000000000000/* 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. */ /* @NOTEST */ exports.add2 = function(a, b) { return a + b; } iotjs-1.0+715/test/run_pass/require1/test_pkg/lib/000077500000000000000000000000001371177304000217515ustar00rootroot00000000000000iotjs-1.0+715/test/run_pass/require1/test_pkg/lib/multi.js000066400000000000000000000013571371177304000234470ustar00rootroot00000000000000/* 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. */ /* @NOTEST */ exports.multi = function(a, b) { return a * b; }; exports.add2 = require('../add2').add2; iotjs-1.0+715/test/run_pass/require1/test_pkg/main.js000066400000000000000000000014261371177304000224700ustar00rootroot00000000000000/* 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. */ /* @NOTEST */ exports.add = function(a, b) { return a + b; }; var x = require("lib/multi.js"); exports.multi = x.multi; exports.add2 = x.add2; iotjs-1.0+715/test/run_pass/require1/test_pkg/package.json000066400000000000000000000000301371177304000234620ustar00rootroot00000000000000{ "main": "main.js" } iotjs-1.0+715/test/run_pass/test_adc.js000066400000000000000000000050201371177304000177470ustar00rootroot00000000000000/* 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 adc = require('adc'); var assert = require('assert'); var configuration = {}; if (process.platform === 'linux') { configuration.device = '/sys/devices/12d10000.adc/iio:device0/in_voltage0_raw'; } else if (process.platform === 'nuttx') { configuration.pin = require('stm32f4dis').pin.ADC1_3; } else if (process.platform === 'tizenrt') { configuration.pin = 0; } else { assert.assert(false, "Unsupported platform: " + process.platform); } // start async test asyncTest(); function asyncTest() { var adc0 = adc.open(configuration, function(err) { console.log('ADC initialized'); if (err) { assert.assert(false, "Failed to open device."); } var loopCnt = 5; console.log('test1 start(read async test)'); var test1Loop = setInterval(function() { if (--loopCnt < 0) { console.log('test1 complete'); clearInterval(test1Loop); adc0.close(function (err) { assert.equal(err, null); // start sync test syncTest(); }); } else { adc0.read(function(err, value) { if (err) { assert.assert(false, "Failed to read device."); } console.log(value); }); } }, 1000); }); } function syncTest() { var adc0 = adc.openSync(configuration); console.log('ADC initialized'); var loopCnt = 5, value = -1; console.log('test2 start(read sync test)'); var test2Loop = setInterval(function() { if (--loopCnt < 0) { console.log('test2 complete'); clearInterval(test2Loop); adc0.closeSync(); } else { value = adc0.readSync(); if (value < 0) { assert.assert(false, "Failed to read device."); } else { console.log(value); } } }, 1000); } // error test assert.throws(function() { var adc = adc.open(configuration); }, TypeError, 'Calling adc.open without a callback function.'); iotjs-1.0+715/test/run_pass/test_assert.js000066400000000000000000000052221371177304000205250ustar00rootroot00000000000000/* 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 assert = require('assert'); assert.assert(1 == 1); assert.equal(1, 1); assert.notEqual(1, 2); assert.strictEqual(0, 0); assert.throws(function() { assert.strictEqual(1, 0); }, assert.AssertionError); assert.throws(function() { assert.notStrictEqual(true, true); }, assert.AssertionError); assert.throws(function() { assert.notStrictEqual(true, true); }, assert.AssertionError, "something"); assert.throws(function() { assert.throws(function() {}); }, assert.AssertionError); assert.throws(function() { assert.throws(function() { assert.strictEqual(1, 0); }, TypeError); }, assert.AssertionError); assert.doesNotThrow(function() { assert.strictEqual(1, 1); }, "something"); assert.throws(function() { assert.strictEqual(1, 0); }, assert.AssertionError, assert.AssertionError.name="something"); assert.equal(0, false); assert.notStrictEqual(0, false); assert.throws( function() { assert.equal(1, 2); }, assert.AssertionError ); assert.throws( function() { assert.assert(1 == 2); }, assert.AssertionError ); assert.doesNotThrow( function() { assert.assert(1 == 1); } ); assert.throws( function() { assert.doesNotThrow( function() { assert.assert(1 == 2); } ); }, assert.AssertionError ); try { assert.assert(false, 'assert test'); } catch (e) { assert.equal(e.name, 'AssertionError'); assert.equal(e.actual, false); assert.equal(e.expected, true); assert.equal(e.operator, '=='); assert.equal(e.message, 'assert test'); } try { assert.equal(1, 2, 'assert.equal test'); } catch (e) { assert.equal(e.name, 'AssertionError'); assert.equal(e.actual, 1); assert.equal(e.expected, 2); assert.equal(e.operator, '=='); assert.equal(e.message, 'assert.equal test'); } try { assert.fail('actual', 'expected', 'message', 'operator'); } catch (e) { assert.equal(e.name, 'AssertionError'); assert.equal(e.actual, 'actual'); assert.equal(e.expected, 'expected'); assert.equal(e.operator, 'operator'); assert.equal(e.message, 'message'); } iotjs-1.0+715/test/run_pass/test_ble_advertisement.js000066400000000000000000000023401371177304000227160ustar00rootroot00000000000000/* 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 ble = require('ble'); ble.on('stateChange', function(state){ console.log('onStateChange: ' + state); if (state == 'poweredOn') { ble.startAdvertising('iotjs', ['180F'], function(err) { if (err) console.log(err); else { setTimeout(function() { ble.stopAdvertising(function(err) { if (err) console.log(err); else console.log('stop advertising.'); }); }, 5000); } }); } else { ble.stopAdvertising(function(err) { if (err) console.log(err); else console.log('stop advertising.'); }); } }); iotjs-1.0+715/test/run_pass/test_ble_setservices.js000066400000000000000000000072501371177304000224100ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var ble = require('ble'); var BlenoPrimaryService = ble.PrimaryService; var BlenoCharacteristic = ble.Characteristic; var util = require('util'); var EchoCharacteristic = function() { BlenoCharacteristic.call(this, { uuid: 'ec0e', properties: ['read', 'write', 'notify'], value: null }); this._value = new Buffer(0); this._updateValueCallback = null; }; util.inherits(EchoCharacteristic, BlenoCharacteristic); EchoCharacteristic.prototype.onReadRequest = function(offset, callback) { console.log('EchoCharacteristic - onReadRequest: value = ' + this._value.toString('hex')); callback(this.RESULT_SUCCESS, this._value); }; EchoCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) { this._value = data; console.log('EchoCharacteristic - onWriteRequest: value = ' + this._value.toString('hex')); if (this._updateValueCallback) { console.log('EchoCharacteristic - onWriteRequest: notifying'); this._updateValueCallback(this._value); } callback(this.RESULT_SUCCESS); }; EchoCharacteristic.prototype.onSubscribe = function(maxValueSize, updateValueCallback) { console.log('EchoCharacteristic - onSubscribe'); this._updateValueCallback = updateValueCallback; }; EchoCharacteristic.prototype.onUnsubscribe = function() { console.log('EchoCharacteristic - onUnsubscribe'); this._updateValueCallback = null; }; console.log('ble - echo'); ble.on('stateChange', function(state) { console.log('on -> stateChange: ' + state); if (state === 'poweredOn') { ble.startAdvertising('iotjs_echo', ['ec00']); } else { ble.stopAdvertising(); } }); ble.on('advertisingStart', function(error) { console.log('on -> advertisingStart: ' + (error ? 'error ' + error : 'success')); if (!error) { ble.setServices([ new BlenoPrimaryService({ uuid: 'ec00', characteristics: [ new EchoCharacteristic() ] }) ]); } }); iotjs-1.0+715/test/run_pass/test_ble_setservices_central.js000066400000000000000000000105611371177304000241170ustar00rootroot00000000000000/* 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. */ /* Copyright (C) 2015 Sandeep Mistry sandeep.mistry@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. */ var noble = require('../..'); var echoServiceUuid = 'ec00'; var echoCharacteristicUuid = 'ec0e'; noble.on('stateChange', function(state) { if (state === 'poweredOn') { // // Once the BLE radio has been powered on, it is possible // to begin scanning for services. Pass an empty array to // scan for all services (uses more time and power). // console.log('scanning...'); noble.startScanning([echoServiceUuid], false); } else { noble.stopScanning(); } }) var echoService = null; var echoCharacteristic = null; noble.on('discover', function(peripheral) { // we found a peripheral, stop scanning noble.stopScanning(); // // The advertisment data contains a name, power level (if available), // certain advertised service uuids, as well as manufacturer data, // which could be formatted as an iBeacon. // console.log('found peripheral:', peripheral.advertisement); // // Once the peripheral has been discovered, then connect to it. // It can also be constructed if the uuid is already known. /// peripheral.connect(function(err) { // // Once the peripheral has been connected, then discover the // services and characteristics of interest. // peripheral.discoverServices([echoServiceUuid], function(err, services) { services.forEach(function(service) { // // This must be the service we were looking for. // console.log('found service:', service.uuid); // // So, discover its characteristics. // service.discoverCharacteristics([], function(err, characteristics) { characteristics.forEach(function(characteristic) { // // Loop through each characteristic and match them to the // UUIDs that we know about. // console.log('found characteristic:', characteristic.uuid); if (echoCharacteristicUuid == characteristic.uuid) { echoCharacteristic = characteristic; } }) // // Check to see if we found all of our characteristics. // if (echoCharacteristic) { bakePizza(); } else { console.log('missing characteristics'); } }) }) }) }) }) function bakePizza() { var crust = new Buffer("Hello BLE Service."); echoCharacteristic.write(crust, false, function(err) { if (!err) { echoCharacteristic.read(function (err, buffer) { if (!err) { console.log('BLE says' + buffer.toString()); } }); } else { console.log('crust error'); } }) } iotjs-1.0+715/test/run_pass/test_buffer.js000066400000000000000000000141001371177304000204700ustar00rootroot00000000000000/* 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 assert = require('assert'); var buff1 = new Buffer("test"); assert.equal(buff1.toString(), "test"); assert.equal(buff1.toString(undefined, 0, 0), ""); assert.equal(buff1.toString(undefined, 0, 1), "t"); assert.equal(buff1.toString(undefined, 0, 2), "te"); assert.equal(buff1.toString(undefined, 0, 3), "tes"); assert.equal(buff1.toString(undefined, 0, 4), "test"); assert.equal(buff1.toString(undefined, 1, 4), "est"); assert.equal(buff1.toString(undefined, 2, 4), "st"); assert.equal(buff1.toString(undefined, 3, 4), "t"); assert.equal(buff1.toString(undefined, 4, 4), ""); assert.equal(buff1.length, 4); var buff2 = new Buffer(10); buff2.write("abcde"); assert.equal(buff2.toString(), "abcde"); assert.equal(buff2.length ,10); buff2.write("fgh", 5); assert.equal(buff2.toString(), "abcdefgh"); assert.equal(buff2.length ,10); assert.throws(function() { buff2.write("ijk", -1); }, RangeError); assert.throws(function() { buff2.write("ijk", 10); }, RangeError); var buff3 = Buffer.concat([buff1, buff2]); assert.equal(buff3.toString(), "testabcdefgh"); assert.equal(buff3.length ,14); var buff4 = new Buffer(10); var buff5 = new Buffer('a1b2c3'); buff5.copy(buff4); assert.equal(buff4.toString(), 'a1b2c3'); buff5.copy(buff4, 4, 2); assert.equal(buff4.toString(), 'a1b2b2c3'); assert.throws(function() { buff5.copy(buff4, -1); }, RangeError); assert.throws(function() { buff2.write(null, 0, 0);}, TypeError); assert.throws(function() { buff5.copy(null); }, TypeError); assert.throws(function() { buff5.compare(null); }, TypeError); assert.throws(function() { buff5.equals(null); }, TypeError); assert.throws(function() { Buffer.concat([buff1, null]);}, TypeError); assert.throws(function() {Buffer.concat(null, null); }, TypeError); assert.throws(function() {var buff_err = new Buffer(null); }, TypeError); var buffer_err = new Buffer(-1); var buff_1 = new Buffer("asd"); var buff_2 = new Buffer(2); buff_1.copy(buff_2, 0, 0, 2); buff_2.write("asd", 0, 3); assert.throws(function() {var buff_3 = new Buffer('asd', 'hex'); }, TypeError); var buff_3 = new Buffer(4); assert.throws(function() {buff_3.writeUInt8(10000, 0); }, TypeError); var buff_4 = new Buffer(4); assert.throws(function() {buff_4.writeUInt8(0x11, 3000); }, RangeError); var buff_5 = new Buffer(4); assert.throws(function() {buff_5.readUInt8(3000); }, RangeError); var buff_6 = buff_5.slice(undefined, 2); buff_5.fill("asd"); buff_5.readInt8(3, true); buff_5.writeUInt32LE(0, 0, true); buff_5.writeUInt8(0, 0, true); buff_5.writeUInt16LE(0, 0, true); var buff6 = buff3.slice(1); assert.equal(buff6.toString(), 'estabcdefgh'); assert.equal(buff6.length, 13); var buff7 = buff6.slice(3, 5); assert.equal(buff7.toString(), 'ab'); assert.equal(buff7.length, 2); var buff8 = new Buffer(buff5); assert.equal(buff8.toString(), 'a1b2c3'); assert.equal(buff8.equals(buff5), true); assert.equal(buff8.equals(buff6), false); var buff9 = new Buffer('abcabcabcd'); var buff10 = buff9.slice(0, 3); var buff11 = buff9.slice(3, 6); var buff12 = buff9.slice(6); assert.equal(buff10.equals(buff11), true); assert.equal(buff11.equals(buff10), true); assert.equal(buff11.equals(buff12), false); assert.equal(buff10.compare(buff11), 0); assert.equal(buff11.compare(buff10), 0); assert.equal(buff11.compare(buff12), -1); assert.equal(buff12.compare(buff11), 1); assert.equal(buff9.slice(-2).toString(), 'cd'); assert.equal(buff9.slice(-3, -2).toString(), 'b'); assert.equal(buff9.slice(0, -2).toString(), 'abcabcab'); assert.equal(Buffer.isBuffer(buff9), true); assert.equal(Buffer.isBuffer(1), false); assert.equal(Buffer.isBuffer({}), false); assert.equal(Buffer.isBuffer('1'), false); assert.equal(Buffer.isBuffer([1]), false); assert.equal(Buffer.isBuffer([buff1]), false); assert.equal(Buffer.isBuffer({obj:buff1}), false); assert.equal(buff3.toString(), 'testabcdefgh'); var buff13 = new Buffer(4); buff13.writeUInt8(0x11, 0); assert.equal(buff13.readUInt8(0), 0x11); buff13.writeUInt16LE(0x3456, 1); assert.equal(buff13.readUInt8(1), 0x56); assert.equal(buff13.readUInt8(2), 0x34); assert.equal(buff13.readUInt16LE(1), 0x3456); buff13.writeUInt32LE(0x89abcdef, 0); assert.equal(buff13.readUInt8(0), 0xef); assert.equal(buff13.readUInt8(1), 0xcd); assert.equal(buff13.readUInt8(2), 0xab); assert.equal(buff13.readUInt8(3), 0x89); assert.equal(buff13.readUInt16LE(0), 0xcdef); assert.equal(buff13.readUInt16LE(2), 0x89ab); var buff14 = new Buffer([0x01, 0xa1, 0xfb]); assert.equal(buff14.readUInt8(0), 0x01); assert.equal(buff14.readUInt8(1), 0xa1); assert.equal(buff14.readUInt8(2), 0xfb); assert.equal(buff14.readInt8(2), -5); assert.equal(buff14.toString('hex'), '01a1fb'); var buff15 = new Buffer('7456a9', 'hex'); assert.equal(buff15.length, 3); assert.equal(buff15.readUInt8(0), 0x74); assert.equal(buff15.readUInt8(1), 0x56); assert.equal(buff15.readUInt8(2), 0xa9); assert.equal(buff15.toString('hex'), '7456a9'); var buff16 = new Buffer(4); var ret = buff16.fill(7); assert.equal(buff16.readInt8(0), 7); assert.equal(buff16.readInt8(1), 7); assert.equal(buff16.readInt8(2), 7); assert.equal(buff16.readInt8(3), 7); assert.equal(buff16, ret); buff16.fill(13+1024); assert.equal(buff16.readInt8(0), 13); assert.equal(buff16.readInt8(1), 13); assert.equal(buff16.readInt8(2), 13); assert.equal(buff16.readInt8(3), 13); assert.equal(Buffer(new Array()).toString(), ''); assert.equal(new Buffer(1).readUInt8(1, true), 0); assert.equal(new Buffer(1).readUInt16LE({}, true), 0); var buff17 = new Buffer("a"); assert.throws(function() { buff17.fill(8071).toString(); }, TypeError); iotjs-1.0+715/test/run_pass/test_buffer_from.js000066400000000000000000000030501371177304000215150ustar00rootroot00000000000000/* Copyright 2018-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 array_src = [65, 66, 67]; var buff = Buffer.from(array_src, 0, 3); assert.equal(buff.toString(), "ABC"); var buff2 = Buffer.from(array_src, 0, -3); // Buffer.from(string, encoding) var string_utf = "ABC"; var buff3 = Buffer.from(string_utf, 'utf8'); assert.equal(buff3.toString(), "ABC"); var string_hex = "414243"; var buff4 = Buffer.from(string_hex, 'hex'); assert.equal(buff4.toString(), "ABC"); // Buffer.from(Buffer) var buffer_src = new Buffer([0x41, 0x42, 0x43]); var buff5 = Buffer.from(buffer_src); assert.equal(buff5.toString(), "ABC"); var buff_undef = new Buffer(10); var buff6 = Buffer.from(buff_undef); assert.equal(buff6.toString(), buff_undef.toString()); // Corner case tests var obj = {}; var num = 5; assert.throws(function() { var buffer = Buffer.from(obj); }, TypeError); assert.throws(function() { var buffer = Buffer.from(num); }, TypeError); iotjs-1.0+715/test/run_pass/test_buffer_from_arraybuffer.js000066400000000000000000000057111371177304000241130ustar00rootroot00000000000000/* Copyright 2018-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 source = new ArrayBuffer(10); //creation tests var buff1 = Buffer.from(source, 0, 10); assert.equal(buff1.length, 10); var buff2 = Buffer.from(source, 3, 7); assert.throws(function() { var buffer = buffer.from(source, 3, 10) }) assert.equal(buff2.length, 7); var buff3 = Buffer.from(source, 10, 0); assert.equal(buff3.length, 0); var buff4 = Buffer.from(source, 0, 0); assert.equal(buff4.length, 0); assert.throws(function() { var buffer = Buffer.from(source, 0, 1000); }, RangeError); assert.throws(function() { var buffer = Buffer.from(source, 1000, 9); }, RangeError); assert.throws(function() { var buffer = Buffer.from(source, 1000, 1000); }, RangeError); var buff5 = Buffer.from(source, undefined, 10); assert.equal(buff5.length, 10); var buff6 = Buffer.from(source, undefined, 0); assert.equal(buff6.length, 0); var buff7 = Buffer.from(source, undefined, -10); assert.equal(buff7.length, 0); var buff8 = Buffer.from(source, 0, undefined); assert.equal(buff8.length, 10); var buff9 = Buffer.from(source, 10, undefined); assert.equal(buff9.length, 0); assert.throws(function() {var buffer = Buffer.from(source, -10, undefined); }, RangeError); var buff10 = Buffer.from(source, undefined, undefined); assert.equal(buff10.length, 10); var buff11 = Buffer.from(source, NaN, 10); assert.equal(buff11.length, 10); var buff12 = Buffer.from(source, NaN, 0); assert.equal(buff12.length, 0); var buff13 = Buffer.from(source, NaN, -10); assert.equal(buff13.length, 0); var buff14 = Buffer.from(source, 0, NaN); assert.equal(buff14.length, 0); var buff15 = Buffer.from(source, 10, NaN); assert.equal(buff15.length, 0); assert.throws(function() { var buffer = Buffer.from(source, -10, NaN); }, RangeError); //value checks var typed_source1 = new Uint8Array([65, 66]); var arr_buff = Buffer.from(typed_source1.buffer, 0, 2); assert.equal(arr_buff.toString('utf-8'), 'AB'); var typed_source2 = new Uint16Array([65, 66]); var arr_buff2 = Buffer.from(typed_source2.buffer, 0, 1); var arr_buff3 = Buffer.from(typed_source2.buffer, 2, 1); assert.equal(arr_buff2.toString(), 'A'); assert.equal(arr_buff3.toString(), 'B'); var typed_source3 = new Uint8Array([42, 43]); var arr_buff4 = Buffer.from(typed_source3.buffer, 0, 2); assert.equal(arr_buff4.toString('hex'), '2a2b'); iotjs-1.0+715/test/run_pass/test_buffer_inmutability_creation.js000066400000000000000000000024221371177304000251520ustar00rootroot00000000000000/* Copyright 2018-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. */ /* Related issue: https://github.com/Samsung/iotjs/issues/1379 */ var assert = require('assert'); /* The global Buffer by default is a function */ assert.strictEqual(typeof(Buffer), "function"); var backup_buffer = Buffer; /* Modify the global Buffer */ Buffer++; /** * The ++ operation will change the value of the "Buffer" variable. * Thus the type shouldn't be a function now. */ assert.notStrictEqual(typeof(Buffer), "function"); /** * Still the creation of buffer should work. * Using an already saved buffer reference */ var new_buffer = backup_buffer("OK"); assert.equal(new_buffer.length, 2); assert.equal(new_buffer.toString(), "OK"); iotjs-1.0+715/test/run_pass/test_buffer_str_conv.js000066400000000000000000000070511371177304000224140ustar00rootroot00000000000000/* 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 assert = require('assert'); function decodeError(string, encode) { try { new Buffer(string, encode); } catch (e) { assert.assert(e instanceof TypeError); } } function testWrite(input, string, offset, length, encoding, expected, expectedLength) { var buf = new Buffer(input); assert.equal(buf.write(string, offset, length, encoding), expectedLength); assert.equal(buf.toString(), expected); } /* Base64 tests. */ assert.equal((new Buffer('YnVmZg==', 'base64')).toString(), 'buff'); assert.equal((new Buffer('YnVmZmU=', 'base64')).toString(), 'buffe'); assert.equal((new Buffer('YnVmZmVy', 'base64')).toString(), 'buffer'); assert.equal((new Buffer('KiAxMjM0ICo=', 'base64')).toString(), '* 1234 *'); assert.equal((new Buffer('f39/fw==', 'base64')).toString(), '\u007f\u007f\u007f\u007f'); assert.equal((new Buffer('fn5+fg==', 'base64')).toString(), '\u007e\u007e\u007e\u007e'); decodeError('Yn=mZg==', 'base64'); decodeError('YnVmZ===', 'base64'); decodeError('YnVmZm', 'base64'); decodeError('KiAx*jM0ICo=', 'base64'); testWrite('xxxxxxxx', 'MTIzNA==', 2, 16, 'base64', 'xx1234xx', 4); testWrite('xxxxxxxx', 'MTIzNA==', 2, 0, 'base64', 'xxxxxxxx', 0); testWrite('xxxxxxxx', 'MTIzNA==', 3, 2, 'base64', 'xxx12xxx', 2); testWrite('xxxx', 'MTIzNA==', 2, 16, 'base64', 'xx12', 2); assert.throws(function () { /* Malformed string must throw error regardless of the buffer length. */ testWrite('xxxxxxxx', 'MTIzNA=!', 2, 2, 'base64', 'xx12xxxx'); }); assert.equal((new Buffer('buff')).toString('base64'), 'YnVmZg=='); assert.equal((new Buffer('buffe')).toString('base64'), 'YnVmZmU='); assert.equal((new Buffer('buffer')).toString('base64'), 'YnVmZmVy'); assert.equal((new Buffer('\u007f\u007f\u007f\u007f')).toString('base64'), 'f39/fw=='); assert.equal((new Buffer('\u007e\u007e\u007e\u007e')).toString('base64'), 'fn5+fg=='); assert.equal((new Buffer('**buffer**')).toString('base64', 2, 7), 'YnVmZmU='); /* Hex tests. */ assert.equal((new Buffer('6768696A6b6c6D6e6f70', 'hex')).toString(), 'ghijklmnop'); assert.equal((new Buffer('2a20427546663352202a', 'hex')).toString(), '* BuFf3R *'); assert.equal((new Buffer('eFbfBf', 'hex')).toString(), '\uffff'); decodeError('0*12', 'hex'); decodeError('0fe', 'hex'); decodeError('0g', 'hex'); testWrite('xxxxxxxx', '31323334', 2, 16, 'hex', 'xx1234xx', 4); testWrite('xxxxxxxx', '31323334', 2, 0, 'hex', 'xxxxxxxx', 0); testWrite('xxxxxxxx', '31323334', 3, 2, 'hex', 'xxx12xxx', 2); testWrite('xxxx', '31323334', 2, 16, 'hex', 'xx12', 2); assert.throws(function () { /* Malformed string must throw error regardless of the buffer length. */ testWrite('xxxxxxxx', '3132333g', 2, 2, 'base64', 'xx12xxxx'); }); assert.equal((new Buffer('ghijklmnop')).toString('hex'), '6768696a6b6c6d6e6f70'); assert.equal((new Buffer('ghijklmnop')).toString('hex', 2, 8), '696a6b6c6d6e'); iotjs-1.0+715/test/run_pass/test_console.js000066400000000000000000000021671371177304000206730ustar00rootroot00000000000000/* 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 console = require('console'); console.log("Hello IoT.js!!"); console.log(1); console.log(2); console.log(3); console.log(3+5*2); console.log([1, 2, 3]); console.log(1, 2, 3); console.log('a', 1, 'b', 2, 'c', 3); console.log("test", null, undefined); console.log({ a: '123', b: 123, c: [1, 2, 3]}); console.error("Hello IoT.js!!"); console.error(1); console.error(2); console.error(3); console.error(3+5*2); console.error([1, 2, 3]); console.error(1, 2, 3); console.error('a', 1, 'b', 2, 'c', 3); iotjs-1.0+715/test/run_pass/test_crypto.js000066400000000000000000000021641371177304000205460ustar00rootroot00000000000000/* Copyright 2018-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 crypto = require('crypto'); var assert = require('assert'); var hash = crypto.createHash('sha1'); assert.throws(function() { var err_hash = crypto.createHash('sadf'); }); hash.update('Hello IoT.js'); assert.equal(hash.digest('hex'), '4f5cf1945efb60f400c23172edb4e36b47f5a25e'); assert.throws(function() { hash.digest('hex'); }); var hash2 = crypto.createHash('sha1'); hash2.update('Hello IoT.js'); hash2.update(' v2'); assert.equal(hash2.digest('base64'), 'DBnLTkxZ70AgUzCjZ7FTv91AWZw='); iotjs-1.0+715/test/run_pass/test_crypto_tls.js000066400000000000000000000055721371177304000214360ustar00rootroot00000000000000/* Copyright 2018-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 crypto = require('crypto'); var fs = require('fs'); var hash = crypto.createHash('sha256'); hash.update('Hello IoT.js'); assert.equal(hash.digest('hex'), '23a1b938002c83a74b887d0a447c990' + '5e83bab00459bcfd0bad548623b942e20'); /* This test requires a key file, which can be generated using the following steps: openssl genrsa -aes128 -passout pass: -out private.pem 2048 openssl rsa -in private.pem -passin pass: -pubout -out public.pem Recreating this test with your own data requires you to have (a) key file(s) with a public and a private key in them. The private key is used to sign the data. The public key is used to verify that the signature was done with the appropriate private key. To generate the rsa-sha256 signature you need to execute these lines: Creating an sha256 signature openssl dgst -sha256 -sign -out Creating a base64 encoded signature openssl base64 -in -out To verify the signature, you need: - The file, - The public key, most likely from the public.pem file, - The which contains the data, or you can just copy and paste, the data and give it to the `verify.update()` function. Having created the `verify` object, just call the `.verify(pubkey, signature)` on it, and you are ready to go. */ var pubKey = fs.readFileSync(process.cwd() + '/resources/crypto_public.pem'); var verify = crypto.createVerify('sha256'); verify.update('Hello IoT.js\n'); var res = verify.verify(pubKey, 'JkFnOrBQGXYlpmlcMuS5EwyJ44WY/kW5sFwb8DRgAoo7' + 'RmxYPKgyo/OrZ0YAcY5xpxbVZzS7ftxz7N4q+Ouufg6s' + 'NSzmIimBPLV+afX4Qb8jOV0edCmeBKZaHQrMWpisWXF/' + 'bZKS1yiMij2NGSJYXWhjRzreIeVNVv/b0phHHeK2r2tT' + '9T+XA+rdgHlIOb+r/FT/VWopr+vd+8I0fjxpP/S8lZ5u' + 'HSF9jZ5TFdIEYMWchKit4Eyw7/VAWRlJNNKVxTmuM337' + '+rP9oLKiFUeoM6jrE10LxGnIpelvyNV+MHfo11I1GAMK' + 'jsOuye9JZ8/hQPg+KLWH/l/xZlUD2fZNNg=='); assert.equal(res, true); iotjs-1.0+715/test/run_pass/test_dgram_1_server_1_client.js000066400000000000000000000037241371177304000237070ustar00rootroot00000000000000/* 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 dgram = require('dgram'); var port = 41234; var msg = 'Hello IoT.js'; var server = dgram.createSocket('udp4'); server.on('error', function(err) { assert.fail(); server.close(); }); server.on('message', function(data, rinfo) { console.log('server got data : ' + data); console.log('client address : ' + rinfo.address); console.log('client port : ' + rinfo.port); console.log('client family : ' + rinfo.family); assert.equal(data, msg); server.send(msg, rinfo.port, 'localhost', function (err, len) { assert.equal(err, null); assert.equal(len, msg.length); server.close(); }); }); server.on('listening', function() { console.log('listening'); }); server.bind(port); var client = dgram.createSocket('udp4'); client.send(msg, port, 'localhost', function(err, len) { assert.equal(err, null); assert.equal(len, msg.length); }); client.on('error', function(err) { assert.fail(); client.close(); }); client.on('message', function(data, rinfo) { console.log('client got data : ' + data); console.log('server address : ' + rinfo.address); console.log('server port : ' + rinfo.port); console.log('server family : ' + rinfo.family); assert.equal(port, rinfo.port); assert.equal(data, msg); client.close(); }); process.on('exit', function(code) { assert.equal(code, 0); }); iotjs-1.0+715/test/run_pass/test_dgram_1_server_n_clients.js000066400000000000000000000035321371177304000241640ustar00rootroot00000000000000/* 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 dgram = require('dgram'); var port = 41235; var msg = ''; var sockcount = 5; var sendcount = 0; var server = dgram.createSocket('udp4'); server.on('error', function(err) { assert.fail(); server.close(); }); server.on('message', function(data, rinfo) { console.log('server got data : ' + data); msg += data; server.send(data, rinfo.port, 'localhost', function (err, len) { sendcount++; if (sendcount >= sockcount) { server.close(); } }); }); server.bind(port); function sendAndRecieve(i) { var client = dgram.createSocket('udp4'); client.send(i.toString(), port, 'localhost'); client.on('error', function(err) { assert.fail(); client.close(); }); client.on('message', function(data, rinfo) { console.log('client got data : ' + data); assert.equal(port, rinfo.port); assert.equal(data, i.toString()); client.close(); }); } for (var i = 0; i < sockcount; i++) { setTimeout(sendAndRecieve, 200 * i, i); } process.on('exit', function(code) { assert.equal(msg.length, sockcount); for (var i = 0; i < sockcount; i++) { if (msg.indexOf(i.toString()) === -1) { assert.fail(); } } assert.equal(code, 0); }); iotjs-1.0+715/test/run_pass/test_dgram_address.js000066400000000000000000000034211371177304000220220ustar00rootroot00000000000000/* 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 dgram = require('dgram'); var port = 41236; var msg = 'Hello IoT.js'; var client = dgram.createSocket({ type: 'udp4', reuseAddr: true }); var server = dgram.createSocket({ type: 'udp4', reuseAddr: true }); var server_address, server_port, client_address, client_port; server.on('error', function(err) { assert.fail(); server.close(); }); server.on('message', function(data, rinfo) { var address = client.address(); client_address = address.address; client_port = address.port; assert.equal('0.0.0.0', client_address); assert.equal(rinfo.port, client_port); server.send(msg, rinfo.port, 'localhost'); }); server.on('listening', function() { var address = server.address(); server_address = address.address; server_port = address.port; }) server.bind(port); client.send(msg, port, 'localhost'); client.on('error', function(err) { assert.fail(); client.close(); }); client.on('message', function(data, rinfo) { assert.equal('0.0.0.0', server_address); assert.equal(rinfo.port, server_port); client.close(); server.close(); }); process.on('exit', function(code) { assert.equal(code, 0); }); iotjs-1.0+715/test/run_pass/test_dgram_broadcast.js000066400000000000000000000043341371177304000223430ustar00rootroot00000000000000/* 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 dgram = require('dgram'); var port = 41237; var broadcast_address = '255.255.255.255'; var interval = 100; var msg_count = 0, msg_count2 = 0, msg_count3 = 0, send_count = 0; var msg = 'Hello IoT.js'; var socket = dgram.createSocket({type: 'udp4', reuseAddr: true}); var socket2 = dgram.createSocket({type: 'udp4', reuseAddr: true}); var socket3 = dgram.createSocket({type: 'udp4', reuseAddr: true}); socket.on('error', function(err) { assert.fail(); socket.close(); }); socket2.on('error', function(err) { assert.fail(); socket2.close(); }); socket3.on('error', function(err) { assert.fail(); socket3.close(); }); socket.on('message', function(data, rinfo) { console.log('socket got data : ' + data); msg_count++; if (msg_count == 3) { socket.close(); } }); socket2.on('message', function(data, rinfo) { console.log('socket2 got data : ' + data); msg_count2++; if (msg_count2 == 3) { socket2.close(); } }); socket3.on('message', function(data, rinfo) { console.log('socket3 got data : ' + data); msg_count3++; if (msg_count3 == 3) { socket3.close(); } }); socket.bind(port, function() { socket.setBroadcast(true); var timer = setInterval(function () { send_count++; socket.send(msg, port, broadcast_address); if (send_count == 3) { clearInterval(timer); } }, interval); }); socket2.bind(port); socket3.bind(port); process.on('exit', function(code) { assert.equal(code, 0); assert.equal(msg_count, 3); assert.equal(msg_count2, 3); assert.equal(msg_count3, 3); assert.equal(send_count, 3); }); iotjs-1.0+715/test/run_pass/test_dgram_multicast_membership.js000066400000000000000000000042601371177304000246170ustar00rootroot00000000000000/* 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 dgram = require('dgram'); var MODE = process.argv[2] || 'echo'; var SERVER = 'server'; var CLIENT = 'client'; var ECHO = 'echo'; if (MODE !== 'server' && MODE !== 'client' && MODE !== 'echo') { console.log( 'usage: iotjs test_dgram_multicast_membership.js server|client|echo'); assert(false); } var port = 41239; var multicast_address = '230.255.255.250'; var interval = 1000; var msg = 'Hello IoT.js'; if (MODE !== CLIENT) { // for server and echo var recv_count = 0; var server = dgram.createSocket('udp4'); server.on('message', function(data, rinfo) { console.log('server got data : ' + data); recv_count++; if (recv_count == 1) { server.dropMembership(multicast_address); } }); server.bind(port, function() { server.addMembership(multicast_address); }); server.on('error', function(err) { assert.fail(); server.close(); }); setTimeout(function() { server.close(); }, 5000); } if (MODE !== SERVER) { // for client and echo var send_count = 0; var client = dgram.createSocket('udp4'); var timer = setInterval(function () { send_count++; console.log('client send data : ' + msg); client.send(msg, port, multicast_address); if (send_count == 3) { clearInterval(timer); } }, interval); setTimeout(function() { client.close(); }, 5000); } process.on('exit', function(code) { assert.equal(code, 0); if (MODE !== CLIENT) { assert.equal(recv_count, 1); } if (MODE !== SERVER) { assert.equal(send_count, 3); } }); iotjs-1.0+715/test/run_pass/test_dgram_multicast_set_multicast_loop.js000066400000000000000000000023261371177304000263760ustar00rootroot00000000000000/* 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 dgram = require('dgram'); var port = 41240; var multicast_address = '230.255.255.250'; var msg = 'Hello IoT.js'; var server = dgram.createSocket('udp4'); server.on('error', function(err) { assert.fail(); }); server.on('message', function(data, rinfo) { assert.fail(); }); server.bind(port, function() { server.setMulticastLoopback(false); server.addMembership(multicast_address); server.send(msg, port, multicast_address); }); setTimeout(function() { server.close(); }, 1000); process.on('exit', function(code) { assert.equal(code, 0); }); iotjs-1.0+715/test/run_pass/test_dgram_setttl_client.js000066400000000000000000000032511371177304000232530ustar00rootroot00000000000000/* 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 dgram = require('dgram'); var port = 41234; var msg = 'Hello IoT.js'; var msg2 = 'Bye IoT.js'; var addr = '192.168.0.1'; // Change to your ip address var server = dgram.createSocket('udp4'); var client = dgram.createSocket('udp4'); client.send(msg, port, addr, function(err, len) { assert.equal(err, null); assert.equal(len, msg.length); }); client.on('error', function(err) { assert.fail(); }); client.on('listening', function(err) { client.setTTL(2); }); client.on('message', function(data, rinfo) { console.log('client got data : ' + data); console.log('server address : ' + rinfo.address); console.log('server port : ' + rinfo.port); console.log('server family : ' + rinfo.family); assert.equal(port, rinfo.port); assert.equal(data, msg); /* send with TTL=1 */ client.setTTL(1); client.send(msg2, port, addr, function(err, len) { assert.equal(err, null); assert.equal(len, msg2.length); client.close(); }); }); process.on('exit', function(code) { assert.equal(code, 0); }); iotjs-1.0+715/test/run_pass/test_dgram_setttl_server.js000066400000000000000000000030471371177304000233060ustar00rootroot00000000000000/* 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 dgram = require('dgram'); var port = 41234; var msg = 'Hello IoT.js'; var server = dgram.createSocket('udp4'); var recvMsg = ""; var recvCnt = 0; server.on('error', function(err) { assert.fail(); server.close(); }); server.on('message', function(data, rinfo) { console.log('server got data : ' + data); console.log('client address : ' + rinfo.address); console.log('client port : ' + rinfo.port); console.log('client family : ' + rinfo.family); recvMsg = data; recvCnt++; server.send(msg, rinfo.port, rinfo.address, function (err, len) { assert.equal(err, null); assert.equal(len, msg.length); }); setTimeout(function() { server.close() }, 4000); }); server.on('listening', function() { console.log('listening'); }); server.bind(port); process.on('exit', function(code) { assert.equal(code, 0); assert.equal(recvCnt, 1); assert.equal(recvMsg, msg); }); iotjs-1.0+715/test/run_pass/test_dns.js000066400000000000000000000026501371177304000200120ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var server = net.createServer(); var port = 1236; server.listen(port, 5); server.on('connection', function(socket) { socket.on('data', function(data) { socket.end('Hello IoT.js'); }); socket.on('close', function() { server.close(); }); }); var socket = new net.Socket(); var msg = ""; var lookupHandled = false; socket.on('lookup', function(err, ip, family) { lookupHandled = true; }); socket.connect(port, "localhost"); // connect with hostname socket.write("Hello IoT.js"); socket.on('data', function(data) { msg += data; }); socket.on('end', function() { socket.end(); }); process.on('exit', function(code) { assert.equal(code, 0); assert.equal(msg, "Hello IoT.js"); assert.equal(lookupHandled, true); }); iotjs-1.0+715/test/run_pass/test_dns_lookup.js000066400000000000000000000062261371177304000214060ustar00rootroot00000000000000/* 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 dns = require('dns'); var assert = require('assert'); var options = { family: 4, hints: dns.ADDRCONFIG | dns.V4MAPPED, }; function isIPv4(ip) { var IPv4Regex = new RegExp( '^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$' ); return IPv4Regex.test(ip); } dns.lookup('localhost', 4, function(err, ip, family) { assert.equal(err, null); assert.equal(isIPv4(ip), true); assert.equal(ip, '127.0.0.1'); assert.strictEqual(family, 4); }); // Test with IPv4 option. dns.lookup('localhost', 4, function(err, ip, family) { assert.equal(err, null); assert.equal(isIPv4(ip), true); assert.equal(ip, '127.0.0.1'); assert.strictEqual(family, 4); }); // Test without explicit options parameter. dns.lookup('localhost', function(err, ip, family) { assert.equal(err, null); assert.equal(isIPv4(ip), true); assert.equal(ip, '127.0.0.1'); }); // Test with invalid hostname. dns.lookup('invalid', 4, function(err, ip, family) { assert.notEqual(err, null); }); // Test with empty hostname. dns.lookup('', 4, function(err, ip, family) { if (process.platform === "windows") { /* On windows the empty dns name can be resolved. */ assert.equal(err, null); assert.notEqual(ip, null); assert.notEqual(family, null); } else { assert.notEqual(err, null); } }); // Test with non string hostname. assert.throws(function() { dns.lookup(5000, options, function(err, ip, family) {}); }, TypeError); // Test without callback function. assert.throws(function() { dns.lookup('localhost', options); }, TypeError); // Test with invalid callback parameter. assert.throws(function() { dns.lookup('localhost', options, 5000); }, TypeError); assert.throws(function() { dns.lookup('localhost', options, 'callback'); }, TypeError); // Test with invalid hints option. options.hints = -1; assert.throws(function() { dns.lookup('localhost', options, function(err, ip, family) {}); }, TypeError); options.hints = 5000; assert.throws(function() { dns.lookup('localhost', options, function(err, ip, family) {}); }, TypeError); // Test with invalid options parameter. assert.throws(function() { dns.lookup('localhost', 'options', function(err, ip, family) {}); }, TypeError); assert.throws(function() { dns.lookup('localhost', '', function(err, ip, family) {}); }, TypeError); // Test with invalid family option. assert.throws(function() { dns.lookup('localhost', 10, function(err, ip, family) {}); }, TypeError); assert.throws(function() { dns.lookup('localhost', -5, function(err, ip, family) {}); }, TypeError); iotjs-1.0+715/test/run_pass/test_events.js000066400000000000000000000142431371177304000205330ustar00rootroot00000000000000/* 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 EventEmitter = require('events'); var assert = require('assert'); assert.strictEqual(EventEmitter, EventEmitter.EventEmitter); var emitter = new EventEmitter(); var eventCnt1 = 0; var eventCnt2 = 0; var eventCnt3 = 0; var onceCnt = 0; var eventSequence = ""; emitter.once('once', function() { onceCnt += 1; }); assert.equal(onceCnt, 0); emitter.emit('once'); assert.equal(onceCnt, 1); emitter.emit('once'); assert.equal(onceCnt, 1); { var emit_test = new EventEmitter(); emit_test._events = false; emit_test.emit(); } { var emit_test = new EventEmitter(); emit_test._events.error = false; emit_test.emit(null); } { var emit_test = new EventEmitter(); emit_test._events = false; assert.throws(function() { emit_test.addListener(null, null); }, TypeError); } { var emit_test = new EventEmitter(); emit_test._events = false; emit_test.addListener('event', function() { }); } { var emit_test = new EventEmitter(); assert.throws(function() { emit_test.once(null, null); }, TypeError); } { var emit_test = new EventEmitter(); assert.throws(function() { emit_test.removeListener(null, null); }, TypeError); } { var emit_test = new EventEmitter(); emit_test._events = false; emit_test.removeListener('rmtest', function() { }); } emitter.once('once2', function() { onceCnt += 1; assert.equal(arguments.length, 14); assert.equal(arguments[0], 0); assert.equal(arguments[1], 1); assert.equal(arguments[2], 2); assert.equal(arguments[3], 3); assert.equal(arguments[4], 4); assert.equal(arguments[5], 5); assert.equal(arguments[6], 6); assert.equal(arguments[7], 7); assert.equal(arguments[8], 8); assert.equal(arguments[9], 9); assert.equal(arguments[10], "a"); assert.equal(arguments[11], "b"); assert.equal(arguments[12], "c"); assert.equal(arguments[13].a, 123); }); assert.equal(onceCnt, 1); emitter.emit('once2', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", { a: 123}); assert.equal(onceCnt, 2); emitter.emit('once2', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", { a: 123}); assert.equal(onceCnt, 2); emitter.addListener('event', function() { eventCnt1 += 1; eventSequence += "1"; }); assert.equal(eventCnt1, 0); emitter.emit('event'); assert.equal(eventCnt1, 1); emitter.addListener('event', function() { eventCnt2 += 1; eventSequence += "2"; }); assert.equal(eventCnt2, 0); emitter.emit('event'); assert.equal(eventCnt1, 2); assert.equal(eventCnt2, 1); emitter.addListener('event', function() { eventCnt3 += 1; eventSequence += "3"; }); assert.equal(eventCnt3, 0); emitter.emit('event'); assert.equal(eventCnt1, 3); assert.equal(eventCnt2, 2); assert.equal(eventCnt3, 1); emitter.emit('event'); assert.equal(eventCnt1, 4); assert.equal(eventCnt2, 3); assert.equal(eventCnt3, 2); emitter.emit('no receiver'); assert.equal(eventCnt1, 4); assert.equal(eventCnt2, 3); assert.equal(eventCnt3, 2); emitter.addListener('args', function() { assert.equal(arguments.length, 14); assert.equal(arguments[0], 0); assert.equal(arguments[1], 1); assert.equal(arguments[2], 2); assert.equal(arguments[3], 3); assert.equal(arguments[4], 4); assert.equal(arguments[5], 5); assert.equal(arguments[6], 6); assert.equal(arguments[7], 7); assert.equal(arguments[8], 8); assert.equal(arguments[9], 9); assert.equal(arguments[10], "a"); assert.equal(arguments[11], "b"); assert.equal(arguments[12], "c"); assert.equal(arguments[13].a, 123); eventSequence += "4"; }); emitter.addListener('args', function() { assert.equal(arguments.length, 14); eventSequence += "5"; }) emitter.emit('args', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", { a: 123}); var listener1 = function() { eventSequence += '6'; }; emitter.addListener('rmTest', listener1); emitter.emit('rmTest'); emitter.removeListener('rmTest', function() {}); emitter.emit('rmTest'); emitter.removeListener('rmTest', listener1); emitter.emit('rmTest'); var listener2 = function() { eventSequence += '7'; }; emitter.addListener('rmTest', listener2); emitter.addListener('rmTest', listener2); emitter.emit('rmTest'); eventSequence += "|" emitter.removeListener('rmTest', listener2); emitter.emit('rmTest'); eventSequence += "|" emitter.removeListener('rmTest', listener2); emitter.emit('rmTest'); eventSequence += "|" var listener3 = function() { eventSequence += '8'; }; emitter.addListener('rmTest', listener3); emitter.addListener('rmTest', listener3); emitter.emit('rmTest'); eventSequence += "|"; emitter.removeAllListeners('rmTest'); emitter.emit('rmTest'); eventSequence += "|"; emitter.emit('event'); eventSequence += "|"; emitter.removeAllListeners(); emitter.emit('event'); eventSequence += "|"; assert.equal(eventSequence, "112123123456677|7||88||123||"); /* Test if an event listener for a once call can be removed. */ var removableListenerCnt = 0; function removableListener() { removableListenerCnt++; } emitter.once('onceRemove', removableListener); assert.equal(removableListenerCnt, 0); emitter.removeListener('onceRemove', removableListener); emitter.emit('onceRemove'); assert.equal(removableListenerCnt, 0, 'a listener for a "once" typed event should be removable'); /* * Test when the last listener is removed from an object, * the related property doesn't exist anymore. */ var listener1 = function() { }; emitter.addListener('event1', listener1); emitter.removeListener('event1', listener1); var res = emitter.emit('event1'); assert.equal(res, false); emitter.addListener('event2', listener1); emitter.addListener('event2', listener1); emitter.removeAllListeners('event2'); res = emitter.emit('event2'); assert.equal(res, false); iotjs-1.0+715/test/run_pass/test_events_assert_emit_error.js000066400000000000000000000014641371177304000243440ustar00rootroot00000000000000/* 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 assert = require('assert'); var EventEmitter = require('events').EventEmitter; var ee = new EventEmitter(); assert.throws( function() { ee.emit('error'); }, Error); iotjs-1.0+715/test/run_pass/test_events_uncaught_error.js000066400000000000000000000022671371177304000236450ustar00rootroot00000000000000/* 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 assert = require('assert'); var EventEmitter = require('events').EventEmitter; var uncaught_error = false; process.on('uncaughtException', function(err) { assert.equal(err.message, "Uncaught 'error' event", 'Error type does not match'); uncaught_error = true; }); process.on('exit', function(code) { process.removeAllListeners('uncaughtException'); assert.equal(code, 0, 'Non-zero exit status code:' + code); assert(uncaught_error, 'Expected uncaughtException was not executed'); }); var ee = new EventEmitter(); ee.emit('error'); iotjs-1.0+715/test/run_pass/test_fs_event.js000066400000000000000000000042021371177304000210320ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var srcFilePath = process.cwd() + "/resources/test1.txt"; var dstFilePath = process.cwd() + "/tmp/test_fs2.txt"; // TizenRT tests are performed from ROM // Files should be stored in other path if (process.platform === 'tizenrt') { dstFilePath = "/mnt/test_fs2.txt"; // Prepare test environment if (fs.existsSync(dstFilePath)) { fs.unlinkSync(dstFilePath); } } function cleanup() { if (process.platform === 'tizenrt') { fs.unlinkSync(dstFilePath); } } var result = 'TEST File Read & Write\n'; var data; function onOpenForWrite(err, fd) { assert.equal(err, null, 'Failed to open for write file:' + err); fs.write(fd, data, 0, data.length, function (err, written, buffer) { assert.equal(err, null, 'Failed to write file:' + err); fs.closeSync(fd); var fdr = fs.openSync(dstFilePath, 'r'); var buffer = new Buffer(128); fs.readSync(fdr, buffer, 0, buffer.length, 0); fs.closeSync(fdr); cleanup(); assert.equal(buffer.toString(), result, 'Read/write content does not match'); }); } function onRead(err, bytesRead, buffer) { assert.equal(err, null, 'Failed to read file:' + err); data = new Buffer(buffer.toString()); fs.open(dstFilePath, 'w', onOpenForWrite); } function onOpenForRead(err, fd) { assert.equal(err, null, 'Failed to open for read file:' + err); var buffer = new Buffer(128); fs.read(fd, buffer, 0, buffer.length, 0, onRead); } fs.open(srcFilePath, 'r', onOpenForRead); iotjs-1.0+715/test/run_pass/test_fs_exists.js000066400000000000000000000036551371177304000212430ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); { var filePath = process.cwd() + '/resources/tobeornottobe.txt'; fs.exists(filePath, function(exists) { assert.equal(exists, true, 'File should exist: ' + filePath); }); } { var filePath = ''; assert.doesNotThrow(function() { fs.exists(filePath, function (exists) { assert.equal(exists, false, 'File with empty name should not exist'); }); }, 'Checking fs.exists(\'\') without callback does not throw exception'); assert.doesNotThrow(function() { fs.exists(filePath); }, 'Checking fs.exists(\'\') without callback does not throw exception'); } { var filePath = process.cwd() + '/resources/tobeornottobe.txt'; assert.doesNotThrow(function() { fs.exists(filePath); }, 'Checking fs.exists() for existing file does not throw exception'); } { var filePath = process.cwd() + '/resources/empty.txt'; fs.exists(filePath, function(exists) { assert.equal(exists, false, 'File should not exist' + filePath); }); } { var filePath = ''; fs.exists(filePath, function(exists) { assert.equal(exists, false, 'File with empty name should not exist'); }); } { var filePath = ' '; fs.exists(filePath, function(exists) { assert.equal(exists, false, 'File name with single whitespace check'); }); } iotjs-1.0+715/test/run_pass/test_fs_exists_sync.js000066400000000000000000000024471371177304000222750ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); { var filePath = process.cwd() + "/resources/tobeornottobe.txt"; var result = fs.existsSync(filePath); assert.equal(result, true, 'File should exist: ' + filePath); } { var filePath = process.cwd() + "/resources/empty.txt"; var result = fs.existsSync(filePath); assert.equal(result, false, 'File should not exist: ' + filePath); } { var filePath = ""; var result = fs.existsSync(filePath); assert.equal(result, false, 'File with empty should not exist'); } { var filePath = " "; var result = fs.existsSync(filePath); assert.equal(result, false, 'File name with single whitespace check'); } iotjs-1.0+715/test/run_pass/test_fs_fstat.js000066400000000000000000000027641371177304000210450ustar00rootroot00000000000000/* 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 assert = require('assert'); var testfile = process.cwd() + "/run_pass/test_fs_fstat.js"; var testdir = process.cwd() + "/resources"; var flags = "r"; // fstat - file fs.open(testfile, flags, function(err, fd) { if (err) { throw err; } fs.fstat(fd, function(err, stat) { if (err) { throw err; } assert.equal(stat.isFile(), true); assert.equal(stat.isDirectory(), false); fs.close(fd, function(err) { if (err) { throw err; } }); }); }); // fstat - directory fs.open(testdir, flags, function(err, fd) { if (err) { throw err; } fs.fstat(fd, function(err, stat) { if (err) { throw err; } assert.equal(stat.isFile(), false); assert.equal(stat.isDirectory(), true); fs.close(fd, function(err) { if (err) { throw err; } }); }); }); iotjs-1.0+715/test/run_pass/test_fs_fstat_sync.js000066400000000000000000000024151371177304000220720ustar00rootroot00000000000000/* 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 assert = require('assert'); var testfile = process.cwd() + "/run_pass/test_fs_fstat_sync.js"; var testdir = process.cwd() + "/resources"; var flags = "r"; // fstatSync - file try { var fd = fs.openSync(testfile, flags); var stat = fs.fstatSync(fd); assert.equal(stat.isFile(), true); assert.equal(stat.isDirectory(), false); fs.closeSync(fd); } catch (err) { throw err; } // fstatSync - directory try { var fd = fs.openSync(testdir, flags); var stat = fs.fstatSync(fd); assert.equal(stat.isFile(), false); assert.equal(stat.isDirectory(), true); fs.closeSync(fd); } catch (err) { throw err; } iotjs-1.0+715/test/run_pass/test_fs_mkdir_rmdir.js000066400000000000000000000046771371177304000222340ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var testRoot = process.cwd() + "/resources"; // TizenRT tests are performed from ROM // Files should be stored in other path if (process.platform === 'tizenrt') { testRoot = "/mnt"; } function unlink(path) { try { fs.rmdirSync(path); } catch (e) { } assert.equal(fs.existsSync(path), false); } { var root = testRoot + "/test_dir"; var sub1 = root + "/file1"; var sub2 = root + "/file2"; unlink(sub1); unlink(sub2); unlink(root); fs.mkdir(root, function(err) { assert.equal(err, null); assert.equal(fs.existsSync(root), true); assert.equal(fs.mkdirSync(sub1), undefined); assert.equal(fs.mkdirSync(sub2), undefined); assert.equal(fs.existsSync(sub1), true); assert.equal(fs.existsSync(sub2), true); unlink(sub1); unlink(sub2); fs.rmdir(root, function() { assert.equal(fs.existsSync(root), false); var root2 = testRoot + "/test_dir2"; fs.mkdir(root2, 777, function(err) { assert.equal(err, null); assert.equal(fs.existsSync(root2), true); fs.rmdir(root2, function() { assert.equal(fs.existsSync(root2), false); }); // Run read-only directory test only on linux and Tizen // NuttX does not support read-only attribute. if (process.platform === 'linux' || process.platform === 'tizen') { var testMode = '0444'; fs.mkdir(root, testMode, function(err) { assert.equal(err, null); assert.equal(fs.existsSync(root), true); var mode = fs.statSync(root).mode; assert.strictEqual(mode.toString(8).slice(-4), testMode); fs.rmdir(root, function() { assert.equal(fs.existsSync(root), false); }); }); } }); }); }); } iotjs-1.0+715/test/run_pass/test_fs_open_close.js000066400000000000000000000101431371177304000220400ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var fileName = process.cwd() + '/resources/greeting.txt'; // test sync open & close. // test normal sequence. assert.doesNotThrow(function() { var fd = fs.openSync(fileName, 'r'); assert.notEqual(fs, null, 'Error opening file: ' + fileName); fs.closeSync(fd); }, 'Test normal sequence. Open file for reading'); // test trying to open not exist file - expecting exception. assert.throws(function() { var fd = fs.openSync('not_exist_file', 'r'); }, Error, 'Test trying to openSync not exist file - expecting exception'); // test trying to close with bad fd - expecting exception. assert.throws(function() { fs.closeSync(-1); }, Error, 'Test trying to close with bad fd - expecting exception'); // test async open & close. // test normal sequence. fs.open(fileName, 'r', function(err, fd) { assert.equal(err, null, 'Async Normal: Error opening ' + fileName + ': ' + err); fs.close(fd, function(err) { assert.equal(err, null, 'Async Normal: Error closing ' + fileName + ': ' + err); }); }); // test not exist file - expecting exception. fs.open('not_exist_file', 'r', function(err, fd) { assert.notEqual(err, null, 'Test not exist file - expecting exception'); }); // test trying to close with bad fd - expecting exception. fs.close(-1, function(err) { assert.notEqual(err, null, 'Test trying to close with bad fd - expecting exception'); }); { var buffer = new Buffer(10); // expect length out of bound assert.throws(function () { fs.readSync(5, buffer, 0, 20); }, RangeError, 'Expect length out of bound 0, 20'); // expect offset out of bound assert.throws(function () { fs.readSync(5, buffer, -1, 20); }, RangeError, 'Expect length out of bound -1, 20'); } fs.open(fileName, 'r', '4' , function(err, fd) { assert.equal(err, null, 'Async Normal2: Error opening ' + fileName + ': ' + err); fs.close(fd, function(err) { assert.equal(err, null, 'Async Normal2: Error closing ' + fileName + ': ' + err); }); }); assert.throws(function() { var fd = fs.openSync(null, 123); }, TypeError, 'Calling fs.openSync with null file path'); assert.throws(function() { var fd = fs.openSync(process.cwd() + '/run_pass/test_fs_stat.js', 'k'); }, TypeError, 'Calling fs.openSync with invalid flag'); assert.throws(function() { var fd = fs.openSync(process.cwd() + '/resources/test2.txt', null); }, TypeError, 'Calling fs.openSync with null flag'); var testRoot = process.cwd() + '/resources'; var readFile = testRoot + '/test2.txt'; // TizenRT tests are performed from ROM // Files should be stored in other path if (process.platform === 'tizenrt') { testRoot = '/mnt'; readFile = testRoot + '/test2.txt'; // Create file for read test fs.closeSync(fs.openSync(readFile, 'w')); } ('rs sr r+ rs+ sr+ a a+') .split(' ').forEach(function (flag) { assert.doesNotThrow(function () { var fd = fs.openSync(readFile, flag); fs.closeSync(fd); }, 'File could not be opened with flag: ' + flag); }); // Cleanup after test if (process.platform === 'tizenrt') { fs.unlinkSync(readFile); } ('wx xw w+ wx+ xw+ ax+ xa+ ax xa') .split(' ').forEach(function (flag) { assert.doesNotThrow(function() { var file = testRoot + '/TEMP' + flag + '.txt'; var fd = fs.openSync(file, flag); fs.closeSync(fd); fs.unlinkSync(file); }, 'File could not be opened with flag: ' + flag); }); iotjs-1.0+715/test/run_pass/test_fs_open_read.js000066400000000000000000000033651371177304000216560ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var fileName = process.cwd() + "/resources/greeting.txt"; var expectedContents = "Hello IoT.js!!"; var flags = "r"; var mode = 438; // test async open & read fs.open(fileName, flags, mode, function(err, fd) { if (err) { throw err; } else { var buffer = new Buffer(64); fs.read(fd, buffer, 0, buffer.length, 0, function(err, bytesRead, buffer) { if (err) { throw err; } else { assert.equal(buffer.toString(), expectedContents); } }); } }); // error test assert.throws( function() { fs.openSync("non_exist_file", flags, mode); }, Error ); // test the position argument of fs.read() fs.open(fileName, flags, function(err, fd) { if (err) { throw err; } var buffer = new Buffer(64); fs.read(fd, buffer, 0, 7, null, function(err, bytesRead, buffer) { if (err) { throw err; } fs.read(fd, buffer, 7, 7, null, function(err, bytesRead, buffer) { if (err) { throw err; } assert.equal(buffer.toString(), expectedContents); fs.closeSync(fd); }); }); }); iotjs-1.0+715/test/run_pass/test_fs_open_read_sync_1.js000066400000000000000000000033351371177304000231270ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var srcFilePath = process.cwd() + "/resources/test1.txt"; var dstFilePath = process.cwd() + "/tmp/test_fs1.txt"; // TizenRT tests are performed from ROM // Files should be stored in other path if (process.platform === 'tizenrt') { dstFilePath = "/mnt/test_fs1.txt"; } try { var fd1 = fs.openSync(srcFilePath, 'r'); var buffer = new Buffer(128); var bytes1 = fs.readSync(fd1, buffer, 0, buffer.length, 0); fs.closeSync(fd1); var fd2 = fs.openSync(dstFilePath, 'w'); var bytes2 = fs.writeSync(fd2, buffer, 0, bytes1, 0); var bytes4 = fs.writeSync(fd2, buffer, 0, bytes1, null); var bytes5 = fs.writeSync(fd2, buffer, 0, bytes1, undefined); fs.closeSync(fd2); assert.equal(bytes1, bytes2); assert.equal(bytes1, bytes4); assert.equal(bytes1, bytes5); var fd3 = fs.openSync(srcFilePath, 'r'); var bytes3 = fs.readSync(fd3, buffer, 0, buffer.length, 0); fs.closeSync(fd3); assert.equal(bytes1, bytes3); var result = 'TEST File Read & Write\n'; assert.equal(buffer.toString(), result); } catch (err) { throw err; } iotjs-1.0+715/test/run_pass/test_fs_open_read_sync_2.js000066400000000000000000000020611371177304000231230ustar00rootroot00000000000000/* 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 assert = require('assert'); var fileName = process.cwd() + "/resources/greeting.txt"; var expectedContents = "Hello IoT.js!!"; var flags = "r"; var mode = 438; // test sync open & read try { var fd = fs.openSync(fileName, flags, mode); var buffer = new Buffer(64); fs.readSync(fd, buffer, 0, buffer.length, 0); assert.equal(buffer.toString(), expectedContents); } catch (err) { throw err; } iotjs-1.0+715/test/run_pass/test_fs_open_read_sync_3.js000066400000000000000000000021761371177304000231330ustar00rootroot00000000000000/* 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 assert = require('assert'); var fileName = process.cwd() + "/resources/greeting.txt"; var expectedContents = "Hello IoT.js!!"; var flags = "r"; // test the position argument of fs.readSync() try { var buffer = new Buffer(64); var fd = fs.openSync(fileName, flags); var bytes1 = fs.readSync(fd, buffer, 0, 7, null); var bytes2 = fs.readSync(fd, buffer, 7, 7, null); assert.equal(buffer.toString(), expectedContents); fs.closeSync(fd); } catch (err) { throw err; } iotjs-1.0+715/test/run_pass/test_fs_read_stream.js000066400000000000000000000055311371177304000222050ustar00rootroot00000000000000/* Copyright 2018-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 assert = require('assert'); if (fs.createReadStream === undefined || fs.createWriteStream === undefined) { process.exit(0); } var inputFile = process.cwd() + '/resources/tobeornottobe.txt'; var res; var expected = "To be, or not to be, that is the Question:\n" + "Whether ’tis Nobler in the mind to Å¿uffer\n" + "The Slings and Arrows of outragious Fortune,\n" + "Or to take Armes against a Sea of troubles,\n" + "And by opposing end them: to dye, to Å¿leepe\n" + "No more; and by a sleep, to say we end\n" + "The Heart-ake, and the thouÅ¿and Naturall Å¿hockes\n" + 'That Flesh is there too? "Tis a consummation\n' + "Deuoutly to be wiÅ¿h'd. To dye to sleepe,\n" + "To sleep, perchance to Dream; I, there's the rub,\n" + "For in that sleep of death, what dreams may come,\n" + "When we haue Å¿hufflel’d off this mortall coile,\n" + "MuÅ¿t giue us pause. There's the respect\n" + "That makes Calamity of long life:\n" + "For who would beare the Whips and Scornes of time,\n" + "The Oppreſſors wrong, the poore mans Contumely,\n" + "The pangs of diÅ¿priz’d Loue, the Lawes delay,\n" + "The inÅ¿olence of Office, and the Spurnes\n" + "That patient merit of the vnworthy takes,\n" + "When he himÅ¿elfe might his Quietus make\n" + "With a bare Bodkin? Who would theÅ¿e Fardles beare\n" + "To grunt and Å¿weat vnder a weary life,\n" + "But that the dread of Å¿omething after death,\n" + "The vndiÅ¿couered Countrey, from whoÅ¿e Borne\n" + "No Traueller returnes, Puzels the will,\n" + "And makes vs rather beare those illes we haue,\n" + "Then flye to others that we know not of.\n" + "Thus ConÅ¿cience does make Cowards of vs all,\n" + "And thus the Natiue hew of Resolution\n" + "Is Å¿icklied o’re, with the pale caÅ¿t of Thought,\n" + "And enterprizes of great pith and moment,\n" + "With this regard their Currants turne away,\n" + "And looÅ¿e the name of Action. Soft you now,\n" + "The faire Ophelia? Nimph, in thy Orizons\n" + "Be all my Å¿innes remembred."; var readableFileStream = fs.createReadStream(inputFile); readableFileStream.on('data', function(data) { res = data; }); process.on('exit', function() { assert.equal(res, expected); }); iotjs-1.0+715/test/run_pass/test_fs_readdir.js000066400000000000000000000023331371177304000213260ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var path = process.cwd() + '/resources/readdir' var ans = 'DO_NOT_MODIFY_THIS_FOLDER\n'+ 'This_is_a_directory\n'+ 'This_is_another_directory\n'+ 'regular.txt\n'; var res; var items, i; res = ""; items = fs.readdirSync(path); items.sort(); for (i = 0; i < items.length; i++) res += items[i] + '\n'; assert.equal(res, ans); res = ""; fs.readdir(path, function(err, items) { assert.equal(err, null); items.sort(); for (i = 0; i < items.length; i++) res += items[i] + '\n'; assert.equal(res, ans); }); iotjs-1.0+715/test/run_pass/test_fs_readfile.js000066400000000000000000000052241371177304000214710ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var filePath = process.cwd() + "/resources/tobeornottobe.txt"; fs.readFile(filePath, function(err, data) { assert.equal(err, null); var result = "To be, or not to be, that is the Question:\n" + "Whether ’tis Nobler in the mind to Å¿uffer\n" + "The Slings and Arrows of outragious Fortune,\n" + "Or to take Armes against a Sea of troubles,\n" + "And by opposing end them: to dye, to Å¿leepe\n" + "No more; and by a sleep, to say we end\n" + "The Heart-ake, and the thouÅ¿and Naturall Å¿hockes\n" + 'That Flesh is there too? "Tis a consummation\n' + "Deuoutly to be wiÅ¿h'd. To dye to sleepe,\n" + "To sleep, perchance to Dream; I, there's the rub,\n" + "For in that sleep of death, what dreams may come,\n" + "When we haue Å¿hufflel’d off this mortall coile,\n" + "MuÅ¿t giue us pause. There's the respect\n" + "That makes Calamity of long life:\n" + "For who would beare the Whips and Scornes of time,\n" + "The Oppreſſors wrong, the poore mans Contumely,\n" + "The pangs of diÅ¿priz’d Loue, the Lawes delay,\n" + "The inÅ¿olence of Office, and the Spurnes\n" + "That patient merit of the vnworthy takes,\n" + "When he himÅ¿elfe might his Quietus make\n" + "With a bare Bodkin? Who would theÅ¿e Fardles beare\n" + "To grunt and Å¿weat vnder a weary life,\n" + "But that the dread of Å¿omething after death,\n" + "The vndiÅ¿couered Countrey, from whoÅ¿e Borne\n" + "No Traueller returnes, Puzels the will,\n" + "And makes vs rather beare those illes we haue,\n" + "Then flye to others that we know not of.\n" + "Thus ConÅ¿cience does make Cowards of vs all,\n" + "And thus the Natiue hew of Resolution\n" + "Is Å¿icklied o’re, with the pale caÅ¿t of Thought,\n" + "And enterprizes of great pith and moment,\n" + "With this regard their Currants turne away,\n" + "And looÅ¿e the name of Action. Soft you now,\n" + "The faire Ophelia? Nimph, in thy Orizons\n" + "Be all my Å¿innes remembred." assert.equal(data, result); }); iotjs-1.0+715/test/run_pass/test_fs_readfile_sync.js000066400000000000000000000051541371177304000225270ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var filePath = process.cwd() + "/resources/tobeornottobe.txt"; var data = fs.readFileSync(filePath); var result = "To be, or not to be, that is the Question:\n" + "Whether ’tis Nobler in the mind to Å¿uffer\n" + "The Slings and Arrows of outragious Fortune,\n" + "Or to take Armes against a Sea of troubles,\n" + "And by opposing end them: to dye, to Å¿leepe\n" + "No more; and by a sleep, to say we end\n" + "The Heart-ake, and the thouÅ¿and Naturall Å¿hockes\n" + 'That Flesh is there too? "Tis a consummation\n' + "Deuoutly to be wiÅ¿h'd. To dye to sleepe,\n" + "To sleep, perchance to Dream; I, there's the rub,\n" + "For in that sleep of death, what dreams may come,\n" + "When we haue Å¿hufflel’d off this mortall coile,\n" + "MuÅ¿t giue us pause. There's the respect\n" + "That makes Calamity of long life:\n" + "For who would beare the Whips and Scornes of time,\n" + "The Oppreſſors wrong, the poore mans Contumely,\n" + "The pangs of diÅ¿priz’d Loue, the Lawes delay,\n" + "The inÅ¿olence of Office, and the Spurnes\n" + "That patient merit of the vnworthy takes,\n" + "When he himÅ¿elfe might his Quietus make\n" + "With a bare Bodkin? Who would theÅ¿e Fardles beare\n" + "To grunt and Å¿weat vnder a weary life,\n" + "But that the dread of Å¿omething after death,\n" + "The vndiÅ¿couered Countrey, from whoÅ¿e Borne\n" + "No Traueller returnes, Puzels the will,\n" + "And makes vs rather beare those illes we haue,\n" + "Then flye to others that we know not of.\n" + "Thus ConÅ¿cience does make Cowards of vs all,\n" + "And thus the Natiue hew of Resolution\n" + "Is Å¿icklied o’re, with the pale caÅ¿t of Thought,\n" + "And enterprizes of great pith and moment,\n" + "With this regard their Currants turne away,\n" + "And looÅ¿e the name of Action. Soft you now,\n" + "The faire Ophelia? Nimph, in thy Orizons\n" + "Be all my Å¿innes remembred." assert.equal(data, result); iotjs-1.0+715/test/run_pass/test_fs_rename.js000066400000000000000000000031741371177304000211670ustar00rootroot00000000000000/* 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. */ /* @STDOUT=Pass */ var fs = require('fs'); var assert = require('assert'); var file1 = process.cwd() + '/resources/rename.txt'; var file2 = process.cwd() + '/resources/rename.txt.async'; // TizenRT tests are performed from ROM // Files should be stored in other path if (process.platform === 'tizenrt') { file1 = '/mnt/rename.txt'; file2 = '/mnt/rename.txt.sync'; fs.closeSync(fs.openSync(file1, 'w')); } assert.equal(fs.existsSync(file1), true, 'Test prerequisites: checking existance of ' + file1); fs.rename(file1, file2, function(err) { assert.equal(err, null, 'Rename error:' + err); assert.equal(fs.existsSync(file1), false, 'Source file exist after renaming'); assert.equal(fs.existsSync(file2), true, 'Destination file not exist after renaming'); fs.rename(file2, file1, function(err) { assert.equal(err, null, 'Renaming back error: ' + err); // Cleanup after test if (process.platform === 'tizenrt') { fs.unlinkSync(file1); } }); }); iotjs-1.0+715/test/run_pass/test_fs_rename_sync.js000066400000000000000000000026761371177304000222310ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var file1 = process.cwd() + '/resources/rename.txt'; var file2 = process.cwd() + '/resources/rename.txt.sync'; // TizenRT tests are performed from ROM // Files should be stored in other path if (process.platform === 'tizenrt') { file1 = '/mnt/rename.txt'; file2 = '/mnt/rename.txt.sync'; fs.closeSync(fs.openSync(file1, 'w')); } assert.equal(fs.existsSync(file1), true, 'Test prerequisites: checking existance of ' + file1); fs.renameSync(file1, file2); assert.equal(fs.existsSync(file1), false, 'Source file exist after renaming'); assert.equal(fs.existsSync(file2), true, 'Destination file not exist after renaming'); fs.renameSync(file2, file1); // Cleanup after test if (process.platform === 'tizenrt') { fs.unlinkSync(file1); } iotjs-1.0+715/test/run_pass/test_fs_stat.js000066400000000000000000000032061371177304000206670ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var stats1 = fs.statSync(process.cwd() + '/run_pass/test_fs_stat.js'); assert.equal(stats1.isFile(), true); assert.equal(stats1.isDirectory(), false); fs.stat(process.cwd() + '/run_pass/test_fs_stat.js', function(err, stats) { if (!err) { assert.equal(stats.isFile(), true); assert.equal(stats.isDirectory(), false); } else { throw err; } }); var stats2 = fs.statSync(process.cwd() + '/resources'); assert.equal(stats2.isDirectory(), true); assert.equal(stats2.isFile(), false); fs.stat(process.cwd() + '/resources', function(err, stats) { if (!err) { assert.equal(stats.isDirectory(), true); assert.equal(stats.isFile(), false); } else { throw err } }); // fs.statSync throws an exception for a non-existing file. try { var stats3 = fs.statSync(process.cwd() + '/non_existing.js'); assert.assert(false); } catch(e) { assert.equal(e instanceof Error, true); assert.equal(e instanceof assert.AssertionError, false); } iotjs-1.0+715/test/run_pass/test_fs_stream_pipe.js000066400000000000000000000041401371177304000222220ustar00rootroot00000000000000/* Copyright 2018-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 assert = require('assert'); if (fs.createReadStream === undefined || fs.createWriteStream === undefined) { process.exit(0); } var inputFileName = process.cwd() + '/resources/tobeornottobe.txt'; var outputFileName = process.cwd() + '/tmp/test_fs4.txt'; var buff1 = new Buffer(2048); var buff2 = new Buffer(2048); // Get the correct content of the input for later checking. fs.open(inputFileName, 'r', 0666, function(err, fd) { if (err) { throw err; } fs.read(fd, buff1, 0, buff1.length, 0, function(err, bytesRead, buffer) { if (err) { throw err; } fs.close(fd, onclose); }); }); function onclose(err) { if (err) { throw err; } var readableFileStream = fs.createReadStream(inputFileName); var writableFileStream = fs.createWriteStream(outputFileName); writableFileStream.on('ready', function() { readableFileStream.pipe(writableFileStream); }); writableFileStream.on('close', check_output); } function check_output() { // Read the output for checking. fs.open(outputFileName, 'r', function(err, fd) { if (err) { throw err; } fs.read(fd, buff2, 0, buff2.length, 0, function(err, bytesRead, buffer) { if (err) { throw err; } fs.close(fd, function(err) { if (err) { throw err; } }) }); }); } process.on('exit', function() { assert.equal(buff1.toString(), buff2.toString(), 'File contents do not match'); }); iotjs-1.0+715/test/run_pass/test_fs_write.js000066400000000000000000000032421371177304000210460ustar00rootroot00000000000000/* 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 assert = require('assert'); var dstFilePath = process.cwd() + '/tmp/test_fs3.txt'; if (process.platform === 'tizenrt') { dstFilePath = '/mnt/test_fs3.txt'; } var buff1 = new Buffer('IoT'); var buff2 = new Buffer('.js'); fs.open(dstFilePath, 'w+', function(err, fd) { if (err) { throw err; } // Test the position argument of fs.write(). fs.write(fd, buff1, 0, buff1.length, undefined, function(err, bytes, buffer) { if (err) { throw err; } fs.write(fd, buff2, 0, buff2.length, null, function(err, bytes, buffer) { if (err) { throw err; } // Check the result. var result = new Buffer(6); fs.read(fd, result, 0, result.length, 0, function(err, bytes, buffer) { if (err) { throw err; } var init_buffers = Buffer.concat([buff1, buff2]); assert.assert(result.equals(init_buffers)); fs.close(fd, function(err) { if (err) { throw err; } }); }); }); }); }); iotjs-1.0+715/test/run_pass/test_fs_write_stream.js000066400000000000000000000031101371177304000224130ustar00rootroot00000000000000/* Copyright 2018-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 assert = require('assert'); if (fs.createReadStream === undefined || fs.createWriteStream === undefined) { process.exit(0); } var dir = (process.platform === 'tizenrt') ? '/mnt/' : process.cwd() + '/tmp/'; var outputFile = dir + 'test_fs5.txt'; var testData = 'WriteStream test'; var writableFileStream = fs.createWriteStream(outputFile); writableFileStream.on('ready', function() { writableFileStream.write(testData); }); var buff = new Buffer(64); writableFileStream.on('close', function() { // Check output correctness fs.open(outputFile, 'r', 0666, function(err, fd) { if (err) { throw err; } fs.read(fd, buff, 0, buff.length, 0, function(err, bytesRead, buffer) { if (err) { throw err; } assert.equal(buff.toString(), testData, 'Incorrect data in output file'); fs.close(fd, function(err) { if (err) { throw err; } }); }); }) }); iotjs-1.0+715/test/run_pass/test_fs_writefile.js000066400000000000000000000033031371177304000217040ustar00rootroot00000000000000/* 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. */ /* @STDOUT=Pass */ var fs = require('fs'); var assert = require('assert'); var file = process.cwd() + '/resources/test'; var buff1 = new Buffer('test string1'); var str = 'test string2'; var num = 1; if (process.platform === 'tizenrt') { file = '/mnt/test'; } fs.writeFile(file, buff1, function (err) { assert.equal(err, null); fs.readFile(file, function (err, buff2) { assert.equal(err, null); assert.equal(buff2.equals(buff1), true); fs.writeFile(file, str, function (err) { assert.equal(err, null); fs.readFile(file, function (err, buff2) { assert.equal(err, null); assert.equal(str.valueOf(), buff2.toString('utf8')); fs.writeFile(file, num, function (err) { assert.equal(err, null); fs.readFile(file, function (err, buff2) { assert.equal(err, null); assert.equal(num, parseInt(buff2.toString('utf8'), 10)); console.log('Pass'); fs.unlinkSync(file); }); }); }); }); }); }); iotjs-1.0+715/test/run_pass/test_fs_writefile_sync.js000066400000000000000000000024351371177304000227450ustar00rootroot00000000000000/* 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. */ /* @STDOUT=Pass */ var fs = require('fs'); var assert = require('assert'); var file = process.cwd() + '/resources/test'; var buff1 = new Buffer('test string1'); var buff2 = null; var str = 'test string2'; var num = 1; if (process.platform === 'tizenrt') { file = '/mnt/test'; } fs.writeFileSync(file, buff1); buff2 = fs.readFileSync(file); assert.equal(buff2.equals(buff1), true); fs.writeFileSync(file, str); buff2 = fs.readFileSync(file); assert.equal(str.valueOf(), buff2.toString('utf8')); fs.writeFileSync(file, num); buff2 = fs.readFileSync(file); assert.equal(num, parseInt(buff2.toString('utf8'), 10)); console.log('Pass'); fs.unlinkSync(file); iotjs-1.0+715/test/run_pass/test_fs_writefile_unlink.js000066400000000000000000000027741371177304000232770ustar00rootroot00000000000000/* 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. */ /* @STDOUT=Pass */ var fs = require('fs'); var assert = require('assert'); var file1 = process.cwd() + '/resources/tobeornottobe.txt'; var file2 = process.cwd() + '/resources/tobeornottobe_async.txt'; if (process.platform === 'tizenrt') { file2 = '/mnt/tobeornottobe_sync.txt'; } fs.readFile(file1, function(err, buf1) { assert.equal(err, null); fs.writeFile(file2, buf1, function(err) { assert.equal(err, null); fs.exists(file2, function(exists) { assert.equal(exists, true); fs.readFile(file1, function(err, buf2) { assert.equal(err, null); assert.equal(buf1.toString(), buf2.toString()); fs.unlink(file2, function(err) { assert.equal(err, null); fs.exists(file2, function(exists) { assert.equal(exists, false); console.log("Pass"); }); }); }); }); }); }); iotjs-1.0+715/test/run_pass/test_fs_writefile_unlink_sync.js000066400000000000000000000024631371177304000243260ustar00rootroot00000000000000/* 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 fs = require('fs'); var assert = require('assert'); var file1 = process.cwd() + '/resources/tobeornottobe.txt'; var file2 = process.cwd() + '/resources/tobeornottobe_sync.txt'; if (process.platform === 'tizenrt') { file2 = '/mnt/tobeornottobe_sync.txt'; } /* make a new file2 from file1 */ var buf1 = fs.readFileSync(file1); fs.writeFileSync(file2, buf1); /* Does file2 exists ? */ var result = fs.existsSync(file2); assert.equal(result, true); /* Is file2 equal to file1 */ var buf2 = fs.readFileSync(file2); assert(buf1.toString(), buf2.toString()); /* Remove file2 */ fs.unlinkSync(file2); /* Is file2 removed? */ result = fs.existsSync(file2); assert.equal(result, false); iotjs-1.0+715/test/run_pass/test_gpio_api.js000066400000000000000000000173671371177304000210300ustar00rootroot00000000000000/* Copyright 2018-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 gpio = require('gpio'); // ------ Test API existance assert.assert(gpio.DIRECTION, 'gpio module does not provide \'DIRECTION\' property'); assert.notEqual(gpio.DIRECTION.IN, undefined); assert.notEqual(gpio.DIRECTION.OUT, undefined); assert.assert(gpio.EDGE, 'gpio module does not provide \'EDGE\' property'); assert.notEqual(gpio.EDGE.NONE, undefined); assert.notEqual(gpio.EDGE.RISING, undefined); assert.notEqual(gpio.EDGE.FALLING, undefined); assert.notEqual(gpio.EDGE.BOTH, undefined); assert.assert(gpio.MODE, 'gpio module does not provide \'MODE\' property'); assert.notEqual(gpio.MODE.NONE, undefined); if (process.platform === 'nuttx') { assert.notEqual(gpio.MODE.PULLUP, undefined); assert.notEqual(gpio.MODE.PULLDOWN, undefined); assert.notEqual(gpio.MODE.FLOAT, undefined); assert.notEqual(gpio.MODE.PUSHPULL, undefined); assert.notEqual(gpio.MODE.OPENDRAIN, undefined); } assert.equal(typeof gpio.open, 'function', 'gpio does not provide \'open\' function'); assert.equal(typeof gpio.openSync, 'function', 'gpio does not provide \'openSync\' function'); function check_gpiopin(gpiopin) { assert.equal(typeof pin.setDirectionSync, 'function', '\'gpiopin\' does not provide \'setDirectionSync\' function'); assert.equal(typeof pin.write, 'function', '\'gpiopin\' does not provide \'write\' function'); assert.equal(typeof pin.writeSync, 'function', '\'gpiopin\' does not provide \'writeSync\' function'); assert.equal(typeof pin.read, 'function', '\'gpiopin\' does not provide \'read\' function'); assert.equal(typeof pin.readSync, 'function', '\'gpiopin\' does not provide \'readSync\' function'); assert.equal(typeof pin.close, 'function', '\'gpiopin\' does not provide \'close\' function'); assert.equal(typeof pin.closeSync, 'function', '\'gpiopin\' does not provide \'closeSync\' function'); } // ------ Test synchronous GPIO pin opening assert.throws( function() { gpio.openSync({pin: 0, direction: 123}); }, TypeError ); assert.throws( function() { gpio.openSync({pin: 0, direction: {}}); }, TypeError ); assert.throws( function() { gpio.openSync({pin: 0, direction: 'out'}); }, TypeError ); assert.throws( function() { gpio.openSync({pin: 0, edge: 123}); }, TypeError ); assert.throws( function() { gpio.openSync({pin: 0, edge: {}}); }, TypeError ); assert.throws( function() { gpio.openSync({pin: 0, edge: 'rising'}); }, TypeError ); assert.throws( function() { gpio.openSync({pin: '12'}); }, TypeError ); assert.throws( function() { gpio.openSync({pin: {}}); }, TypeError ); assert.throws( function() { gpio.openSync({pin: -12}); }, TypeError ); var pin = gpio.openSync({pin: 0, direction: gpio.DIRECTION.OUT}); check_gpiopin(pin); pin.closeSync(); assert.throws( // close twice function() { pin.closeSync(); }, Error ); pin = gpio.openSync({pin: 0, direction: gpio.DIRECTION.IN}); check_gpiopin(pin); pin.closeSync(); pin = gpio.openSync({pin: 0}); check_gpiopin(pin); assert.doesNotThrow(function() { pin.setDirectionSync(gpio.DIRECTION.OUT) }); assert.throws( function() { pin.setDirectionSync(123); }, TypeError ); assert.throws( function() { pin.setDirectionSync('out'); }, Error ); assert.throws( function() { pin.setDirectionSync({}); }, Error ); assert.doesNotThrow( function() { pin.writeSync(true); pin.writeSync(false); pin.writeSync(0); pin.writeSync(1); pin.writeSync(123); pin.writeSync(-123); } ); assert.doesNotThrow( function() { pin.write(true, function(err) { assert.assert(err === null, 'gpio.write failed: ' + err); write_cb1 = true; }); pin.write(false, function(err) { assert.assert(err === null, 'gpio.write failed: ' + err); write_cb2 = true; }); pin.write(0, function(err) { assert.assert(err === null, 'gpio.write failed: ' + err); write_cb3 = true; }); pin.write(1, function(err) { assert.assert(err === null, 'gpio.write failed: ' + err); write_cb4 = true; }); pin.write(123, function(err) { assert.assert(err === null, 'gpio.write failed: ' + err); write_cb5 = true; }); pin.write(-123, function(err) { assert.assert(err === null, 'gpio.write failed: ' + err); write_cb6 = true; }); } ); assert.throws( function() { pin.writeSync('true'); }, Error ); assert.throws( function() { pin.writeSync({}); }, Error ); assert.throws( function() { gpio.write({}); }, Error ); assert.throws( function() { gpio.write('true'); }, Error ); pin.write('true', function(err) { assert.assert(err, 'gpio.write did not fail as expected'); }); pin.write({}, function(err) { assert.assert(err, 'gpio.write did not fail as expected'); }); // ------ Test asynchronous GPIO pin opening var async_pin1 = gpio.open( { pin: 20, direction: gpio.DIRECTION.OUT }, function(err, async_pin2) { open_cb1 = true; assert.assert(err === null, 'gpio.open failed: ' + err); assert.assert(async_pin1); assert.assert(async_pin2); assert.assert(async_pin1 === async_pin2, 'return value and callback parameters are not equal'); check_gpiopin(async_pin2); async_pin2.close(function(err) { close_cb1 = true; assert.assert(err === null, 'gpio.close failed: ' + err); }); } ); gpio.open( { pin: 21, direction: gpio.DIRECTION.IN }, function(err, async_pin) { open_cb2 = true; assert.assert(err === null, 'gpio.open failed: ' + err); check_gpiopin(async_pin); async_pin.close(function(err) { close_cb2 = true; assert.assert(err === null, 'gpio.close failed: ' + err); }); } ); gpio.open( { pin: 22 }, function(err, async_pin) { open_cb3 = true; assert.assert(err === null, 'gpio.open failed: ' + err); check_gpiopin(async_pin); async_pin.close(function(err) { close_cb3 = true; assert.assert(err === null, 'gpio.close failed: ' + err); }); } ); process.on('exit', function(code) { if (code === 0) { assert.assert(open_cb1, 'callback of \'gpio.open\' was not called'); assert.assert(close_cb1, 'callback of \'gpio.close\' was not called'); assert.assert(open_cb2, 'callback of \'gpio.open\' was not called'); assert.assert(close_cb2, 'callback of \'gpio.close\' was not called'); assert.assert(open_cb3, 'callback of \'gpio.open\' was not called'); assert.assert(close_cb3, 'callback of \'gpio.close\' was not called'); assert.assert(write_cb1, 'callback of \'gpio.write\' was not called'); assert.assert(write_cb2, 'callback of \'gpio.write\' was not called'); assert.assert(write_cb3, 'callback of \'gpio.write\' was not called'); assert.assert(write_cb4, 'callback of \'gpio.write\' was not called'); assert.assert(write_cb5, 'callback of \'gpio.write\' was not called'); assert.assert(write_cb6, 'callback of \'gpio.write\' was not called'); } pin.closeSync(); }); iotjs-1.0+715/test/run_pass/test_gpio_direction.js000066400000000000000000000023671371177304000222310ustar00rootroot00000000000000/* Copyright 2018-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('tools/systemio_common').pin; var gpioPin = gpio.openSync({ pin: pin.led, direction: gpio.DIRECTION.OUT, }); console.log('GPIO input test. Press the button.'); gpioPin.setDirectionSync(gpio.DIRECTION.IN); var loop = setInterval(function() { var value = gpioPin.readSync(); console.log('GpioPin value:', value); }, 500); setTimeout(function() { clearInterval(loop); console.log('GPIO output test. Led is on for 5000ms.'); gpioPin.setDirectionSync(gpio.DIRECTION.OUT); gpioPin.writeSync(1); setTimeout(function() { gpioPin.writeSync(0); }, 5000); }, 5000); iotjs-1.0+715/test/run_pass/test_gpio_event.js000066400000000000000000000022641371177304000213660ustar00rootroot00000000000000/* 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 testGpioInfo = [ { pin: 13, edge: gpio.EDGE.RISING }, { pin: 19, edge: gpio.EDGE.FALLING }, { pin: 26, edge: gpio.EDGE.BOTH } ]; testGpioInfo.forEach(function(info) { var switchGpio = gpio.open({ pin: info.pin, edge: info.edge, direction: gpio.DIRECTION.IN }, function() { switchGpio.on('change', function() { console.log('pin:', info.pin, ', current value:', switchGpio.readSync()); }); }); }); setTimeout(function(){ console.log('finish test'); }, 10000); iotjs-1.0+715/test/run_pass/test_gpio_input.js000066400000000000000000000032541371177304000214040ustar00rootroot00000000000000/* 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 assert = require('assert'); var gpio = require('gpio'); var pin = require('tools/systemio_common').pin; var checkError = require('tools/systemio_common').checkError; var ledGpio = null, switchGpio = null; var SWITCH_ON = false, LED_ON = true, LED_OFF = false; var loopCnt = 0; ledGpio = gpio.open({ pin: pin.led, direction: gpio.DIRECTION.OUT, }, function(err) { checkError(err); ledGpio.writeSync(LED_OFF); }); switchGpio = gpio.openSync({ pin: pin.switch, direction: gpio.DIRECTION.IN }); var loop = setInterval(function() { if (!ledGpio || !switchGpio) { return; } if ((++loopCnt) == 10) { clearInterval(loop); ledGpio.closeSync(); switchGpio.closeSync(); ledGpio = switchGpio = null; console.log('finish test'); return; } switchGpio.read(function(err, value) { if (err) { clearInterval(loop); assert.fail(); } if (value === SWITCH_ON) { console.log('led on'); ledGpio.writeSync(LED_ON); } else { ledGpio.writeSync(LED_OFF); } }); }, 500); iotjs-1.0+715/test/run_pass/test_gpio_output.js000066400000000000000000000044501371177304000216040ustar00rootroot00000000000000/* 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 assert = require('assert'); var gpio = require('gpio'); var pin = require('tools/systemio_common').pin; var checkError = require('tools/systemio_common').checkError; var LED_ON = true, LED_OFF = false; var gpio20; test1(); gpio20 = gpio.open({ pin: pin.led, direction: gpio.DIRECTION.OUT, }, test2); function test1() { // Check gpio.DIRECTION assert.notEqual(gpio.DIRECTION.IN, undefined); assert.notEqual(gpio.DIRECTION.OUT, undefined); // Check gpio.MODE assert.notEqual(gpio.MODE.NONE, undefined); if (process.platform === 'nuttx') { assert.notEqual(gpio.MODE.PULLUP, undefined); assert.notEqual(gpio.MODE.PULLDOWN, undefined); assert.notEqual(gpio.MODE.FLOAT, undefined); assert.notEqual(gpio.MODE.PUSHPULL, undefined); assert.notEqual(gpio.MODE.OPENDRAIN, undefined); } // Check gpio.EDGE assert.notEqual(gpio.EDGE.NONE, undefined); assert.notEqual(gpio.EDGE.RISING, undefined); assert.notEqual(gpio.EDGE.FALLING, undefined); assert.notEqual(gpio.EDGE.BOTH, undefined); } // turn on LED for 3000ms function test2(err) { assert.equal(err, null); gpio20.write(LED_ON, function(writeErr) { checkError(writeErr); console.log('gpio write'); gpio20.read(function(readErr, value) { checkError(readErr); console.log('gpio read:', value); assert.equal(LED_ON, value); setTimeout(function() { gpio20.writeSync(LED_OFF); var value = gpio20.readSync(); console.log('gpio read:', value); assert.equal(LED_OFF, value); gpio20.close(function(closeErr) { checkError(closeErr); console.log('finish test'); }); }, 3000); }); }); } iotjs-1.0+715/test/run_pass/test_http_signature.js000066400000000000000000000046571371177304000222770ustar00rootroot00000000000000/* Copyright 2018-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_sign = require('http_signature'); var assert = require('assert'); var key = fs.readFileSync(process.cwd() + '/resources/http_signature_key.key'); // This is an example request of a Samsung C2C demo var sampleRequest = { "headers": { "Content-Type":"application/json", "Accept":"application/json", "Authorization":"Signature keyId=\"http_signature_key\"," + "signature=\"mJUG2ceYWCGww2tXrVJywQUqQvaWbkWpAx4xSfqZD9Gr" + "G12N8pVysa/nl18kEKe2Sbd00c50qyF/xH5hKtxFyyUYBxY5cOrdt+7W" + "1EmctaGGIDOnZA/qZcXcnTBZsp8k68XI/6HxwIxHVUntAd2vxJvqzibB" + "TZLHAhTRVCoAqHzjHe0kybv5oebbMASaNEhZTLslQYQUOYqVzE+4Ecen" + "Vxrlk2wpjjFjnBdxd/Ek34FTOcWMoPKjpj1ja+hfet2Em8YzF+aeHrBR" + "t7FTt7r/GkYfuwm9M0XYSY1JvnvCKxIU20YXKbZ+KINBaUXDwEKapUvm" + "bDFuLi3arJcDigWIOA==\",headers=\"(request-target) digest" + " date\",algorithm=\"rsa-sha256\"", "Date":"Tue, 28 Aug 2018 15:28:59 UTC", "Digest":"SHA-256=52eIrPP0TxhlUVwnChuVLj6qFmbl5dYdMIvUr+DlZ0A=", "X-ST-CORRELATION":"b7891162-2084-da6e-da84-401be50cd534", "X-B3-TraceId":"fb04fc10f3088f10", "X-B3-SpanId":"c6245b1a3c934a0d", "X-B3-ParentSpanId":"989731b1f545e7d1", "X-B3-Sampled":"1", "content-length":"344", "host":"example.host.com", "user-agent":"AHC/2.1", "X-Forwarded-Proto":"https", "X-Forwarded-For":"52.14.6.245" }, "method": "POST", "url": "/", "httpVersion": "1.1", }; var parsedRequest = http_sign.parseRequest(sampleRequest); assert.equal(http_sign.verifySignature(parsedRequest, key), true); iotjs-1.0+715/test/run_pass/test_i2c_api.js000066400000000000000000000073121371177304000205340ustar00rootroot00000000000000/* Copyright 2018-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 i2c = require('i2c'); // ------ Test API existance assert.equal(typeof i2c.open, 'function', 'i2c does not provide \'open\' function'); assert.equal(typeof i2c.openSync, 'function', 'i2c does not provide \'openSync\' function'); function check_i2cbus(i2cbus) { assert.equal(typeof i2cbus.write, 'function', '\'i2cpin\' does not provide \'write\' function'); assert.equal(typeof i2cbus.writeSync, 'function', '\'i2cpin\' does not provide \'writeSync\' function'); assert.equal(typeof i2cbus.read, 'function', '\'i2cpin\' does not provide \'read\' function'); assert.equal(typeof i2cbus.readSync, 'function', '\'i2cpin\' does not provide \'readSync\' function'); assert.equal(typeof i2cbus.close, 'function', '\'i2cpin\' does not provide \'close\' function'); assert.equal(typeof i2cbus.closeSync, 'function', '\'i2cpin\' does not provide \'closeSync\' function'); } // ------ Test synchronous I2C Bus opening assert.throws( function() { i2c.openSync({address: '0x0'}); }, TypeError ); assert.throws( function() { i2c.openSync('0x0'); }, Error ); assert.throws( function() { i2c.openSync({}); }, TypeError ); var bus = i2c.openSync({address: 0x23}); check_i2cbus(bus); assert.doesNotThrow( function() { bus.writeSync([0x10, 123, -12]); read_result = bus.readSync(5); } ); assert.throws( function() { bus.writeSync(0x23); }, Error ); assert.throws( function() { bus.writeSync(null); }, Error ); assert.throws( function() { bus.readSync('5'); }, Error ); assert.throws( function() { bus.readSync(null); }, Error ); assert.throws( function() { bus.readSync([5]); }, Error ); assert.throws( function() { bus.readSync({}); }, Error ); assert.assert(Array.isArray(read_result)); assert.strictEqual(read_result.length, 5); bus.closeSync(); // ------ Test asynchronous I2C Bus opening i2c.open({address: 0x0}, function(open_err, async_bus) { assert.equal(open_err, null); open_cb1 = true; assert.throws( function() { async_bus.read(null); }, Error ); assert.throws( function() { async_bus.write(null); }, Error ); async_bus.write([0x10, 123, -12], function(write_err) { assert.equal(write_err, null); write_cb1 = true; async_bus.read(5, function(read_err, res) { assert.equal(read_err, null); read_cb1 = true; assert.assert(Array.isArray(res)); assert.strictEqual(res.length, 5); async_bus.close(function(close_err) { assert.equal(close_err, null); close_cb1 = true; }); }); }); }); process.on('exit', function(code) { if (code === 0) { assert.assert(open_cb1, 'callback of \'i2c.open\' was not called'); assert.assert(close_cb1, 'callback of \'i2c.close\' was not called'); assert.assert(read_cb1, 'callback of \'i2cbus.read\' was not called'); assert.assert(write_cb1, 'callback of \'i2cbus.write\' was not called'); } }); iotjs-1.0+715/test/run_pass/test_i2c_gy30.js000066400000000000000000000042571371177304000205520ustar00rootroot00000000000000/* 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. */ /* This should be tested with GY-30 Sensor. * * The following is pin information. * Linux(Raspberry PI2): BCM2(SDA), BCM3(SCL) * NuttX(STM32F4-Discovery): PB7(SDA), PB8(SCL) * TizenRT(Artik053): CON703(10)(SDA), CON703(8)(SCL) - XI2C1 * */ var assert = require('assert'); var pin = require('tools/systemio_common').pin; var checkError = require('tools/systemio_common').checkError; var i2c = require('i2c'); var configuration = { address: 0x23, device: pin.i2c1, // for Linux bus: pin.i2c1, // for TizenRT and NuttX }; syncTest(); function syncTest() { console.log('I2C sync function test'); var wire = i2c.openSync(configuration); var loopCnt = 5; var loop = setInterval(function() { wire.writeSync([0x10]); var res = wire.readSync(2); console.log('read result', (res[1] + (256 * res[0]))); if (--loopCnt <= 0) { clearInterval(loop); wire.closeSync(); asyncTest(); } }, 800); } function asyncTest() { console.log('I2C async function test'); i2c.open(configuration, function(err, wire) { checkError(err); var loopCnt = 5; var loop = setInterval(function() { wire.write([0x10], function(err) { checkError(err); wire.read(2, function(err, res) { checkError(err); assert.equal(res.length, 2, 'I2C read failed.(length is not equal)'); console.log('read result: ', (res[1] + (256 * res[0]))); if (--loopCnt <= 0) { clearInterval(loop); wire.close(); } }); }); }, 800); }); } iotjs-1.0+715/test/run_pass/test_iotjs_promise.js000066400000000000000000000021651371177304000221150ustar00rootroot00000000000000/* 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 fulfill_ret; var p = new Promise(function(resolve, reject) { // mimic asynchronous operation via setTimeout setTimeout(function() { resolve("Resolved") }, 100); }); p.then(function (msg) { // Promise does not like throwing error in fulfill handler // So just set the message in global variable. fulfill_ret = msg; }); // If Promise's fulfill worked well, assertion must be valid. setTimeout(function() { assert.equal(fulfill_ret, "Resolved"); }, 1000); iotjs-1.0+715/test/run_pass/test_iotjs_promise_chain_calls.js000066400000000000000000000036171371177304000244400ustar00rootroot00000000000000/* 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 assert = require('assert'); function readfile(fileName) { return new Promise(function (resolve, reject) { fs.readFile(fileName, function(error, data) { if (error) { reject(new Error('Cannot open file!')); } else { resolve(data.toString()); } }); }); }; function loadfi(files, idx) { var fileName = process.cwd() + '/resources/promise_chain_calls/' + files[idx]; readfile(fileName). then(function(value) { assert.equal(value, 'Content of ' + files[idx] + '\n'); idx++; loadfi(files, idx); }).catch(function (e) { // Note: assert cannot be used here, because exception cannot be thrown // from Promise.prototype.catch if (e.message !== "Cannot open file!") { console.log('Error message does not match. Expected ' + '"Cannot open file!", but got "' + e.message + '".'); process.emitExit(1); } else if (idx !== 4) { console.log('Did not read every file. The expected number of files ' + 'read is "4", but got "' + idx + '".'); process.emitExit(1); } }); }; var files = ['1.txt', '2.txt', '3.txt', '4.txt']; loadfi(files, 0); iotjs-1.0+715/test/run_pass/test_module_cache.js000066400000000000000000000021441371177304000216340ustar00rootroot00000000000000/* 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 assert = require('assert'); var dir = process.cwd() + '/run_pass/require1/'; var dirDoubleDot = dir + '../require1/'; var dirDot = dir + './'; var moduleCache = require(dir + 'module_cache.js'); moduleCache.i = 100; moduleCache = require(dir + 'module_cache.js'); assert.equal(moduleCache.i, 100); moduleCache = require(dirDoubleDot + 'module_cache.js'); assert.equal(moduleCache.i, 100); moduleCache = require(dirDot + 'module_cache.js'); assert.equal(moduleCache.i, 100); iotjs-1.0+715/test/run_pass/test_module_json.js000066400000000000000000000017611371177304000215460ustar00rootroot00000000000000/* 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 json = require(process.cwd() + '/resources/test.json'); assert.equal(json.name, 'IoT.js'); assert.equal(json.author, 'Samsung Electronics Co., Ltd.'); assert.equal(json.license, 'Apache-2.0'); assert.equal(json.number, 123); assert.equal(Array.isArray(json.array), true); assert.equal(json.array.toString(), [1,2,3,4].toString()); iotjs-1.0+715/test/run_pass/test_module_require.js000066400000000000000000000027071371177304000222520ustar00rootroot00000000000000/* 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 assert = require('assert'); var dir = process.cwd() + "/run_pass/require1/"; // Load a JS file. var x = require(dir + "require_add"); assert.equal(x.add(1,4), 5); // Load a package. var pkg1 = require(dir + "test_pkg"); assert.equal(pkg1.add(22, 44), 66); assert.equal(pkg1.multi(22, 44), 968); assert.equal(pkg1.add2(22, 44), 66); var pkg2 = require(dir + "test_index"); assert.equal(pkg2.add(22, 44), 66); assert.equal(pkg2.multi(22, 44), 968); assert.equal(pkg2.add2(22, 44), 66); var pkg3 = require(dir + "test_index2"); assert.equal(pkg3.add(22, 44), 66); assert.equal(pkg3.multi(22, 44), 968); assert.equal(pkg3.add2(22, 44), 66); // Load invalid modules. assert.throws(function() { var test3 = require('run_pass/require1/babel-template'); }, Error); assert.throws(function() { var test4 = require('tmp'); }, Error); iotjs-1.0+715/test/run_pass/test_mqtt.js000066400000000000000000000047251371177304000202200ustar00rootroot00000000000000/* Copyright 2018-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 mqtt = require('mqtt'); var assert = require('assert'); var connected = false; var subscribed = false; // The number of the variable is the qos level (0-2) var msg0 = 'hello iotjs 1'; var msg1 = 'hello iotjs 2'; var msg2 = 'hello iotjs 3'; var published0 = false; var published1 = false; var published2 = false; var received0 = false; var received1 = false; var received2 = false; var subClientOpts = { clientId: 'iotjs-mqtt-test-sub', host: 'test.mosquitto.org', port: 1883, keepalive: 30, }; var pubClientOpts = { clientId: 'iotjs-mqtt-test-pub', port: 1883, keepalive: 30 }; var pubClient; var subClient = mqtt.connect(subClientOpts, function() { connected = true; subClient.subscribe('iotjs-test-topic', { qos:2 }, function() { subscribed = true; pubClient = mqtt.connect('test.mosquitto.org', pubClientOpts, function() { pubClient.publish('iotjs-test-topic', msg0, { qos:0 }, function() { published0 = true; }); pubClient.publish('iotjs-test-topic', msg1, { qos:1 }, function() { published1 = true; }); pubClient.publish('iotjs-test-topic', msg2, { qos:2 }, function() { published2 = true; }); }); }); subClient.on('message', function(data) { var str = data.message.toString(); if (str == msg0) { received0 = true; } if (str == msg1) { received1 = true; } if (str == msg2) { received2 = true; } if (received0 && received1 && received2) { subClient.end(); pubClient.end(); } }); }); process.on('exit', function() { assert.equal(connected, true); assert.equal(subscribed, true); assert.equal(published0, true); assert.equal(published1, true); assert.equal(published2, true); assert.equal(received0, true); assert.equal(received1, true); assert.equal(received2, true); }); iotjs-1.0+715/test/run_pass/test_mqtt_frags.js000066400000000000000000000067671371177304000214120ustar00rootroot00000000000000/* Copyright 2018-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 stream = require('stream'); var mqtt = require('mqtt'); var assert = require('assert'); var fs = require('fs'); var duplex = new stream.Duplex(); var connect_state = 0; var recv_count = 0; var fragment_index = 0; // Message we send is always the same, but it is fragmented in different ways var fragments = [ // Basic message: '3014000d67656e6572616c2f746f70696368656c6c6f', // One message in three fragments '30', '14', '000d67656e6572616c2f746f70696368656c6c6f', // One message in four fragments '30', '14', '00', '0d67656e6572616c2f746f70696368656c6c6f', // One message in five fragments '30', '14', '00', '0d67656e6572616c2f746f70696368656c6c', '6f', // Two connected messages '3014000d67656e6572616c2f746f70696368656c6c6f' + '3014000d67656e6572616c2f746f70696368656c6c6f', // Two messages in three fragments '3014000d67656e6572616c2f74', '6f70696368656c6c6f3014000d67656e65', '72616c2f746f70696368656c6c6f', // Two messages in three fragments '3014000d67656e6572616c2f746f70696368656c6c6f30', '14', '000d67656e6572616c2f746f70696368656c6c6f', // A 132 byte long message '30', '87', '01', '000d67656e6572616c2f746f706963', '68656c6c6f68656c6c6f68656c6c6f68656c6c6f', '68656c6c6f68656c6c6f68656c6c6f68656c6c6f' + '68656c6c6f68656c6c6f68656c6c6f68656c6c6f' + '68656c6c6f68656c6c6f68656c6c6f68656c6c6f', '68656c6c6f68656c6c6f68656c6c6f68656c6c6f' + '68656c6c6f68656c6c6f68656c6c6f68656c6c6f' ]; function send_fragment() { duplex.push(new Buffer(fragments[fragment_index], 'hex')); if (++fragment_index < fragments.length) { process.nextTick(send_fragment); } else { duplex.end(); } } duplex._write = function(chunk, callback, onwrite) { onwrite(); switch (connect_state) { case 0: assert.equal(chunk.toString('hex'), '100f00044d5154540402001e0003636c69'); process.nextTick(function() { duplex.push(new Buffer('20020000', 'hex')); }); break; case 1: assert.equal(chunk.toString('hex'), '82120000000d67656e6572616c2f746f70696300'); process.nextTick(function() { duplex.push(new Buffer('9003000002', 'hex')); process.nextTick(send_fragment); }); break; default: throw new RangeError("Unknown connection state") break; } connect_state++; }; duplex._readyToWrite(); var mqtt_client = mqtt.connect({ clientId: 'cli', keepalive: 30, socket: duplex, }, function() { /* Just subscribe a random topic. */ mqtt_client.subscribe('general/topic'); }); mqtt_client.on('message', function(data) { if (recv_count < 10) { assert.equal(data.message.toString(), 'hello'); } else { var str = ''; for (var i = 0; i < 24; i++) str += 'hello'; assert.equal(data.message.toString(), str); } recv_count++; }); mqtt_client.on('finish', function(data) { assert.equal(recv_count, 11); }); iotjs-1.0+715/test/run_pass/test_net_1.js000066400000000000000000000023511371177304000202320ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var server = net.createServer(); var port = 22701; server.listen(port, 5); server.on('connection', function(socket) { socket.on('data', function(data) { socket.end('Hello IoT.js'); }); socket.on('close', function() { server.close(); }); }); var socket = new net.Socket(); var msg = ""; socket.connect(port, "127.0.0.1"); socket.write("Hello IoT.js"); socket.on('data', function(data) { msg += data; }); socket.on('end', function() { socket.end(); }); process.on('exit', function(code) { assert.equal(msg, "Hello IoT.js"); }); iotjs-1.0+715/test/run_pass/test_net_10.js000066400000000000000000000025071371177304000203150ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var server = net.createServer(); var port = 22709; var timedout = false; var connected = false; server.listen(port, 1); server.on('connection', function(newSocket) { connected = true; console.log("Connected!"); newSocket.on('error', function() { assert.fail(); }); newSocket.setTimeout(500); newSocket.on('timeout', function() { console.log("Timeout"); timedout = true; newSocket.destroy(); socket.destroy(); server.close(); }); }); var socket = net.createConnection(port); socket.on('error', function() { assert.fail(); }); process.on('exit', function() { assert(timedout); assert(connected); }); iotjs-1.0+715/test/run_pass/test_net_2.js000066400000000000000000000023751371177304000202410ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var port = 22702; var server = net.createServer({ allowHalfOpen: true }); server.listen(port, 5); server.on('connection', function(socket) { var msg = ''; socket.on('data', function(data) { msg += data; }); socket.on('end', function() { socket.end(msg); server.close(); }); }); var socket = new net.Socket(); var echo_msg = ''; socket.connect(port, '127.0.0.1', function() { socket.end('Hello IoT.js'); }); socket.on('data', function(data) { echo_msg += data; }); socket.on('end', function() { assert.equal(echo_msg, "Hello IoT.js"); }); iotjs-1.0+715/test/run_pass/test_net_3.js000066400000000000000000000036441371177304000202420ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var port = 22703; var limit = 200; var server = net.createServer(); server.listen({ port: port }); server.on('connection', function(socket) { var i = 0; var writing = function() { var ok; do { ok = socket.write("" + (i % 10)); if (++i == limit) { socket.end(); ok = false; } } while (ok); }; socket.on('drain', writing); writing(); }); var msg1 = ''; var socket1 = net.createConnection(port); socket1.on('data', function(data) { msg1 += data; }); var msg2 = ''; var socket2 = net.createConnection({port: port}); socket2.on('data', function(data) { msg2 += data; }); var msg3 = ''; var socket3 = net.createConnection({port: port, host: '127.0.0.1'}); socket3.on('data', function(data) { msg3 += data; }); var msg4 = ''; var connectListenerCheck = false; var socket4 = net.createConnection({port: port}, function() { connectListenerCheck = true; }); socket4.on('data', function(data) { msg4 += data; }); socket4.on('end', function() { server.close(); }); process.on('exit', function(code) { assert.equal(msg1.length, limit); assert.equal(msg2.length, limit); assert.equal(msg3.length, limit); assert.equal(msg4.length, limit); assert(connectListenerCheck); }); iotjs-1.0+715/test/run_pass/test_net_4.js000066400000000000000000000025701371177304000202400ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var timers = require('timers'); var server = net.createServer(); var port = 22704; var timeout = 1000; var writeat = 2000; server.listen(port, 5); server.on('connection', function(socket) { socket.setTimeout(timeout, function() { socket.end(); }); socket.on('data', function(data) { socket.end(); }); socket.on('close', function() { server.close(); }); }); var socket = new net.Socket(); socket.connect(port, "127.0.0.1"); socket.on('connect', function() { timers.setTimeout(function() { assert.throws( function() { socket.write('Hello IoT.js'); }, Error); }, writeat); }); process.on('exit', function(code) { assert.equal(code, 0); }); iotjs-1.0+715/test/run_pass/test_net_5.js000066400000000000000000000026431371177304000202420ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var timers = require('timers'); var server = net.createServer(); var port = 22705; var timeout = 2000; var writeat = 1000; var msg = ''; server.listen(port, 5); server.on('connection', function(socket) { socket.setTimeout(timeout, function() { assert.equal(msg, 'Hello IoT.js'); socket.end(); }); socket.on('data', function(data) { msg = data; }); socket.on('close', function() { server.close(); }); }); var socket = new net.Socket(); socket.connect(port, "127.0.0.1"); socket.on('end', function() { socket.end(); }); socket.on('connect', function() { timers.setTimeout(function() { socket.write('Hello IoT.js'); }, writeat); }); process.on('exit', function(code) { assert.equal(code, 0); }); iotjs-1.0+715/test/run_pass/test_net_6.js000066400000000000000000000031561371177304000202430ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var timers = require('timers'); var server = net.createServer(); var port = 22706; server.listen(port, 5); server.on('connection', function(socket) { socket.on('data', function(data) { msg += data; socket.end(); }); socket.on('close', function() { server.close(); }); // as soon as connection established, pause the socket socket.pause(); // resume after 2 secs timers.setTimeout(function() { socket.resume(); }, 2000); }); var socket = new net.Socket(); var msg = ""; socket.connect(port, "127.0.0.1"); socket.on('connect', function() { // client writes "1" first, but server is paused for 2 secs // server gets "1" after 2 secs socket.write("1"); // "2" is appended to msg before "1" timers.setTimeout(function() { msg += "2"; }, 1000); }); socket.on('end', function() { socket.end(); }); process.on('exit', function(code) { assert.equal(code, 0); assert.equal(msg, "21"); }); iotjs-1.0+715/test/run_pass/test_net_7.js000066400000000000000000000046521371177304000202460ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var timers = require('timers'); var port = 22707; var count = 40; var connectionCount = 0; if (process.platform === 'linux' || process.platform === 'darwin' || process.platform === 'tizen' || process.platform === 'windows') { var maxConnection = 40; } else if (process.platform === 'nuttx' || process.platform === 'tizenrt') { var maxConnection = 5; } else { assert.fail(); } var check = []; var queue = []; var isClose = false; function serverListen() { var server = net.createServer({ allowHalfOpen: true }); var cnt = 0; server.listen(port); server.on('connection', function(socket) { var msg = ''; socket.on('data', function(data) { msg += data; }); socket.on('end', function() { socket.end(msg); cnt++; if (cnt == count) { server.close(); isClose = true; } }); }); } serverListen(); function connectServer(i) { connectionCount++; var socket = new net.Socket(); var msg = ""; socket.connect(port, "localhost"); socket.on('connect', function() { socket.end(i.toString(), function() { connectionCount--; }); }); socket.on('data', function(data) { check[data] = true; }); } for (var i = 0; i < count; ++i) { queue.push(i); } var interval = setInterval(function() { if (isClose) { clearInterval(interval); } var queueLength = queue.length; if (connectionCount !== 0 && queueLength === 0) { return; } var end = maxConnection < queueLength ? maxConnection : queueLength; queue.splice(0, end).forEach(function(val) { connectServer(val); }); }, 500); process.on('exit', function(code) { assert.equal(code, 0); for (var i = 0; i < count; ++i) { if (!check[i]) { assert.fail(); } } }); iotjs-1.0+715/test/run_pass/test_net_8.js000066400000000000000000000030631371177304000202420ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var timers = require('timers'); var port = 22708; var server = net.createServer(); server.listen(port, 5); server.on('close', function() { assert.equal(msg, '12'); }); server.on('connection', function(socket) { socket.on('data', function(data) { socket.end(data); }); socket.on('close', function() { server.close(); }); }); var sock1 = new net.Socket(); var sock2 = new net.Socket(); var msg = ''; sock1.connect(port, 'localhost'); sock2.connect(port, 'localhost'); sock1.on('data', function(data) { msg += data; }); sock1.on('end', function() { sock1.end(); }); sock2.on('data', function(data) { msg += data; }); sock2.on('end', function() { sock2.end(); }); timers.setTimeout(function() { sock1.write('1'); }, 1000); timers.setTimeout(function() { sock2.write('2'); }, 2000); process.on('exit', function(code) { assert.equal(code, 0); }); iotjs-1.0+715/test/run_pass/test_net_9.js000066400000000000000000000024501371177304000202420ustar00rootroot00000000000000/* 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 net = require('net'); var assert = require('assert'); var server = net.createServer(); var port = 22709; server.listen(port, 5); server.on('close', function() { }); server.on('connection', function(socket) { socket.on('data', function(data) { socket.end('Hello IoT.js'); }); socket.on('close', function() { server.close(); }); }); var socket = new net.Socket(); var msg = ""; socket.connect(port, "127.0.0.1"); socket.write("Hello IoT.js"); socket.on('data', function(data) { msg += data; }); socket.on('end', function() { socket.end(); }); process.on('exit', function(code) { assert.equal(code, 0); assert.equal(msg, "Hello IoT.js"); }); iotjs-1.0+715/test/run_pass/test_net_connect.js000066400000000000000000000023721371177304000215260ustar00rootroot00000000000000/* 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 net = require('net'); var host = '127.0.0.1'; var port = 5696; var msg = 'Hello IoT.js'; var server = net.createServer({ allowHalfOpen: true } ).listen(port); server.on('connection', function(socket) { var data = ''; socket.on('data', function(chuck) { data += chuck; }); socket.on('end', function() { socket.end(data); }); }); var socket = net.connect(port, host, function() { var data = ''; socket.on('data', function(chuck) { data += chuck; }); socket.on('end', function() { assert.equal(data, msg); server.close(); }); socket.end(msg); }); iotjs-1.0+715/test/run_pass/test_net_headers.js000066400000000000000000000047201371177304000215070ustar00rootroot00000000000000/* 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 assert = require('assert'); var http = require('http'); var checkReqFinish = false; // server side code // Server just ends after sending with some headers. var server = http.createServer(function (req, res) { req.on('data', function (chunk) { body += chunk; }); var endHandler = function () { // this should return. res.removeHeader('h1'); res.setHeader('h1','h1'); res.setHeader('h2','h2'); res.setHeader('h3','h3'); res.removeHeader('h2'); if (res.getHeader('h3') == 'h3') { res.setHeader('h3','h3prime'); // h3 value should be overwrited } // final res.headers = { 'h1' : 'h1', 'h3': 'h3prime' } var responseSize; if (process.platform === 'linux' || process.platform === 'tizen') { // For Desktop and RPI, test with large header. responseSize = 500; } else { // NuttX and TizenRt cannot handle large header. responseSize = 10; } for (var i = 0; i < responseSize; i++) { res.setHeader('h' + (5 + i), 'h' + (5 + i)); } res.setHeader('content-length', 0); res.end(function(){ server.close(); }); }; req.on('end', endHandler); }); server.listen(3045, 3); // client req code var options = { method : 'GET', port : 3045 }; var postResponseHandler = function (res) { var res_body = ''; assert.equal(200, res.statusCode); assert.equal(res.headers['h1'], 'h1'); assert.equal(res.headers['h2'], undefined); assert.equal(res.headers['h3'], 'h3prime'); assert.equal(res.headers['content-length'], 0); var endHandler = function(){ checkReqFinish = true; }; res.on('end', endHandler); res.on('data', function(chunk){ res_body += chunk.toString(); }); }; var req = http.request(options, postResponseHandler); req.end(); process.on('exit', function() { assert.equal(checkReqFinish, true); }); iotjs-1.0+715/test/run_pass/test_net_http_get.js000066400000000000000000000041611371177304000217110ustar00rootroot00000000000000/* 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 assert = require('assert'); var http = require('http'); var server = http.createServer(function (req, res) { var body = ''; var url = req.url; req.on('data', function (chunk) { body += chunk; }); var endHandler = function () { res.writeHead(200, { 'Connection' : 'close', 'Content-Length' : body.length }); res.write(body); res.end(function(){ if(body == 'close server') server.close(); }); }; req.on('end', endHandler); }); server.listen(3005,5); // 1. GET req options = { method : 'GET', port : 3005 }; var getResponseHandler = function (res) { var res_body = ''; assert.equal(200, res.statusCode); var endHandler = function(){ // GET msg, no received body assert.equal('', res_body); }; res.on('end', endHandler); res.on('data', function(chunk){ res_body += chunk.toString(); }); }; http.get(options, getResponseHandler); // 2. close server req var finalMsg = 'close server'; var finalOptions = { method : 'POST', port : 3005, headers : {'Content-Length': finalMsg.length} }; var finalResponseHandler = function (res) { var res_body = ''; assert.equal(200, res.statusCode); var endHandler = function(){ assert.equal(finalMsg, res_body); }; res.on('end', endHandler); res.on('data', function(chunk){ res_body += chunk.toString(); }); }; var finalReq = http.request(finalOptions, finalResponseHandler); finalReq.write(finalMsg); finalReq.end(); iotjs-1.0+715/test/run_pass/test_net_http_methods.js000066400000000000000000000024301371177304000225720ustar00rootroot00000000000000/* Copyright 2018-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 http = require('http'); assert(http.METHODS instanceof Array, 'http.METHODS should be an array'); for (var idx in http.METHODS) { assert(typeof(http.METHODS[idx]) === 'string', 'Elements of the http.METHODS should be strings. ' + 'Found an invalid element, index: ' + idx); } /* Test if at least the basic HTTP methods should be supported */ var main_methods = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD']; for (var idx in main_methods) { var method_name = main_methods[idx]; assert.notEqual(http.METHODS.indexOf(method_name), -1, 'http.METHODS is missing the value: ' + method_name); } iotjs-1.0+715/test/run_pass/test_net_http_modified_req_resp.js000066400000000000000000000067031371177304000246160ustar00rootroot00000000000000/* Copyright 2018-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 http = require('http'); var response_message = 'DATA'; var response_got = 'NOT THIS'; /* * Test if 'subclassing' the IncomingMessage * and ServerResponse is correctly propagated. */ function newIncomingMessage() { http.IncomingMessage.apply(this, arguments); }; newIncomingMessage.prototype = Object.create(http.IncomingMessage.prototype); newIncomingMessage.prototype.extra_field = 'found'; newIncomingMessage.prototype.waitForBody = function() { var chunks = []; this.on('data', function(chunk) { chunks.push(chunk); }); this.on('end', function() { this.emit('full_body', Buffer.concat(chunks)); }); }; function newServerResponse() { http.ServerResponse.apply(this, arguments); }; newServerResponse.prototype = Object.create(http.ServerResponse.prototype); newServerResponse.prototype.sendJSON = function (obj) { var message_body = JSON.stringify(obj); this.setHeader('Content-Length', message_body.length); this.setHeader('Content-Type', 'application/json'); this.writeHead(200); this.end(message_body); }; var serveropts = { IncomingMessage: newIncomingMessage, ServerResponse: newServerResponse, }; var server = http.createServer(serveropts, function (req, res) { assert.equal(req.method, 'POST', 'Incorrect request method detected'); assert.equal(req.url, '/put_msg', 'Incorrect request url detected'); assert.assert(req instanceof http.IncomingMessage, 'Request is not instance of http.IncomingMessage'); assert.assert(req instanceof newIncomingMessage, 'Request is not instance of the new Request object'); assert.equal(req.extra_field, 'found', 'No "extra_field" property on the request instance'); req.waitForBody(); req.on('full_body', function(body) { assert.assert(body instanceof Buffer); assert.equal(body.toString(), 'DEMO'); res.sendJSON({message: response_message}); }); }); server.listen(3001); var demo_msg = 'DEMO'; var options = { method : 'POST', port : 3001, path : '/put_msg', headers: { 'Content-Length': demo_msg.length, }, }; var req = http.request(options, function (response){ var content_type = response.headers['Content-Type'] || response.headers['content-type'] assert.equal(content_type, 'application/json', 'Incorrect content type returned by the server'); var chunks = [] response.on('data', function(chunk) { chunks.push(chunk); }); response.on('end', function() { var body = JSON.parse(Buffer.concat(chunks).toString()); assert.assert('message' in body, 'No "message" key in response JSON'); response_got = body.message; server.close(); }); }); req.end(demo_msg); process.on('exit', function() { assert.equal(response_got, response_message, 'Invalid response returned from the demo server'); }); iotjs-1.0+715/test/run_pass/test_net_http_modified_request.js000066400000000000000000000062651371177304000244710ustar00rootroot00000000000000/* Copyright 2018-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 http = require('http'); var response_message = 'DATA'; var response_got = 'NOT THIS'; /* * Test if 'subclassing' the IncomingMessage * and ServerResponse is propagated correctly. */ function newIncomingMessage() { http.IncomingMessage.apply(this, arguments); }; newIncomingMessage.prototype = Object.create(http.IncomingMessage.prototype); newIncomingMessage.prototype.extra_field = 'found'; newIncomingMessage.prototype.waitForBody = function() { var chunks = []; this.on('data', function(chunk) { chunks.push(chunk); }); this.on('end', function() { this.emit('full_body', Buffer.concat(chunks)); }); }; var serveropts = { IncomingMessage: newIncomingMessage, }; var server = http.createServer(serveropts, function (req, res) { assert.equal(req.method, 'POST', 'Incorrect request method detected'); assert.equal(req.url, '/put_msg', 'Incorrect request url detected'); assert.assert(req instanceof http.IncomingMessage, 'Request is not instance of http.IncomingMessage'); assert.assert(req instanceof newIncomingMessage, 'Request is not instance of the new Request object'); assert.equal(req.extra_field, 'found', 'No "extra_field" property on the request instance'); req.waitForBody(); req.on('full_body', function(body) { assert.assert(body instanceof Buffer); assert.equal(body.toString(), 'DEMO'); var message_body = JSON.stringify({message: response_message}); res.setHeader('Content-Length', message_body.length); res.setHeader('Content-Type', 'application/json'); res.writeHead(200); res.end(message_body); }); }); server.listen(3001); var demo_msg = 'DEMO'; var options = { method : 'POST', port : 3001, path : '/put_msg', headers: { 'Content-Length': demo_msg.length, }, }; var req = http.request(options, function (response){ var content_type = response.headers['Content-Type'] || response.headers['content-type'] assert.equal(content_type, 'application/json', 'Incorrect content type returned by the server'); var chunks = [] response.on('data', function(chunk) { chunks.push(chunk); }); response.on('end', function() { var body = JSON.parse(Buffer.concat(chunks).toString()); assert.assert('message' in body, 'No "message" key in response JSON'); response_got = body.message; server.close(); }); }); req.end(demo_msg); process.on('exit', function() { assert.equal(response_got, response_message, 'Invalid response returned from the demo server'); }); iotjs-1.0+715/test/run_pass/test_net_http_modified_response.js000066400000000000000000000054211371177304000246300ustar00rootroot00000000000000/* Copyright 2018-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 http = require('http'); var response_message = 'DATA'; var response_got = 'NOT THIS'; /* * Test if 'subclassing' the ServerResponse is propagated correctly. */ function newServerResponse() { http.ServerResponse.apply(this, arguments); }; newServerResponse.prototype = Object.create(http.ServerResponse.prototype); newServerResponse.prototype.sendJSON = function (obj) { var message_body = JSON.stringify(obj); this.setHeader('Content-Length', message_body.length); this.setHeader('Content-Type', 'application/json'); this.writeHead(200); this.end(message_body); }; var serveropts = { ServerResponse: newServerResponse, }; var server = http.createServer(serveropts, function (req, res) { assert.equal(req.method, 'POST', 'Incorrect request method detected'); assert.equal(req.url, '/put_msg', 'Incorrect request url detected'); assert.assert(req instanceof http.IncomingMessage, 'Request is not instance of http.IncomingMessage'); var chunks = []; req.on('data', function(chunk) { chunks.push(chunk); }); req.on('end', function() { var body = Buffer.concat(chunks); assert.equal(body.toString(), 'DEMO'); res.sendJSON({message: response_message}); }); }); server.listen(3001); var demo_msg = 'DEMO'; var options = { method : 'POST', port : 3001, path : '/put_msg', headers: { 'Content-Length': demo_msg.length, }, }; var req = http.request(options, function (response){ var content_type = response.headers['Content-Type'] || response.headers['content-type'] assert.equal(content_type, 'application/json', 'Incorrect content type returned by the server'); var chunks = [] response.on('data', function(chunk) { chunks.push(chunk); }); response.on('end', function() { var body = JSON.parse(Buffer.concat(chunks).toString()); assert.assert('message' in body, 'No "message" key in response JSON'); response_got = body.message; server.close(); }); }); req.end(demo_msg); process.on('exit', function() { assert.equal(response_got, response_message, 'Invalid response returned from the demo server'); }); iotjs-1.0+715/test/run_pass/test_net_http_outgoing_buffer.js000066400000000000000000000032221371177304000243130ustar00rootroot00000000000000/* Copyright 2018-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 assert = require('assert'); var clientMessage = new Buffer([0xE6, 0x7F, 0x3, 0x6, 0x7]); var serverMessage = new Buffer([0x3, 0x7F, 0x6, 0x7, 0xE6]); var serverReceived; var clientReceived; var server = http.createServer(function(req, res) { var received = []; req.on('data', function(data) { received.push(data); }); req.on('end', function() { serverReceived = Buffer.concat(received); res.end(serverMessage); }); }).listen(8383, 5); var reqOpts = { method: 'POST', port: 8383, path: '/', headers: {'Content-Length': clientMessage.length}, }; var clientReq = http.request(reqOpts, function(res) { var response = []; res.on('data', function(data) { response.push(data); }); res.on('end', function() { clientReceived = Buffer.concat(response); server.close(); }); }); clientReq.end(clientMessage); process.on('exit', function() { assert.equal(serverReceived.compare(clientMessage), 0); assert.equal(clientReceived.compare(serverMessage), 0); }); iotjs-1.0+715/test/run_pass/test_net_http_request_http_version.js000066400000000000000000000023161371177304000254260ustar00rootroot00000000000000/* Copyright 2018-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 http = require('http'); var server = http.createServer(function(request, response) { // the http version in IoT.js is hardcoded to 1.1 assert.equal(request.httpVersion, "1.1", "incorrect http version returned via the http request object"); response.writeHead(200); response.end(); }); server.listen(3008, 5); var request = http.request({ method: 'HEAD', port: 3008, path: '/' }, function(response) { assert.equal(response.statusCode, 200); response.on('end', function() { server.close(); }); }) request.end(); iotjs-1.0+715/test/run_pass/test_net_http_request_response.js000066400000000000000000000113341371177304000245400ustar00rootroot00000000000000/* 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 http = require('http'); var net = require('net'); // Messages for further requests. var message = 'Hello IoT.js'; // Options for further requests. var options = { method: 'POST', port: 3005, path: '/', headers : {'Content-Length': message.length} }; var server1 = http.createServer(function(request, response) { var str = ''; request.on('data', function (chunk) { str += chunk.toString(); }); request.on('end', function() { assert.equal(str, message); response.end(); }); }); server1.listen(3005, 5); // Simple request with valid utf-8 message. var isRequest1Finished = false; var request1 = http.request(options, function(response) { var str = ''; response.on('data', function(chunk) { str += chunk.toString(); }); response.on('end', function() { isRequest1Finished = true; server1.close(); }); }); request1.end(message, 'utf-8'); var server2 = http.createServer(function(request, response) { response.end(); }); server2.listen(3006, 5); // Simple request with end callback. var isRequest2Finished = false; options.port = 3006; var request2 = http.request(options); request2.end(message, function() { server2.close(); isRequest2Finished = true; }); var server3 = http.createServer(function(request, response) { var str = ''; request.on('data', function(chunk) { str += chunk; }); request.on('end', function() { // Check if we got the proper message. assert.equal(str, message); response.end(); }); }); server3.listen(3007, 5); // Simple request with buffer chunk as message parameter. options.port = 3007; var isRequest3Finished = false; var request3 = http.request(options, function(response) { var str = ''; response.on('data', function(chunk) { str += chunk; }); response.on('end', function() { isRequest3Finished = true; server3.close(); }); }); request3.end(new Buffer(message)); // This test is to make sure that when the HTTP server // responds to a HEAD request, it does not send any body. var server4 = http.createServer(function(request, response) { response.writeHead(200); response.end(); }); server4.listen(3008, 5); var isRequest4Finished = false; var request4 = http.request({ method: 'HEAD', port: 3008, path: '/' }, function(response) { response.on('end', function() { isRequest4Finished = true; assert.equal(response.statusCode, 200); server4.close(); }); }); request4.end(); // Write a header twice in the server response. var server5 = http.createServer(function(request, response) { var str = ''; request.on('data', function(chunk) { str += chunk; }); request.on('end', function() { response.writeHead(200, 'OK', {'Connection' : 'close1'}); // Wrote the same head twice. response.writeHead(200, 'OK', {'Connection' : 'close2'}); // Wrote a new head. response.writeHead(200, {'Head' : 'Value'}); response.end(); }); }); server5.listen(3009, 5); options.port = 3009; options.headers = null; var isRequest5Finished = false; var request5 = http.request(options, function(response) { response.on('end', function() { isRequest5Finished = true; assert.equal(response.headers['Connection'], 'close2'); assert.equal(response.headers['Head'], 'Value'); server5.close(); }); }); request5.end(); // Test the IncomingMessage read function. var server6 = http.createServer(function(request, response) { request.on('end', function() { response.end('ok'); server6.close(); }); }).listen(8080, 5); var readRequest = http.request({ host: '127.0.0.1', port: 8080, path: '/', method: 'GET' }); readRequest.end(); readRequest.on('response', function(incomingMessage) { incomingMessage.on('readable', function() { var inc = incomingMessage.read(); assert.equal(inc instanceof Buffer, true); assert.assert(inc.toString('utf8').length > 0); }); }); process.on('exit', function() { assert.equal(isRequest1Finished, true); assert.equal(isRequest2Finished, true); assert.equal(isRequest3Finished, true); assert.equal(isRequest4Finished, true); assert.equal(isRequest5Finished, true); }); iotjs-1.0+715/test/run_pass/test_net_http_response_twice.js000066400000000000000000000032561371177304000241670ustar00rootroot00000000000000/* 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 http = require('http'); var net = require('net'); var body = 'Hello IoT.js\r\n'; var fullResponse = 'HTTP/1.1 500 Internal Server Error\r\n' + 'Content-Length: ' + body.length + '\r\n' + 'Content-Type: text/plain\r\n' + 'Date: Fri + 5 May 2017 10:22:45 GMT\r\n' + 'Host: 127.0.0.1\r\n' + 'Access-Control-Allow-Credentials: true\r\n' + 'Server: badly broken/0.1 (OS NAME)\r\n' + '\r\n' + body; var server = net.createServer(function(socket) { var postBody = ''; socket.on('data', function(chunk) { postBody += chunk; if (postBody.indexOf('\r\n') > -1) { socket.write(fullResponse); // Wrote the response twice. socket.end(fullResponse); } }); socket.on('error', function(err) {}); }); server.listen(3085, function() { http.get({ port: 3085 }, function(response) { var buffer = ''; response.on('data', function(chunk) { buffer += chunk; }); response.on('end', function() { assert.equal(body, buffer); server.close(); }); }); }); iotjs-1.0+715/test/run_pass/test_net_http_server.js000066400000000000000000000103241371177304000224360ustar00rootroot00000000000000/* 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 assert = require('assert'); var http = require('http'); var Server = http.Server; var responseCheck = ''; var connectionEvent = 0; var serverCloseEvent = 0; var requestEvent = 0; var responseEvent = 0; var socketEvent = 0; // server side code // server will return the received msg from client // and shutdown var server = http.createServer(function (req, res) { var body = ''; var url = req.url; req.on('data', function (chunk) { body += chunk; }); var endHandler = function () { res.writeHead(200, { 'Connection' : 'close', 'Content-Length' : body.length }); res.write(body); res.end(function(){ if(body == 'close server') { server.close(); } }); }; req.on('end', endHandler); }); server.on('request', function() { requestEvent++; }); server.on('connection', function() { connectionEvent++; }); server.on('close', function() { serverCloseEvent++; }); server.listen(3001, 3); // client side code // 1. send POST req to server and check response msg // 2. send GET req to server and check response msg // 3. send 'close server' msg // 1. POST req var msg = 'http request test msg'; var options = { method : 'POST', port : 3001, rejectUnauthorized: false, headers : {'Content-Length': msg.length} }; var postResponseHandler = function (res) { var res_body = ''; assert.equal(200, res.statusCode); var endHandler = function(){ assert.equal(msg, res_body); responseCheck += '1'; }; res.on('end', endHandler); res.on('data', function(chunk){ res_body += chunk.toString(); }); }; var req = http.request(options, postResponseHandler); req.on('response', function() { responseEvent++; }); req.on('socket', function() { socketEvent++; }); req.write(msg); req.end(); // 2. GET req options = { method : 'GET', port : 3001 }; var getResponseHandler = function (res) { var res_body = ''; assert.equal(200, res.statusCode); var endHandler = function(){ // GET msg, no received body assert.equal('', res_body); responseCheck += '2'; }; res.on('end', endHandler); res.on('data', function(chunk){ res_body += chunk.toString(); }); }; var getReq = http.request(options, getResponseHandler); getReq.on('response', function() { responseEvent++; }); getReq.on('socket', function() { socketEvent++; }); getReq.end(); // 3. close server req var finalMsg = 'close server'; var finalOptions = { method : 'POST', port : 3001, rejectUnauthorized: false, headers : {'Content-Length': finalMsg.length} }; var finalResponseHandler = function (res) { var res_body = ''; assert.equal(200, res.statusCode); var endHandler = function(){ assert.equal(finalMsg, res_body); responseCheck += '3'; }; res.on('end', endHandler); res.on('data', function(chunk){ res_body += chunk.toString(); }); }; var finalReq = http.request(finalOptions, finalResponseHandler); finalReq.on('response', function() { responseEvent++; }); finalReq.on('socket', function() { socketEvent++; }); finalReq.write(finalMsg); finalReq.end(); // Create server without requestListener. var server2 = http.createServer(); // Create server instance without new keyword. var server3 = Server(function(request, response) {}); process.on('exit', function() { assert.equal(responseCheck.length, 3); assert.equal(connectionEvent, 3); assert.equal(serverCloseEvent, 1); assert.equal(requestEvent, 3); assert.equal(responseEvent, 3); assert.equal(socketEvent, 3); assert.equal(server2 instanceof Server, true); assert.equal(server3 instanceof Server, true); }); iotjs-1.0+715/test/run_pass/test_net_http_server_timeout.js000066400000000000000000000023011371177304000242000ustar00rootroot00000000000000/* 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 assert = require('assert'); var http = require('http'); var timeouted = false; var server = http.createServer(function(req, res) { // do nothing }); server.listen(3003); server.setTimeout(100, function(socket) { timeouted = true; socket.destroy(); server.close(); }); // client will connect to server, and do nothing. var options = { method : 'GET', port : 3003 }; var getReq = http.request(options); getReq.on('error', function() {}); process.on('exit', function(code) { assert.equal(timeouted, true); assert.equal(code, 0); }); getReq.end(); iotjs-1.0+715/test/run_pass/test_net_http_status_codes.js000066400000000000000000000033451371177304000236350ustar00rootroot00000000000000/* 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 http = require('http'); var codes = ["150", "199", "200", "204", "304", "404", "510"]; var queue = codes.slice(0); var responses = []; var options = { method: 'POST', port: 3008, headers: {'Content-Length': 3} }; var server = http.createServer(function (request, response) { var str = ''; request.on('data', function (chunk) { str += chunk; }); request.on('end', function() { if (codes.indexOf(str) > -1) { response.writeHead(parseInt(str)); } response.end(); }); }).listen(3008, 5); requestOnQueue(queue.shift()); function requestOnQueue(code) { var request = http.request(options, function(res) { responses.push(res.statusCode); if (responses.length == codes.length) { // Done with downloads. for (var j = 0; j < codes.length; j++) { assert(responses.indexOf(parseInt(codes[j])) > -1); } server.close(); } else { if(queue.length) { process.nextTick(function() { requestOnQueue(queue.shift()); }); } } }).end(code); } iotjs-1.0+715/test/run_pass/test_net_httpclient_error.js000066400000000000000000000030371371177304000234630ustar00rootroot00000000000000/* 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 http = require('http'); var recievedResponse = false; var server = http.createServer(function(request, response) { var str = ''; request.on('data', function (chunk) { str += chunk; }); request.on('end', function() { response.end(); }); }); server.listen(20004, 5); // Connection refusal: The request will try to connect to a server, // however the connection can not be created because the port is invalid. var req = http.request({ host: 'localhost', port: 20002, path: '/', method: 'GET' }, function(response) { var str = ''; response.on('data', function(chunk) { str += chunk; }); response.on('end', function() { recievedResponse = true; server.close(); }); }); req.on('error', function() { recievedResponse = false; server.close(); }); req.end(); process.on('exit', function() { assert.equal(recievedResponse, false); }); iotjs-1.0+715/test/run_pass/test_net_httpclient_parse_error.js000066400000000000000000000023311371177304000246510ustar00rootroot00000000000000/* 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 http = require('http'); var net = require('net'); var errors = 0; // Create a TCP server var server = net.createServer(function(socket) { socket.end('Bad http\r\n\r\n'); // This should trigger the Parse Error. server.close(); }); server.listen(3085, '127.0.0.1'); // Create a simple get request. var request = http.request({ host: '127.0.0.1', port: 3085, method: 'GET', path: '/' }); request.on('error', function(err) { errors++; }); request.end(); process.on('exit', function() { // The error is a Parse Error. assert.equal(errors, 1); }); iotjs-1.0+715/test/run_pass/test_net_httpclient_timeout_1.js000066400000000000000000000033371371177304000242430ustar00rootroot00000000000000/* 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 assert = require('assert'); var http = require('http'); var IncomingMessage = require('http_incoming').IncomingMessage; var OutgoingMessage = require('http_outgoing').OutgoingMessage; var net = require('net'); var timeouted = false; var options = { method: 'GET', port: 3002 }; var incTimeout = 0; var outTimeout = 0; var socket = new net.Socket(); var inc = new IncomingMessage(socket); inc.setTimeout(100, function() { incTimeout++; }); var out = new OutgoingMessage(); out.setTimeout(100, function() { outTimeout++; }); out.emit('timeout'); var server = http.createServer(function(req, res) { // do nothing }); server.listen(options.port, function() { var req = http.request(options, function(res) { }); req.on('close', function() { server.close(); }); var destroyer = function() { timeouted = true; req.socket.destroy(); } req.setTimeout(100, destroyer); req.on('error', function(){}); req.end(); }); process.on('exit', function(code) { assert.equal(code,0); assert.equal(timeouted, true); assert.equal(incTimeout, 1); assert.equal(outTimeout, 1); }); iotjs-1.0+715/test/run_pass/test_net_httpclient_timeout_2.js000066400000000000000000000027011371177304000242360ustar00rootroot00000000000000/* 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 assert = require('assert'); var http = require('http'); var timeouted = false; var options = { method: 'GET', port: 3004 }; var server = http.createServer(function(req, res) { res.write("."); }); server.listen(options.port, function() { var req = http.request(options, function(res) { var destroyer = function() { timeouted = true; req.socket.destroy(); server.close(); } res.on('data', function() { // after connection established req.setTimeout(100, destroyer); }); }); req.on('close', function() { server.close(); }); var before = function(){ /* this handler must not be called */ }; req.setTimeout(1000, before); req.on('error', function(){}); req.end(); }); process.on('exit', function(code) { assert.equal(timeouted, true); }); iotjs-1.0+715/test/run_pass/test_net_https_get.js000066400000000000000000000042061371177304000220740ustar00rootroot00000000000000/* 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 https = require('https'); var isRequest1Finished = false; // 1. GET req options = { method: 'GET', host: 'httpbin.org', path: '/user-agent', rejectUnauthorized: false, headers: {'user-agent': 'iotjs'} }; var getResponseHandler = function (res) { var res_body = ''; assert.equal(200, res.statusCode); var endHandler = function(){ var response = JSON.parse(res_body); assert.equal('iotjs', response['user-agent']); isRequest1Finished = true; }; res.on('end', endHandler); res.on('data', function(chunk){ res_body += chunk.toString(); }); }; https.get(options, getResponseHandler); // 2. close server req var testMsg = 'Hello IoT.js'; var finalOptions = { method: 'POST', host: 'httpbin.org', path: '/post', rejectUnauthorized: false, headers: {'Content-Length': testMsg.length, 'Content-Type': 'application/json'} }; var isRequest2Finished = false; var finalResponseHandler = function (res) { var res_body = ''; assert.equal(200, res.statusCode); var endHandler = function(){ var response = JSON.parse(res_body); assert.equal(testMsg, response['data']); isRequest2Finished = true; }; res.on('end', endHandler); res.on('data', function(chunk){ res_body += chunk.toString(); }); }; var finalReq = https.request(finalOptions, finalResponseHandler); finalReq.write(testMsg); finalReq.end(); process.on('exit', function() { assert.equal(isRequest1Finished, true); assert.equal(isRequest2Finished, true); }); iotjs-1.0+715/test/run_pass/test_net_https_modified_req_resp.js000066400000000000000000000072321371177304000247770ustar00rootroot00000000000000/* Copyright 2018-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 fs = require('fs'); var http = require('http'); var https = require('https'); var response_message = 'DATA'; var response_got = 'NOT THIS'; /* * Test if 'subclassing' the IncomingMessage * and ServerResponse is correctly propagated. */ function newIncomingMessage() { http.IncomingMessage.apply(this, arguments); }; newIncomingMessage.prototype = Object.create(http.IncomingMessage.prototype); newIncomingMessage.prototype.extra_field = 'found'; newIncomingMessage.prototype.waitForBody = function() { var chunks = []; this.on('data', function(chunk) { chunks.push(chunk); }); this.on('end', function() { this.emit('full_body', Buffer.concat(chunks)); }); }; function newServerResponse() { http.ServerResponse.apply(this, arguments); }; newServerResponse.prototype = Object.create(http.ServerResponse.prototype); newServerResponse.prototype.sendJSON = function (obj) { var message_body = JSON.stringify(obj); this.setHeader('Content-Length', message_body.length); this.setHeader('Content-Type', 'application/json'); this.writeHead(200); this.end(message_body); }; var serveropts = { IncomingMessage: newIncomingMessage, ServerResponse: newServerResponse, key: fs.readFileSync(process.cwd() + '/resources/my_key.key'), cert: fs.readFileSync(process.cwd() + '/resources/my_crt.crt') }; var server = https.createServer(serveropts, function (req, res) { assert.equal(req.method, 'POST', 'Incorrect request method detected'); assert.equal(req.url, '/put_msg', 'Incorrect request url detected'); assert.assert(req instanceof http.IncomingMessage, 'Request is not instance of http.IncomingMessage'); assert.assert(req instanceof newIncomingMessage, 'Request is not instance of the new Request object'); assert.equal(req.extra_field, 'found', 'No "extra_field" property on the request instance'); req.waitForBody(); req.on('full_body', function(body) { assert.assert(body instanceof Buffer); assert.equal(body.toString(), 'DEMO'); res.sendJSON({message: response_message}); }); }); server.listen(3001); var demo_msg = 'DEMO'; var options = { method : 'POST', port : 3001, path : '/put_msg', headers: { 'Content-Length': demo_msg.length, }, rejectUnauthorized: false }; var req = https.request(options, function (response){ var content_type = response.headers['Content-Type'] || response.headers['content-type'] assert.equal(content_type, 'application/json', 'Incorrect content type returned by the server'); var chunks = [] response.on('data', function(chunk) { chunks.push(chunk); }); response.on('end', function() { var body = JSON.parse(Buffer.concat(chunks).toString()); assert.assert('message' in body, 'No "message" key in response JSON'); response_got = body.message; server.close(); }); }); req.end(demo_msg); process.on('exit', function() { assert.equal(response_got, response_message, 'Invalid response returned from the demo server'); }); iotjs-1.0+715/test/run_pass/test_net_https_post_status_codes.js000066400000000000000000000030121371177304000250540ustar00rootroot00000000000000/* 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 https = require('https'); var isRequest1Finished = false; // 1. POST req var data = JSON.stringify({}); var options = { method: 'POST', hostname: 'httpbin.org', path: '/post', rejectUnauthorized: false, headers: { 'content-type': 'application/json', 'content-length': data.length, } }; var getResponseHandler = function(res) { var res_body = ''; assert.equal(200, res.statusCode); var endHandler = function() { var response = JSON.parse(res_body); assert.assert(response['data'], 'Recieved incorrect response from server'); isRequest1Finished = true; }; res.on('end', endHandler); res.on('data', function(chunk) { res_body += chunk.toString(); }); }; var req = https.request(options, getResponseHandler); req.write(data); req.end(); process.on('exit', function() { assert.equal(isRequest1Finished, true); }); iotjs-1.0+715/test/run_pass/test_net_https_request_response.js000066400000000000000000000056731371177304000247340ustar00rootroot00000000000000/* 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 http = require('http'); var https = require('https'); var net = require('net'); // Messages for further requests. var message = 'Hello IoT.js'; // Options for further requests. var options = { method: 'POST', host: 'httpbin.org', path: '/post', rejectUnauthorized: false, headers: {'Content-Length': message.length, 'Content-Type': 'application/json'} }; // Simple request with valid utf-8 message. var isRequest1Finished = false; var request1 = https.request(options, function(response) { var str = ''; response.on('data', function(chunk) { str += chunk.toString(); }); response.on('end', function() { var response = JSON.parse(str); assert.equal(message, response['data']); isRequest1Finished = true; }); }); request1.end(message); // Simple request with multiple end callback. var isRequest2Finished = false; var request2 = https.request(options, function(response) { var str = ''; response.on('data', function(chunk) { str += chunk.toString(); }); response.on('end', function() { var response = JSON.parse(str); assert.equal(message, response['data']); }); }); request2.end(message, function() { isRequest2Finished = true; }); // Simple request with buffer chunk as message parameter. var isRequest3Finished = false; var request3 = https.request(options, function(response) { var str = ''; response.on('data', function(chunk) { str += chunk; }); response.on('end', function() { var response = JSON.parse(str); assert.equal(message, response['data']); isRequest3Finished = true; }); }); request3.end(new Buffer(message)); // Test the IncomingMessage read function. var isRequest4Finished = false; var readRequest = https.request({ method: 'GET', host: 'httpbin.org', rejectUnauthorized: false, path: '/get' }); readRequest.on('response', function(incomingMessage) { incomingMessage.on('readable', function() { var inc = incomingMessage.read(); assert.equal(inc instanceof Buffer, true); assert(inc.toString('utf8').length > 0); isRequest4Finished = true; }); }); readRequest.end(); process.on('exit', function() { assert.equal(isRequest1Finished, true); assert.equal(isRequest2Finished, true); assert.equal(isRequest3Finished, true); assert.equal(isRequest4Finished, true); }); iotjs-1.0+715/test/run_pass/test_net_https_server.js000066400000000000000000000027141371177304000226250ustar00rootroot00000000000000/* Copyright 2018-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 https = require('https'); var fs = require('fs'); var server_options = { key: fs.readFileSync(process.cwd() + '/resources/my_key.key').toString(), cert: fs.readFileSync(process.cwd() + '/resources/my_crt.crt').toString() }; var server = https.createServer(server_options, function(req, res) { res.writeHead(200); res.end('hello world\n'); }).listen(8000); var client_options = { host: 'localhost', port: 8000, rejectUnauthorized: false } var responseHandler = function (res) { var res_body = ''; assert.equal(200, res.statusCode); var endHandler = function(){ assert.equal(res_body, 'hello world\n'); }; res.on('end', endHandler); res.on('data', function(chunk){ res_body += chunk.toString(); }); server.close(); } https.get(client_options, responseHandler); iotjs-1.0+715/test/run_pass/test_net_https_timeout.js000066400000000000000000000020401371177304000227750ustar00rootroot00000000000000/* 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 https = require('https'); options = { method: 'GET', host: 'httpbin.org', rejectUnauthorized: false, path: '/delay/10' }; var getReq = https.get(options); getReq.on('error', function(){}); var timeouted = false; getReq.setTimeout(5000, function() { timeouted = true; getReq.abort(); }); process.on('exit', function(code) { assert.equal(timeouted, true); }); iotjs-1.0+715/test/run_pass/test_process.js000066400000000000000000000015001371177304000206750ustar00rootroot00000000000000/* 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 assert = require('assert'); var sequence = ''; process.nextTick(function() { sequence += '2' }); sequence = '1'; process.on('exit', function() { assert.equal(sequence, '12'); }); iotjs-1.0+715/test/run_pass/test_process_chdir.js000066400000000000000000000017751371177304000220640ustar00rootroot00000000000000/* 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 currentPath = process.cwd(); try { process.chdir('/'); } catch (err) { console.log('invalid path'); } var newPath = process.cwd(); if (process.platform === "windows") { /* check if the path is in format: :\ */ assert.equal(newPath.substr(1), ':\\'); } else { assert.equal(newPath, '/'); } process.chdir(currentPath); iotjs-1.0+715/test/run_pass/test_process_cwd.js000066400000000000000000000012361371177304000215400ustar00rootroot00000000000000/* 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. */ console.log(process.cwd()); iotjs-1.0+715/test/run_pass/test_process_exit.js000066400000000000000000000012231371177304000217300ustar00rootroot00000000000000/* 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. */ process.exit(0); iotjs-1.0+715/test/run_pass/test_process_experimental_off.js000066400000000000000000000013321371177304000243070ustar00rootroot00000000000000/* 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'); assert.notEqual(process.env.IOTJS_ENV, 'experimental'); iotjs-1.0+715/test/run_pass/test_process_experimental_on.js000066400000000000000000000013271371177304000241550ustar00rootroot00000000000000/* 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'); assert.equal(process.env.IOTJS_ENV, 'experimental'); iotjs-1.0+715/test/run_pass/test_process_next_tick.js000066400000000000000000000021511371177304000227500ustar00rootroot00000000000000/* 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 assert = require('assert'); var tickTrace = ""; process.nextTick(function() { tickTrace += "1"; process.nextTick(function() { tickTrace += "2"; process.nextTick(function() { tickTrace += "3"; process.nextTick(function() { tickTrace += "4"; process.nextTick(function() { tickTrace += "5"; }); }); }); }); }); process.on('exit', function(code) { assert.equal(code, 0); assert.equal(tickTrace, "12345"); }); iotjs-1.0+715/test/run_pass/test_process_uncaught_order.js000066400000000000000000000020151371177304000237700ustar00rootroot00000000000000/* 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 assert = require('assert'); var trace = ''; process.on('uncaughtException', function (err) { trace += 'A'; }); process.on('uncaughtException', function (err) { trace += 'B'; }); process.on('exit', function() { trace += 'C'; process.removeAllListeners('uncaughtException'); assert.equal(trace, 'ABABC'); }); process.nextTick(function() { assert.fail(); }); assert.fail(); iotjs-1.0+715/test/run_pass/test_process_uncaught_simple.js000066400000000000000000000017031371177304000241510ustar00rootroot00000000000000/* 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 assert = require('assert'); var trace = ''; process.on('uncaughtException', function (err) { trace += 'A'; }); process.on('exit', function() { process.removeAllListeners('uncaughtException'); assert.equal(trace, 'AB'); }); setTimeout(function() { trace += 'B' }, 500); nonexistentFunc(); trace += 'C'; iotjs-1.0+715/test/run_pass/test_pwm_api.js000066400000000000000000000135631371177304000206670ustar00rootroot00000000000000/* Copyright 2019-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 pwm = require('pwm'); // ------ Test API existance assert.equal(typeof pwm.open, 'function', 'pwm does not provide \'open\' function'); assert.equal(typeof pwm.openSync, 'function', 'pwm does not provide \'openSync\' function'); function check_pwmpin(pwmpin) { assert.equal(typeof pwmpin.setPeriod, 'function', '\'pwmpin\' does not provide \'setPeriod\' function'); assert.equal(typeof pwmpin.setPeriodSync, 'function', '\'pwmpin\' does not provide \'setPeriodSync\' function'); assert.equal(typeof pwmpin.setFrequency, 'function', '\'pwmpin\' does not provide \'setFrequency\' function'); assert.equal(typeof pwmpin.setFrequencySync, 'function', '\'pwmpin\' does not provide \'setFrequencySync\' function'); assert.equal(typeof pwmpin.setDutyCycle, 'function', '\'pwmpin\' does not provide \'setDutyCycle\' function'); assert.equal(typeof pwmpin.setDutyCycleSync, 'function', '\'pwmpin\' does not provide \'setDutyCycleSync\' function'); assert.equal(typeof pwmpin.setEnable, 'function', '\'pwmpin\' does not provide \'setEnable\' function'); assert.equal(typeof pwmpin.setEnableSync, 'function', '\'pwmpin\' does not provide \'setEnableSync\' function'); assert.equal(typeof pwmpin.close, 'function', '\'pwmpin\' does not provide \'close\' function'); assert.equal(typeof pwmpin.closeSync, 'function', '\'pwmpin\' does not provide \'closeSync\' function'); } // ------ Test synchronous PWM Pin opening assert.throws( function() { pwm.openSync({period: 0.1, dutyCycle: 0.5}); }, TypeError ); assert.throws( function() { pwm.openSync({pin: 0, period: 0.1, dutyCycle: 1.1}); }, RangeError ); assert.throws( function() { pwm.openSync({pin: 0, period: -0.1, dutyCycle: 0.5}); }, RangeError ); assert.throws( function() { pwm.openSync({}); }, TypeError ); var config = { pin: 0, period: 0.1, dutyCycle: 0.5 } var pwmpin = pwm.openSync(config); check_pwmpin(pwmpin); assert.doesNotThrow( function() { pwmpin.setPeriodSync(1); } ); assert.throws( function() { pwmpin.setPeriodSync(); }, Error ); assert.throws( function() { pwmpin.setPeriodSync(null); }, Error ); assert.doesNotThrow( function() { pwmpin.setFrequencySync(1); } ); assert.throws( function() { pwmpin.setFrequencySync(); }, Error ); assert.throws( function() { pwmpin.setFrequencySync(null); }, Error ); assert.doesNotThrow( function() { pwmpin.setDutyCycleSync(1); } ); assert.throws( function() { pwmpin.setDutyCycleSync(); }, Error ); assert.throws( function() { pwmpin.setDutyCycleSync(null); }, Error ); assert.doesNotThrow( function() { pwmpin.setEnableSync(false); } ); assert.throws( function() { pwmpin.setEnableSync(); }, Error ); assert.throws( function() { pwmpin.setEnableSync(null); }, Error ); pwmpin.closeSync(); // ------ Test asynchronous PWM Pin opening pwm.open(config, function(open_err, async_pwmpin) { assert.equal(open_err, null); open_cb1 = true; assert.throws( function() { pwmpin.setPeriod(); }, Error ); assert.throws( function() { pwmpin.setPeriod(null); }, Error ); assert.throws( function() { pwmpin.setFrequency(); }, Error ); assert.throws( function() { pwmpin.setFrequency(null); }, Error ); assert.throws( function() { pwmpin.setDutyCycle(); }, Error ); assert.throws( function() { pwmpin.setDutyCycle(null); }, Error ); assert.throws( function() { pwmpin.setEnableSync(); }, Error ); assert.throws( function() { pwmpin.setEnableSync(null); }, Error ); async_pwmpin.setPeriod(1, function(period_err) { assert.equal(period_err, null); period_cb1 = true; async_pwmpin.setFrequency(1, function(frequency_err, res) { assert.equal(frequency_err, null); frequency_cb1 = true; async_pwmpin.setDutyCycle(1, function(dutycycle_err, res) { assert.equal(dutycycle_err, null); dutycycle_cb1 = true; async_pwmpin.setEnable(true, function(enable_err, res) { assert.equal(enable_err, null); enable_cb1 = true; async_pwmpin.close(function(close_err) { assert.equal(close_err, null); close_cb1 = true; }); }); }); }); }); }); process.on('exit', function(code) { if (code === 0) { assert.assert(open_cb1, 'callback of \'pwm.open\' was not called'); assert.assert(close_cb1, 'callback of \'pwm.close\' was not called'); assert.assert(period_cb1, 'callback of \'pwmpin.setPeriod\' was not called'); assert.assert(frequency_cb1, 'callback of \'pwmpin.setFrequency\' was not called'); assert.assert(dutycycle_cb1, 'callback of \'pwmpin.setDutyCycle\' was not called'); assert.assert(enable_cb1, 'callback of \'pwmpin.setEnable\' was not called'); } }); iotjs-1.0+715/test/run_pass/test_pwm_async.js000066400000000000000000000045721371177304000212330ustar00rootroot00000000000000/* 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 pwm = require('pwm'); var pin = require('tools/systemio_common').pin; var checkError = require('tools/systemio_common').checkError; var dutyCycles = [0.25, 0.5, 0.75], frequencies = [1, 10, 30], periodInit = false, dutyCycleInit = false; var configuration = { period: 0.001, // 1kHz dutyCycle: dutyCycles[0], pin: pin.pwm1 }; function initPwm(pwm) { pwm.setPeriod(0.001, function(err) { checkError(err); periodInit = true; }); pwm.setDutyCycle(0.5, function(err) { checkError(err); dutyCycleInit = true; }); } var pwm0 = null; pwm0 = pwm.open(configuration, function (err) { console.log('PWM initialized'); checkError(err); pwm0.setEnable(true, checkError); dutyCycleTest(); }); function dutyCycleTest() { var loopCnt = 0; var loop = setInterval(function() { if (pwm0 === null) { return; } if (loopCnt >= dutyCycles.length) { clearInterval(loop); initPwm(pwm0); console.log('PWM duty-cycle test complete'); frequencyTest(); return; } console.log("dutycycle(%d)", dutyCycles[loopCnt]); pwm0.setDutyCycle(dutyCycles[loopCnt++], checkError); }, 1000); } function frequencyTest() { var loopCnt = 0; var loop = setInterval(function() { if (!dutyCycleInit || !periodInit) { return; } if (loopCnt >= frequencies.length) { clearInterval(loop); pwm0.setEnable(false, function(err) { checkError(err); pwm0.close(function(err) { checkError(err); console.log('PWM frequency test complete'); }); }); return; } console.log("frequency(%d)", frequencies[loopCnt]); pwm0.setFrequency(frequencies[loopCnt++], checkError); }, 2000); } iotjs-1.0+715/test/run_pass/test_pwm_sync.js000066400000000000000000000037461371177304000210740ustar00rootroot00000000000000/* 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 pwm = require('pwm'); var pin = require('tools/systemio_common').pin; var checkError = require('tools/systemio_common').checkError; var dutyCycles = [0.25, 0.5, 0.75], frequencies = [1, 10, 30]; var configuration = { period: 0.001, // 1kHz dutyCycle: dutyCycles[0], pin: pin.pwm1 }; function initPwm(pwm) { pwm.setPeriodSync(0.001); pwm.setDutyCycleSync(0.5); } var pwm0 = null; pwm0 = pwm.openSync(configuration); console.log('PWM initialized'); pwm0.setEnableSync(true); dutyCycleTest(); function dutyCycleTest() { var loopCnt = 0; var loop = setInterval(function() { if (pwm0 === null) { return; } if (loopCnt >= dutyCycles.length) { clearInterval(loop); initPwm(pwm0); console.log('PWM duty-cycle test complete'); frequencyTest(); return; } console.log("dutycycle(%d)", dutyCycles[loopCnt]); pwm0.setDutyCycleSync(dutyCycles[loopCnt++]); }, 1000); } function frequencyTest() { var loopCnt = 0; var loop = setInterval(function() { if (loopCnt >= frequencies.length) { clearInterval(loop); pwm0.setEnableSync(false); pwm0.closeSync(); console.log('PWM frequency test complete'); return; } console.log("frequency(%d)", frequencies[loopCnt]); pwm0.setFrequencySync(frequencies[loopCnt++]); }, 2000); } iotjs-1.0+715/test/run_pass/test_spi.js000066400000000000000000000046711371177304000200260ustar00rootroot00000000000000/* 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 pin = require('tools/systemio_common').pin; var configuration = { device: pin.spi1, // for Linux bus: pin.spi1, // for Tizen, TizenRT and Nuttx }; // ------ Test API existance assert.assert(spi.MODE, 'spi module does not provide \'MODE\' property'); assert.assert(spi.CHIPSELECT, 'spi module does not provide \'CHIPSELECT\' property'); assert.assert(spi.BITORDER, 'spi module does not provide \'BITORDER\' property'); assert.equal(typeof spi.open, 'function', 'spi does not provide \'open\' function'); assert.equal(typeof spi.openSync, 'function', 'spi does not provide \'openSync\' function'); // ------ Test basic API functions var data = 'Hello IoTjs'; var tx = new Buffer(data); var spi1 = spi.open(configuration, function(err) { assert.assert(err === null, 'spi.open failed: ' + err); assert.equal(typeof spi1.transfer, 'function', 'spibus does not provide \'transfer\' function'); assert.equal(typeof spi1.transferSync, 'function', 'spibus does not provide \'transferSync\' function'); assert.equal(typeof spi1.close, 'function', 'spibus does not provide \'close\' function'); assert.equal(typeof spi1.closeSync, 'function', 'spibus does not provide \'closeSync\' function'); spi1.transfer(tx, function(err, rx) { assert.assert(err === null, 'spibus.transfer failed: ' + err); spi1.close(function(err) { assert.assert(err === null, 'spibus.close failed: ' + err); testSync(); }); }); }); function testSync() { var spi2 = spi.open(configuration, function(err) { assert.assert(err === null, 'spi.open for sync test failed: ' + err); var rx = spi2.transferSync(tx); spi2.closeSync(); }); } iotjs-1.0+715/test/run_pass/test_spi_buffer_async.js000066400000000000000000000026151371177304000225500ustar00rootroot00000000000000/* 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 pin = require('tools/systemio_common').pin; var checkError = require('tools/systemio_common').checkError; var configuration = { device: pin.spi1, // for Linux bus: pin.spi1, // for Tizen, TizenRT and Nuttx }; // Buffer test var spi1 = spi.open(configuration, function(err) { checkError(err); var data = 'Hello IoTjs'; var tx = new Buffer(data); spi1.transfer(tx, function(err, rx) { checkError(err); var len = data.length; assert.equal(rx.length, len); var value = ''; for (var i = 0; i < len; i++) { value += String.fromCharCode(rx[i]); } console.log(value); assert.equal(value, data); spi1.close(function(err) { checkError(err); }); }); }); iotjs-1.0+715/test/run_pass/test_spi_buffer_sync.js000066400000000000000000000022711371177304000224050ustar00rootroot00000000000000/* Copyright 2018-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 pin = require('tools/systemio_common').pin; var configuration = { device: pin.spi1, // for Linux bus: pin.spi1, // for Tizen, TizenRT and Nuttx }; // Buffer test var spi1 = spi.openSync(configuration); var data = 'Hello IoTjs'; var tx = new Buffer(data); var rx = spi1.transferSync(tx); var len = data.length; assert.equal(rx.length, len); var value = ''; for (var i = 0; i < len; i++) { value += String.fromCharCode(rx[i]); } console.log(value); assert.equal(value, data); spi1.closeSync(); iotjs-1.0+715/test/run_pass/test_spi_mcp3008.js000066400000000000000000000030171371177304000211710ustar00rootroot00000000000000/* 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 pin = require('tools/systemio_common').pin; var checkError = require('tools/systemio_common').checkError; var configuration = { device: pin.spi1, // for Linux bus: pin.spi1, // for Tizen, TizenRT and Nuttx }; // mcp3008 test var channel = 0; var spi0 = spi.open(configuration, function(err) { checkError(err); var mode = (8 + channel) << 4; var tx = [1, mode, 0]; var rx = spi0.transferSync(tx); console.log(((rx[1] & 0x03) << 8) + rx[2]); var loopCnt = 10; var loop = setInterval(function() { spi0.transfer(tx, function(err, rx) { checkError(err); 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); }); iotjs-1.0+715/test/run_pass/test_stream.js000066400000000000000000000070551371177304000205250ustar00rootroot00000000000000/* 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 Readable = require('stream').Readable; var assert = require('assert'); var readable1 = new Readable(); var d = ""; var e = ""; readable1.on('error', function(err) { e += "."; }); readable1.on('data', function(data) { d += data.toString(); }); readable1.on('end', function() { e += 'e'; }); readable1.pause(); readable1.push('abcde'); readable1.push('12345'); assert.equal(d, ''); assert.equal(e, ''); readable1.resume(); assert.equal(d, 'abcde12345'); assert.equal(e, ''); readable1.push('a'); readable1.push('1'); readable1.push('b'); readable1.push('2'); assert.equal(d, 'abcde12345a1b2'); assert.equal(e, ''); assert.equal(readable1.isPaused(), false); readable1.pause(); assert.equal(d, 'abcde12345a1b2'); assert.equal(e, ''); assert.equal(readable1.isPaused(), true); // Pause the readable again. This should do nothing. readable1.pause(); assert.equal(readable1.isPaused(), true); readable1.push('c'); readable1.push('3'); readable1.push('d'); readable1.push('4'); assert.equal(d, 'abcde12345a1b2'); assert.equal(e, ''); readable1.resume(); assert.equal(d, 'abcde12345a1b2c3d4'); assert.equal(e, ''); readable1.push(null); assert.equal(d, 'abcde12345a1b2c3d4'); assert.equal(e, 'e'); readable1.push('push after eof'); assert.equal(d, 'abcde12345a1b2c3d4'); assert.equal(e, 'e.'); // Create a readable stream without the new keyword. var readable2 = Readable({encoding: 'utf8'}); // Push an invalid chunk into it. assert.throws(function() { readable2.push(undefined); }, TypeError); assert.throws(function() { readable2.push(5001); }, TypeError); assert.throws(function() { readable2.push(5001.5); }, TypeError); assert.throws(function() { readable2.push([]); }, TypeError); assert.throws(function() { readable2.push([5001, 'string']); }, TypeError); assert.throws(function() { readable2.push({}); }, TypeError); assert.throws(function() { readable2.push({obj: 'string', second: 5001}); }, TypeError); // Read with irregular parameters from an empty stream. assert.equal(readable2.read(-2), null); assert.equal(readable2.read(0), null); readable2.push('qwerty'); assert.equal(readable2.read(6), 'qwerty'); // Throw not implemented Error when we trying to read less length data. readable2.push('new-data'); assert.throws(function() { readable2.read(1); }, Error); var readable3 = new Readable(); var readable3End = false; var paused = false; var str = 'test'; readable3.on('data', function(data) { assert.equal(paused, true); assert.equal(data, str); }); readable3.on('end', function() { readable3End = true; }); readable3.pause(); readable3.push(str); readable3.push(null); setTimeout(function() { paused = true; readable3.resume(); }, 1000); // End on non-EOF stream var readable4 = new Readable(); readable4.length = 10; assert.throws(function() { readable4.push(null); }, Error); process.on('exit', function() { assert.equal(readable2 instanceof Readable, true); assert.equal(readable3End, true); }); iotjs-1.0+715/test/run_pass/test_stream_duplex.js000066400000000000000000000021521371177304000220770ustar00rootroot00000000000000/* 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 assert = require('assert'); var Duplex = require('stream').Duplex; var duplex = Duplex({ highWaterMark: 0 }); assert(duplex instanceof Duplex); assert(duplex.write); assert(duplex.read); var msg1 = 'message 1'; var msg2 = 'message 2'; duplex._write = function(chunk, callback) { assert.equal(chunk == msg1, true); duplex.push(msg2); duplex.end(); } duplex._readyToWrite(); duplex.write(msg1); process.on('exit', function() { assert.equal(duplex.read() == msg2, true); }); iotjs-1.0+715/test/run_pass/test_stream_pipe.js000066400000000000000000000116731371177304000215430ustar00rootroot00000000000000/* Copyright 2018-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 net = require('net'); var stream = require('stream'); var Duplex = stream.Duplex; var Readable = stream.Readable; var Writable = stream.Writable; var readable = new Readable(); var msg = []; var resp = []; // Test case 1: basic data correctness. var dest1 = new Writable(); msg.push('Hello'); dest1._write = function(chunk, callback, onwrite) { resp.push(chunk.toString()); } dest1._readyToWrite(); readable.pipe(dest1); readable.push(msg[0]); readable.unpipe(dest1); // Test case 2: serial piping. var dest2 = new Duplex(); var dest3 = new Duplex(); var dest4 = new Duplex(); msg.push('data'); dest2._write = function(chunk, callback, onwrite) { this.push(chunk); resp.push(chunk.toString()); } dest3._write = function(chunk, callback, onwrite) { this.push(chunk); resp.push(chunk.toString()); } dest4._write = function(chunk, callback, onwrite) { resp.push(chunk.toString()); } dest2._readyToWrite(); dest3._readyToWrite(); dest4._readyToWrite(); readable.pipe(dest2).pipe(dest3).pipe(dest4); readable.push(msg[1]); readable.unpipe(dest2); dest2.unpipe(dest3); dest3.unpipe(dest4); // Test case 3: unpipe test. var dest5 = new Writable(); var dest5_write_called = false; dest5._write = function(chunk, callback, onwrite) { dest5_write_called = true; } dest5._readyToWrite(); readable.pipe(dest5); readable.unpipe(dest5); readable.push('foo'); // Test case 4: pushing data to the readable stream // before piping it. var readable2 = new Readable(); var dest6 = new Writable(); msg.push('data before pipe'); dest6._write = function(chunk, callback, onwrite) { resp.push(chunk.toString()); } dest6._readyToWrite(); readable2.push(msg[2]); readable2.pipe(dest6); readable2.unpipe(dest6); // Test case 5: piping multiple destinations to a single Readable var readable3 = new Readable(); msg.push('Multiple pipe test'); var dest7 = new Writable(); var dest8 = new Duplex(); dest7._write = function(chunk, callback, onwrite) { resp.push(chunk.toString()); } dest8._write = function(chunk, callback, onwrite) { resp.push(chunk.toString()); } dest7._readyToWrite(); dest8._readyToWrite(); readable.pipe(dest7); readable.pipe(dest8); readable.push(msg[3]); readable.unpipe(dest7); readable.unpipe(dest8); // Test case 6: piping with net.Socket source msg.push('Hello from the server'); var server = net.createServer({}, function(socket) { socket.write(msg[4]); }); server.listen(8080); var dest9 = new Duplex(); dest9._write = function(chunk, callback, onwrite) { resp.push(chunk.toString()); this.emit('_write_done'); } // This is needed to make sure that the order of the results in the resp // array is correct. dest9.on('_write_done', testCase7); dest9._readyToWrite(); var socket = new net.Socket(); socket.pipe(dest9); socket.on('data', function(data) { socket.end(); }); socket.on('end', function() { socket.unpipe(dest9); server.close(); }); socket.connect({'port': 8080}); // Test case 7: piping with net.Socket destination function testCase7() { msg.push('Hello from the socket'); var server2 = net.createServer({}, function(socket) { socket.on('data', function(data) { resp.push(data.toString()); socket.end(); }); }); server2.listen(8081); var socket2 = new net.Socket(); socket2.on('data', function(data) { socket2.write(data); }); socket2.on('end', function() { server2.close(); }); var readable4 = new Readable(); readable4.pipe(socket2); socket2.connect({'port': 8081}); readable4.push(msg[5]); readable4.unpipe(socket2); socket2.end(); } // checking the results process.on('exit', function() { assert.equal(msg[0], resp[0], 'Basic data correctness test failed'); assert.equal(msg[1], resp[1], 'Serial pipe test failed'); assert.equal(msg[1], resp[2], 'Serial pipe test failed'); assert.equal(msg[1], resp[3], 'Serial pipe test failed'); assert.equal(dest5_write_called, false, 'Unpipe test failed'); assert.equal(msg[2], resp[4], 'Incorrect data when pushing to the ' + 'readable stream before piping'); assert.equal(msg[3], resp[5], 'Multiple piping test failed'); assert.equal(msg[3], resp[6], 'Multiple piping test failed'); assert.equal(msg[4], resp[7], 'net.Socket source piping test failed'); assert.equal(msg[5], resp[8], 'net.Socket destination piping test failed'); }); iotjs-1.0+715/test/run_pass/test_timers_arguments.js000066400000000000000000000030051371177304000226110ustar00rootroot00000000000000/* 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 assert = require('assert'); var util = require('util'); var timerFired = false; var shouldnotFired = false; setTimeout(function(a, b, c) { assert.equal(arguments.length, 3); assert.equal(arguments[0], 1); assert.equal(arguments[1], 2); assert.equal(arguments[2], 3); assert.equal(a, 1); assert.equal(b, 2); assert.equal(c, 3); timerFired = true; }, 100, 1, 2, 3); var i = 0; setInterval(function(list) { assert.equal(arguments.length, 1); assert(util.isArray(list)); assert.equal(list.length, 5); if (i >= list.length) { clearInterval(this); } else { assert.equal(list[i], i * i); i++; } }, 100, [0, 1, 4, 9, 16]); var t = setTimeout(function() { shouldnotFired = true; }, 100); clearTimeout(t); process.on('exit', function(code) { assert.equal(code, 0); assert(timerFired); assert.equal(i, 5); assert.equal(shouldnotFired, false); }); iotjs-1.0+715/test/run_pass/test_timers_error.js000066400000000000000000000055711371177304000217470ustar00rootroot00000000000000/* 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'); // Timeout without callback function. assert.throws(function() { setTimeout(1000); }, TypeError); // Timeout with invalid callback function parameter. assert.throws(function() { setTimeout({function: null}, 1000); }, TypeError); assert.throws(function() { setTimeout({function: null, value: function() {}}, 1000); }, TypeError); assert.throws(function() { setTimeout(null, 1000); }, TypeError); assert.throws(function() { setTimeout(undefined, 1000); }, TypeError); assert.throws(function() { setTimeout([10, 100, 1000], 1000); }, TypeError); assert.throws(function() { setTimeout('callback', 1000); }, TypeError); // ClearTimeout without timeout parameter. assert.doesNotThrow(function() { clearTimeout(); }); assert.throws(function() { clearTimeout('timeout'); }, Error); assert.throws(function() { clearTimeout(1000); }, Error); assert.doesNotThrow(function() { clearTimeout(null); }); assert.doesNotThrow(function() { clearTimeout(undefined); }); assert.throws(function() { clearTimeout({timeout: 1000}); }, Error); // SetInterval without callback function. assert.throws(function() { setInterval(10); }, TypeError); // SetInterval with invalid callback function parameter. assert.throws(function() { setInterval(1000, 10); }, TypeError); assert.throws(function() { setInterval('callback', 10); }, TypeError); assert.throws(function() { setInterval({function: null, value: function() {}}, 10); }, TypeError); assert.throws(function() { setInterval(null, 10); }, TypeError); assert.throws(function() { setInterval(undefined, 10); }, TypeError); assert.throws(function() { setInterval([10, 100, 1000], 10); }, TypeError); // ClearInterval without interval parameter. assert.doesNotThrow(function() { clearInterval(); }); // ClearInterval with invalid interval parameter. assert.doesNotThrow(function() { clearInterval(null); }); assert.doesNotThrow(function() { clearInterval(undefined); }); assert.throws(function() { clearInterval('interval'); }, Error); assert.throws(function() { clearInterval(1000); }, Error); assert.throws(function() { clearInterval([interval, 1000]); }, Error); assert.throws(function() { clearInterval({interval: function() {}, value: 1000}); }, Error); iotjs-1.0+715/test/run_pass/test_timers_simple.js000066400000000000000000000024541371177304000221040ustar00rootroot00000000000000/* 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 assert = require('assert'); var timerACnt = 0; var timerBCnt = 0; var timerCCnt = 0; var timerSequence = ''; var timerA = setTimeout(function() { timerSequence += 'A'; timerACnt++; }, 1000); var timerB = setInterval(function() { timerSequence += 'B'; timerBCnt++; if (timerBCnt > 5) { clearInterval(timerB); } }, 300); var timerC = setInterval(function() { timerSequence += 'C'; timerCCnt++; if (timerCCnt > 10) { clearInterval(timerC); } }, 0); process.on('exit', function(code) { assert.equal(code, 0); assert.equal(timerACnt, 1); assert.equal(timerBCnt, 6); assert.equal(timerCCnt, 11); assert.equal(timerSequence.length, 18); }); iotjs-1.0+715/test/run_pass/test_tizen_app_control.js000066400000000000000000000022431371177304000227550ustar00rootroot00000000000000/* Copyright 2018-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 tizen = require('tizen'); // Need to set target APP_ID e.g) app.control.receiver var app_id = ''; var data = { str: 'iotjs' }; // test: tizen.on tizen.on('appControl', function(msg) { console.log('appControl', msg); var extra_data = msg.extra_data; if(extra_data && extra_data.key === 'iotjs' ) { //test: tizen.launchAppControl try { var res = tizen.launchAppControl({ app_id: app_id, extra_data: data, }); console.log('Result', res); } catch(e) { console.log(e); } } }); iotjs-1.0+715/test/run_pass/test_tls_1.js000066400000000000000000000033401371177304000202450ustar00rootroot00000000000000/* Copyright 2018-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 fs = require('fs'); var tls = require('tls'); var tlsClientError_caught = false; var socket_handshake_error_caught = false; var port = 8080; var server_options = { rejectUnauthorized: false, isServer: true } var server = tls.createServer(server_options, function(socket) { }).listen(port, function() {}); server.on('tlsClientError', function(error) { tlsClientError_caught = error instanceof Error; server.close(); }); var socket_options = { host: '127.0.0.1', port: port, rejectUnauthorized: false } var socket = tls.connect(socket_options, function() {}); socket.on('error', function(error) { socket_handshake_error_caught = error instanceof Error; }); function createServerFailed(server_options) { assert.throws(function() { return tls.createServer(server_options); }); } createServerFailed({key: 0}); createServerFailed({cert: null}); createServerFailed({key: false, cert: 7}); createServerFailed({ca: true}); process.on('exit', function() { assert.equal(tlsClientError_caught, true); assert.equal(socket_handshake_error_caught, true); }); iotjs-1.0+715/test/run_pass/test_tls_2.js000066400000000000000000000046161371177304000202550ustar00rootroot00000000000000/* Copyright 2018-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 fs = require('fs'); var tls = require('tls'); var expected_client_msg = 'Client hello'; var expected_server_msg = 'Server hello'; var client_message = ''; var server_message = ''; var server_closed = false; var server_handshake_done = false; var error_caught = false; var handshake_done = false; var port = 8080; var server_options = { key: fs.readFileSync(process.cwd() + '/resources/my_key.key').toString(), cert: fs.readFileSync(process.cwd() + '/resources/my_crt.crt'), rejectUnauthorized: false, isServer: true }; var server = tls.createServer(server_options, function(socket1) { socket1.write('Server hello'); socket1.on('data', function(data) { client_message += data.toString(); }); }).listen(port, function() {}); server.on('secureConnection', function() { server_handshake_done = true; }); server.on('close', function() { server_closed = true; }); var socket_options = { host: '127.0.0.1', port: port, rejectUnauthorized: false } var socket1 = tls.connect(socket_options, function() {}); socket1.on('secureConnect', function() { handshake_done = true; }); socket1.on('end', function() { server.close(); }); socket1.on('data', function(data) { server_message += data.toString(); socket1.write('Client hello'); socket1.end(); }); var socket2 = tls.connect({host: '127.123.123.123', port: 444}, function() { socket2.end(); }); socket2.on('error', function(err) { error_caught = true; }); process.on('exit', function() { assert.equal(error_caught, true); assert.equal(handshake_done, true); assert.equal(server_handshake_done, true); assert.equal(client_message === expected_client_msg, true); assert.equal(server_message === expected_server_msg, true); assert.equal(server_closed, true); }); iotjs-1.0+715/test/run_pass/test_tls_3.js000066400000000000000000000050421371177304000202500ustar00rootroot00000000000000/* Copyright 2018-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 fs = require('fs'); var tls = require('tls'); var expected_client_msg = 'Client hello'; var expected_server_msg = 'Server hello'; var client_message = ''; var server_message = ''; var server_closed = false; var server_handshake_done = false; var handshake_done = false; var port = 8080; var server_options = { key: fs.readFileSync(process.cwd() + '/resources/my_key.key').toString(), cert: fs.readFileSync(process.cwd() + '/resources/my_crt.crt'), rejectUnauthorized: false, isServer: true }; var server = tls.createServer(server_options, function(socket) { socket.write('Server hello'); socket.on('data', function(data) { client_message = data.toString(); }); }).listen(port, function() {}); server.on('secureConnection', function() { server_handshake_done = true; }); server.on('close', function() { server_closed = true; }); var socket1 = tls.connect(port); socket1.on('secureConnect', function() { handshake_done = true; }); socket1.on('data', function(data) { server_message = data.toString(); socket1.write('Client hello'); socket1.end(); }); var socket2 = tls.connect(port, 'localhost'); socket2.on('secureConnect', function() { handshake_done = true; }); socket2.on('data', function(data) { server_message = data.toString(); socket2.write('Client hello'); socket2.end(); }); var socket3 = tls.connect(port, function() {}); socket3.on('secureConnect', function() { handshake_done = true; }); socket3.on('data', function(data) { server_message = data.toString(); socket3.write('Client hello'); socket3.end(); }); socket3.on('end', function() { server.close(); }); process.on('exit', function() { assert.equal(handshake_done, true); assert.equal(server_handshake_done, true); assert.equal(client_message === expected_client_msg, true); assert.equal(server_message === expected_server_msg, true); assert.equal(server_closed, true); }); iotjs-1.0+715/test/run_pass/test_tls_4.js000066400000000000000000000052431371177304000202540ustar00rootroot00000000000000/* Copyright 2018-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 fs = require('fs'); var tls = require('tls'); var expected_client_msg = 'Client hello'; var expected_server_msg = 'Server hello'; var client_message = ''; var server_message = ''; var server_closed = false; var server_handshake_done = false; var handshake_done = false; var port = 8080; var server_options = { key: fs.readFileSync(process.cwd() + '/resources/my_key.key').toString(), cert: fs.readFileSync(process.cwd() + '/resources/my_crt.crt'), rejectUnauthorized: false, isServer: true }; var server = tls.createServer(server_options, function(socket) { socket.write('Server hello'); socket.on('data', function(data) { client_message = data.toString(); }); }).listen(port, function() { }); server.on('secureConnection', function() { server_handshake_done = true; }); server.on('close', function() { server_closed = true; }); var socket_options = { rejectUnauthorized: false, } var socket1 = tls.connect(port, 'localhost', socket_options); socket1.on('secureConnect', function() { handshake_done = true; }); socket1.on('data', function(data) { server_message = data.toString(); socket1.write('Client hello'); socket1.end(); }); var socket2 = tls.connect(port, 'localhost', socket_options, function() {}); socket1.on('secureConnect', function() { handshake_done = true; }); socket2.on('data', function(data) { server_message = data.toString(); socket2.write('Client hello'); socket2.end(); }); var socket3 = tls.connect(port, 'localhost', function() {}); socket3.on('secureConnect', function(){ handshake_done = true; }); socket3.on('data', function(data) { server_message = data.toString(); socket3.write('Client hello'); socket3.end(); }); socket3.on('end', function() { server.close(); }); process.on('exit', function() { assert.equal(handshake_done, true); assert.equal(server_handshake_done, true); assert.equal(client_message === expected_client_msg, true); assert.equal(server_message === expected_server_msg, true); assert.equal(server_closed, true); }); iotjs-1.0+715/test/run_pass/test_tls_ca.js000066400000000000000000000070601371177304000204730ustar00rootroot00000000000000/* Copyright 2018-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 this test, we created a certificate authority, and signed a certificate request with it. Here are the steps taken: 1) created a secret rsa key for ourselves openssl genrsa -out my_key.key 2048 Verify (dump): openssl rsa -in my_key.key -noout -text 2) created a secret rsa key for our certificate authority (CA) openssl genrsa -out my_ca.key 2048 Verify (dump): openssl rsa -in my_ca.key -noout -text 3) created a certificate signing request (CSR), which is signed by the CA later openssl req -new -key my_key.pem -out my_csr.csr Country Name (2 letter code) [AU]:HU State or Province Name (full name) [Some-State]: Locality Name (eg, city) []:Szeged Organization Name (eg, company) [Internet Widgits Pty Ltd]:Trusted Organizational Unit Name (eg, section) []: Common Name (e.g. server FQDN or YOUR name) []:localhost Email Address []:trusted@localhost Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:ch+llenGe An optional company name []: Verify (dump): openssl req -in my_csr.csr -noout -text 4) created a self-signed certificate for the CA openssl req -new -x509 -key my_ca.key -out my_ca.crt Country Name (2 letter code) [AU]:HU State or Province Name (full name) [Some-State]: Locality Name (eg, city) []:Szeged Organization Name (eg, company) [Internet Widgits Pty Ltd]:My CA Organizational Unit Name (eg, section) []: Common Name (e.g. server FQDN or YOUR name) []:myca.org Email Address []:myca@myca.org Verify (dump): openssl x509 -in my_ca.crt -noout -text 5) sign our certificate signing request openssl x509 -req -in my_csr.csr -CA my_ca.crt -CAkey my_ca.key \ -CAcreateserial -out my_crt.crt Note: A my_ca.srl file is also created to record the already issued serial numbers. This file is needed for future certificate signings. Verify (dump): openssl x509 -in my_crt.crt -noout -text */ var tls = require('tls'); var assert = require('assert'); var fs = require('fs'); var port = 8080; var server_message = ''; var options = { key: fs.readFileSync(process.cwd() + '/resources/my_key.key').toString(), cert: fs.readFileSync(process.cwd() + '/resources/my_crt.crt') }; var server = tls.createServer(options, function(socket) { socket.write('Server hello'); }).listen(port); var sockOpts = { // The my_crt.crt certificate was issued for localhost as server FQDN // Anything else here (e.g. 127.0.0.1) makes the handshake failed host: 'localhost', port: port, rejectUnauthorized: true, ca: fs.readFileSync(process.cwd() + '/resources/my_ca.crt') } var socket = tls.connect(sockOpts, function() { socket.on('data', function(data) { server_message += data.toString(); socket.end(); server.close(); }); }); process.on('exit', function() { assert.equal(server_message, 'Server hello'); }); iotjs-1.0+715/test/run_pass/test_tls_stream_duplex.js000066400000000000000000000055041371177304000227650ustar00rootroot00000000000000/* Copyright 2018-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 stream = require('stream'); var tls = require('tls'); var assert = require('assert'); var fs = require('fs'); var tls1_message = 'Hello, this is tls1'; var tls1_expected_message = tls1_message; var tls2_message = 'Hello, this is tls2'; var tls2_expected_message = tls2_message; var tls1_received_message = ''; var tls2_received_message = ''; var tls1_received_encrypted = ''; var tls2_received_encrypted = ''; var handshake_done = false; var tls1_ended = false; var tls2_ended = false; var duplex1 = new stream.Duplex(); var duplex2 = new stream.Duplex(); duplex1._write = function(chunk, callback, onwrite) { duplex2.push(chunk); onwrite(); }; duplex2._write = function(chunk, callback, onwrite) { duplex1.push(chunk); onwrite(); }; duplex1._readyToWrite(); duplex2._readyToWrite(); var server_opts = { key: fs.readFileSync(process.cwd() + '/resources/my_key.key').toString(), cert: fs.readFileSync(process.cwd() + '/resources/my_crt.crt').toString(), isServer: true, rejectUnauthorized: false, }; var client_opts = { rejectUnauthorized: false, }; var tls1 = new tls.TLSSocket(duplex1, server_opts); var tls2 = new tls.TLSSocket(duplex2, client_opts); tls2.on('secureConnect', function() { handshake_done = true; }); tls1.on('data', function(data) { tls1_received_message += data.toString(); tls1.end(); }); tls1._socket.on('data', function(data) { tls1_received_encrypted += data.toString('hex'); }); tls2.on('data', function(data) { tls2_received_message += data.toString(); tls2.write(tls2_message); }); tls2._socket.on('data', function(data) { tls2_received_encrypted += data.toString('hex'); }); tls1.on('end', function() { tls1_ended = true; tls2.end(); }); tls2.on('end', function() { tls2_ended = true; }); tls1.write(tls1_message); process.on('exit', function() { assert.equal(tls1_received_message === tls2_expected_message, true); assert.equal(tls2_received_message === tls1_expected_message, true); assert.equal(tls1_received_encrypted === tls2_message, false); assert.equal(tls2_received_encrypted === tls1_message, false); assert.equal(handshake_done === true, true); assert.equal(tls1_ended === true, true); assert.equal(tls2_ended === true, true); }); iotjs-1.0+715/test/run_pass/test_uart.js000066400000000000000000000034401371177304000201770ustar00rootroot00000000000000/* 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 uart = require('uart'); var pin = require('tools/systemio_common').pin; var checkError = require('tools/systemio_common').checkError; var configuration = { device: pin.uart1, // for Linux, TizenRT and Nuttx port: pin.uart1, // for Tizen baudRate: 115200, dataBits: 8, }; writeTest(); function writeTest() { var serial = uart.openSync(configuration); console.log('open done'); serial.writeSync('Hello IoT.js.\n\r'); serial.closeSync(); console.log('close done'); writeReadTest(); } function writeReadTest() { var read = 0; var write = 0; var serial = uart.open(configuration, function(err) { checkError(err); console.log('open done'); serial.on('data', function(data) { console.log('read result: ' + data.toString()); read = 1; if (read && write) { serial.close(); console.log('close done'); } }); serial.write('Hello there?\n\r', function(err) { checkError(err); console.log('write done'); write = 1; if (read && write) { serial.close(function(err) { checkError(err); }); console.log('close done'); } }); }); } iotjs-1.0+715/test/run_pass/test_uart_api.js000066400000000000000000000016531371177304000210340ustar00rootroot00000000000000/* 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 uart = require('uart'); // ------ Test API existence assert.equal(typeof uart.open, 'function', 'uart does not provide \'open\' function'); assert.equal(typeof uart.openSync, 'function', 'uart does not provide \'openSync\' function'); iotjs-1.0+715/test/run_pass/test_util.js000066400000000000000000000143111371177304000202000ustar00rootroot00000000000000/* 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 util = require('util'); var assert = require('assert'); assert.equal(util.isNull(null), true); assert.equal(util.isNull(0), false); assert.equal(util.isNull('null'), false); assert.equal(util.isUndefined(undefined), true); assert.equal(util.isUndefined(0), false); assert.equal(util.isUndefined('undefined'), false); assert.equal(util.isNumber(0), true); assert.equal(util.isNumber(5001), true); assert.equal(util.isNumber(3.14), true); assert.equal(util.isNumber(-5001), true); assert.equal(util.isNumber('5000'), false); assert.equal(util.isNumber(null), false); assert.equal(util.isNumber([0,1,2,3,4,5]), false); assert.equal(util.isFinite(5001), true); assert.equal(util.isFinite(-5001), true); assert.equal(util.isFinite(3.14), true); assert.equal(util.isFinite(-3.14), true); assert.equal(util.isFinite(0), true); assert.equal(util.isFinite(Infinity), false); assert.equal(util.isBoolean(true), true); assert.equal(util.isBoolean(false), true); assert.equal(util.isBoolean(Boolean(5001)), true); assert.equal(util.isBoolean(Boolean(0)), true); assert.equal(util.isBoolean(Boolean(-5001)), true); assert.equal(util.isBoolean(Boolean('Hello IoT.js')), true); assert.equal(util.isString('Hello IoT.js'), true); assert.equal(util.isString(['Hello IoT.js']), false); assert.equal(util.isString(-5001), false); assert.equal(util.isString(5001), false); assert.equal(util.isString(null), false); var object = { value1: 0, value2: 5001, value3: -5001, value4: 3.14, value5: 'Hello IoT.js' }; assert.equal(util.isObject(object), true); assert.equal(util.isObject({obj: 5001}), true); assert.equal(util.isObject({obj: object}), true); assert.equal(util.isObject({}), true); assert.equal(util.isObject([5001]), true); assert.equal(util.isObject(['Hello IoT.js']), true); assert.equal(util.isObject(null), false); assert.equal(util.isObject(5001), false); assert.equal(util.isObject('Hello IoT.js'), false); var func1 = function() {}; assert.equal(util.isFunction(func1), true); assert.equal(util.isFunction(function(arg) {/*do nothing*/}), true); assert.equal(util.isFunction(null), false); assert.equal(util.isFunction(5001), false); assert.equal(util.isFunction([5001]), false); assert.equal(util.isFunction([func1]), false); assert.equal(util.isFunction({}), false); assert.equal(util.isFunction('Hello IoT.js'), false); var buff = new Buffer('Hello IoT.js'); assert.equal(util.isBuffer(buff), true); assert.equal(util.isBuffer(new Buffer(5001)), true); assert.equal(util.isBuffer(5001), false); assert.equal(util.isBuffer({}), false); assert.equal(util.isBuffer('5001'), false); assert.equal(util.isBuffer([5001]), false); assert.equal(util.isBuffer([buff]), false); assert.equal(util.isBuffer({obj: buff}), false); function Parent() {} function Child() {} util.inherits(Child, Parent); var child = new Child(); assert.equal(child instanceof Parent, true); assert.equal(child instanceof Buffer, false); assert.equal(util.format(), ''); assert.equal(util.format(''), ''); assert.equal(util.format(null), 'null'); assert.equal(util.format(true), 'true'); assert.equal(util.format(false), 'false'); assert.equal(util.format('Hello IoT.js'), 'Hello IoT.js'); assert.equal(util.format(5001), '5001'); assert.equal(util.format('%d', 5001.5), '5001.5'); assert.equal(util.format('Hello IoT.js - %d', 5001), 'Hello IoT.js - 5001'); assert.equal( util.format('%s IoT.js - %d', 'Hello', 5001), 'Hello IoT.js - 5001' ); assert.equal(util.format('%d%%', 5001), '5001%'); var json = { "first":"1st", "second":"2nd" }; assert.equal( util.format('%s: %j', 'Object', json), 'Object: {"first":"1st","second":"2nd"}' ); assert.equal( util.format('%d-%j-%s', 5001, json, 'IoT.js', 'end'), '5001-{"first":"1st","second":"2nd"}-IoT.js end' ); json.json = json; assert.equal(util.format('%j', json), '[Circular]'); assert.equal(util.format('%s', '5001'), '5001'); assert.equal(util.format('%j', '5001'), '"5001"'); assert.equal(util.format('%d%d', 5001), '5001%d'); assert.equal(util.format('%s%d%s%d', 'IoT.js ', 5001), 'IoT.js 5001%s%d'); assert.equal(util.format('%d%% %s', 100, 'IoT.js'), '100% IoT.js'); assert.equal(util.format(new Error('format')), 'Error: format'); var err1 = util.errnoException(3008, 'syscall', 'original message'); assert.equal(err1 instanceof Error, true); assert.equal(err1, 'Error: syscall error original message'); assert.equal(err1.code, 'error'); assert.equal(err1.errno, 'error'); assert.equal(err1.syscall, 'syscall'); var err2 = util.errnoException(1, 'getSyscall'); assert.equal(err2 instanceof Error, true); assert.equal(err2, 'Error: getSyscall error'); assert.equal(err2.code, 'error'); assert.equal(err2.errno, 'error'); assert.equal(err2.syscall, 'getSyscall'); var err3 = util.exceptionWithHostPort(1, 'syscall', '127.0.0.1', 5001, 'additional info'); assert.equal(err3 instanceof Error, true); assert.equal( err3, 'Error: syscall error 127.0.0.1:5001 - Local (additional info)' ); assert.equal(err3.code, 'error'); assert.equal(err3.errno, 'error'); assert.equal(err3.syscall, 'syscall'); assert.equal(err3.address, '127.0.0.1'); assert.equal(err3.port, 5001); var err4 = util.exceptionWithHostPort(3008, 'getSyscall', '127.0.0.1'); assert.equal(err4 instanceof Error, true); assert.equal( err4, 'Error: getSyscall error 127.0.0.1' ); assert.equal(err4.code, 'error'); assert.equal(err4.errno, 'error'); assert.equal(err4.syscall, 'getSyscall'); assert.equal(err4.address, '127.0.0.1'); iotjs-1.0+715/test/run_pass/test_websocket.js000066400000000000000000000030701371177304000212110ustar00rootroot00000000000000/* Copyright 2018-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 ws = require('websocket'); var assert = require('assert'); var websocket = new ws.Websocket(); var connected = false; var message_sent = 'Hello IoT.js WebSocket'; var message_received = null; var ping_sent = 'IoT.js ping message'; var ping_received = null; var close_string = 'Connection successfully closed'; websocket.connect('ws://echo.websocket.org', 80, '/', function() { connected = true; this.on('message', function(msg){ message_received = msg.toString(); }); this.ping(ping_sent, true, function(msg) { ping_received = msg.toString(); }); this.on('close', function(msg) { assert.equal(msg.code, '1000'); assert.equal(msg.reason, close_string); }); this.send(message_sent, {mask: true, binary: false}) this.close(close_string, 1000); }); process.on('exit', function() { assert.equal(connected, true); assert.equal(message_received, message_sent); assert.equal(ping_sent, ping_received); }); iotjs-1.0+715/test/run_pass/test_websocket_headercheck.js000066400000000000000000000031321371177304000235160ustar00rootroot00000000000000/* Copyright 2019-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 ws = require('websocket'); var http = require('http'); var websocket = new ws.Websocket(); var test_connected = false; var test_statuscode = -1; var server = new ws.Server({ port: 8001 }, function(srv) { console.log("Connected!"); test_connected = true; server.close() }); var client = http.request({ method: 'GET', port: 8001, headers: { // Test if multiple values for the Connection header is accepted 'Connection': 'keep-alive, Upgrade', 'Upgrade': 'websocket', 'Sec-WebSocket-Key': 'r3UXMybFKTPGuT2CK5cYGw==', 'Sec-WebSocket-Version': 13, } }, function(response) { // 101 Switching Protocols test_statuscode = response.statusCode; server.close(); }); client.end(); process.on('exit', function () { assert(test_connected, 'WebScoket server did not received connection event'); assert.equal(test_statusCode, 101, 'GET with multiple Connection value should return 101 status'); }); iotjs-1.0+715/test/run_pass/test_websocket_server.js000066400000000000000000000074701371177304000226070ustar00rootroot00000000000000/* Copyright 2018-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 websocket = require('websocket'); var assert = require('assert'); var http = require('http'); var client = new websocket.Websocket(); var client2 = new websocket.Websocket(); var client3 = new websocket.Websocket(); var message_sent = 'Hello IoT.js WebSocket'; var ping_sent = 'IoT.js ping message'; var close_string = 'Connection successfully closed'; var close_code = 1000; function listener(ws) { ws.on('message', function(msg) { assert.equal(message_sent, msg.toString(), 'Message received by the Server'); // echo ws.send(msg.toString(), {mask: true, binary: false}); }); ws.on('ping', function(msg) { assert.equal(ping_sent, msg.toString(), 'Ping received by the Server'); }); } // Test two clients connection var options = { port: 8081, }; var wss = new websocket.Server(options, listener); var address = wss.address(); wss.on('close', function(msg) { assert.equal(close_string, msg.reason, 'Close reason received by the Server1'); assert.equal(close_code, msg.code, 'Close code received by the Server1'); assert.equal(address.address, '0.0.0.0', 'Address of Server1'); assert.equal(address.family, 'IPv4', 'Ip family of Server1'); assert.equal(address.port, '8081', 'Port of Server1'); }); client.connect('ws://localhost', 8081, '/', function() { this.on('message', function(msg) { assert.equal(message_sent, msg.toString(), 'Message received by the Client1'); }); this.ping(ping_sent, true, function(msg) { assert.equal(ping_sent, msg.toString(), 'Ping received by the Client1'); }); this.on('close', function(msg) { assert.equal(close_string, msg.reason, 'Close reason received by the Client1'); assert.equal(close_code, msg.code, 'Close code received by the Client1'); }); // Client2 connect client2.connect('ws://localhost', 8081, '/'); client2.on('open', function() { // Broadcast then terminate all clients and close the server wss.broadcast(message_sent); wss.close(); }); this.send(message_sent, {mask: true, binary: false}); }); // Test http server upgrade to websocket var httpServer = http.createServer().listen(8082); options = { server: httpServer, }; var wss2 = new websocket.Server(options, listener); wss2.on('close', function(msg) { assert.equal(close_string, msg.reason, 'Close reason received by the Server2'); assert.equal(close_code, msg.code, 'Close code received by the Server2'); }); client3.connect('ws://localhost', 8082, '/', function() { this.on('message', function(msg) { assert.equal(message_sent, msg.toString(), 'Message received by the Client3'); wss2.close(); }); this.ping(ping_sent, true, function(msg) { assert.equal(ping_sent, msg.toString(), 'Ping received by the Client3'); }); this.on('close', function(msg) { assert.equal(close_string, msg.reason, 'Close reason received by the Client3'); assert.equal(close_code, msg.code, 'Close code received by the Client3'); }); this.send(message_sent, {mask: true, binary: false}); }); iotjs-1.0+715/test/run_pass/test_websocket_server_secure.js000066400000000000000000000101401371177304000241410ustar00rootroot00000000000000/* Copyright 2018-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 websocket = require('websocket'); var assert = require('assert'); var fs = require('fs'); var tls = require('tls'); var key = fs.readFileSync(process.cwd() + '/resources/my_key.key').toString(); var cert = fs.readFileSync(process.cwd() + '/resources/my_crt.crt'); var client = new websocket.Websocket(); var client2 = new websocket.Websocket(); var client3 = new websocket.Websocket(); var message_sent = 'Hello IoT.js WebSocket'; var ping_sent = 'IoT.js ping message'; var close_string = 'Connection successfully closed'; var close_code = 1000; function listener(ws) { ws.on('message', function(msg) { assert.equal(message_sent, msg.toString(), 'Message received by the Server'); // echo ws.send(msg.toString(), {mask: true, binary: false}); }); ws.on('ping', function(msg) { assert.equal(ping_sent, msg.toString(), 'Ping received by the Server'); }); } // Test two clients connection var options = { port: 8081, secure: true, key: key, cert: cert, }; var wss = new websocket.Server(options, listener); var address = wss.address(); wss.on('close', function(msg) { assert.equal(close_string, msg.reason, 'Close reason received by the Server1'); assert.equal(close_code, msg.code, 'Close code received by the Server1'); assert.equal(address.address, '0.0.0.0', 'Address of Server1'); assert.equal(address.family, 'IPv4', 'Ip family of Server1'); assert.equal(address.port, '8081', 'Port of Server1'); }); client.connect('wss://localhost', 8081, '/', function() { this.on('message', function(msg) { assert.equal(message_sent, msg.toString(), 'Message received by the Client1'); }); this.ping(ping_sent, true, function(msg) { assert.equal(ping_sent, msg.toString(), 'Ping received by the Client1'); }); this.on('close', function(msg) { assert.equal(close_string, msg.reason, 'Close reason received by the Client1'); assert.equal(close_code, msg.code, 'Close code received by the Client1'); }); // Client2 connect client2.connect('wss://localhost', 8081, '/'); client2.on('open', function() { // Broadcast then terminate all clients and close the server wss.broadcast(message_sent); wss.close(); }); this.send(message_sent, {mask: true, binary: false}); }); // Test tls server upgrade to websocket var tlsOptions = { key: key, cert: cert, isServer: true, }; var tlsServer = tls.createServer(tlsOptions).listen(8082); options = { server: tlsServer, }; var wss2 = new websocket.Server(options, listener); wss2.on('close', function(msg) { assert.equal(close_string, msg.reason, 'Close reason received by the Server2'); assert.equal(close_code, msg.code, 'Close code received by the Server2'); }); client3.connect('wss://localhost', 8082, '/', function() { this.on('message', function(msg) { assert.equal(message_sent, msg.toString(), 'Message received by the Client3'); wss2.close(); }); this.ping(ping_sent, true, function(msg) { assert.equal(ping_sent, msg.toString(), 'Ping received by the Client3'); }); this.on('close', function(msg) { assert.equal(close_string, msg.reason, 'Close reason received by the Client3'); assert.equal(close_code, msg.code, 'Close code received by the Client3'); }); this.send(message_sent, {mask: true, binary: false}); }); iotjs-1.0+715/test/testsets.json000066400000000000000000000631361371177304000165560ustar00rootroot00000000000000{ "run_pass": [ { "name": "test_adc.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "adc" ] }, { "name": "test_assert.js" }, { "name": "test_ble_advertisement.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "ble" ] }, { "name": "test_ble_setservices.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "ble" ] }, { "name": "test_ble_setservices_central.js", "skip": [ "all" ], "reason": "run it with nodejs after running test_ble_setservices.js" }, { "name": "test_buffer.js" }, { "name": "test_buffer_from.js" }, { "name": "test_buffer_from_arraybuffer.js", "required-features": [ "ArrayBuffer" ] }, { "name": "test_buffer_str_conv.js" }, { "name": "test_buffer_inmutability_creation.js" }, { "name": "test_console.js", "required-modules": [ "console" ] }, { "name": "test_crypto.js", "required-modules": [ "crypto" ] }, { "name": "test_crypto_tls.js", "required-modules": [ "crypto", "fs", "tls" ] }, { "name": "test_dgram_1_server_1_client.js", "required-modules": [ "dgram" ] }, { "name": "test_dgram_1_server_n_clients.js", "skip": [ "linux" ], "reason": "[linux]: flaky on Travis", "required-modules": [ "dgram" ] }, { "name": "test_dgram_address.js", "required-modules": [ "dgram" ] }, { "name": "test_dgram_broadcast.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "dgram" ] }, { "name": "test_dgram_multicast_membership.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "dgram" ] }, { "name": "test_dgram_multicast_set_multicast_loop.js", "required-modules": [ "dgram" ] }, { "name": "test_dgram_setttl_client.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "dgram" ] }, { "name": "test_dgram_setttl_server.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "dgram" ] }, { "name": "test_dns.js", "required-modules": [ "net" ] }, { "name": "test_dns_lookup.js", "required-modules": [ "dns" ] }, { "name": "test_events.js", "required-modules": [ "events" ] }, { "name": "test_events_assert_emit_error.js", "required-modules": [ "events" ] }, { "name": "test_events_uncaught_error.js", "required-modules": [ "events" ] }, { "name": "test_fs_exists.js", "required-modules": [ "fs" ] }, { "name": "test_fs_exists_sync.js", "required-modules": [ "fs" ] }, { "name": "test_fs_fstat.js", "skip": [ "nuttx", "tizenrt" ], "reason": "not implemented for nuttx/TizenRT", "required-modules": [ "fs" ] }, { "name": "test_fs_fstat_sync.js", "skip": [ "nuttx", "tizenrt" ], "reason": "not implemented for nuttx/TizenRT", "required-modules": [ "fs" ] }, { "name": "test_fs_mkdir_rmdir.js", "skip": [ "nuttx" ], "reason": "[nuttx]: implemented, run manually in default configuration", "required-modules": [ "fs" ] }, { "name": "test_fs_open_close.js", "skip": [ "nuttx" ], "reason": "not implemented for nuttx", "required-modules": [ "fs" ] }, { "name": "test_fs_read_stream.js", "required-modules": [ "fs" ] }, { "name": "test_fs_readdir.js", "required-modules": [ "fs" ] }, { "name": "test_fs_readfile.js", "required-modules": [ "fs" ] }, { "name": "test_fs_readfile_sync.js", "required-modules": [ "fs" ] }, { "name": "test_fs_rename.js", "skip": [ "nuttx" ], "reason": "depends on the type of the memory (testrunner uses Read Only Memory)", "required-modules": [ "fs" ] }, { "name": "test_fs_rename_sync.js", "skip": [ "nuttx" ], "reason": "depends on the type of the memory (testrunner uses Read Only Memory)", "required-modules": [ "fs" ] }, { "name": "test_fs_stat.js", "required-modules": [ "fs" ] }, { "name": "test_fs_stream_pipe.js", "skip": [ "all" ], "reason": "flaky on Travis", "required-modules": [ "fs" ] }, { "name": "test_fs_write.js", "skip": [ "nuttx" ], "reason": "not implemented for nuttx", "required-modules": [ "fs" ] }, { "name": "test_fs_write_stream.js", "skip": [ "nuttx" ], "reason": "depends on the type of the memory (testrunner uses Read Only Memory)", "required-modules": [ "fs" ] }, { "name": "test_fs_writefile.js", "skip": [ "nuttx" ], "reason": "depends on the type of the memory (testrunner uses Read Only Memory)", "required-modules": [ "fs" ] }, { "name": "test_fs_writefile_sync.js", "skip": [ "nuttx" ], "reason": "depends on the type of the memory (testrunner uses Read Only Memory)", "required-modules": [ "fs" ] }, { "name": "test_fs_writefile_unlink.js", "skip": [ "nuttx" ], "reason": "depends on the type of the memory (testrunner uses Read Only Memory)", "required-modules": [ "fs" ] }, { "name": "test_fs_writefile_unlink_sync.js", "skip": [ "nuttx" ], "reason": "depends on the type of the memory (testrunner uses Read Only Memory)", "required-modules": [ "fs" ] }, { "name": "test_fs_event.js", "skip": [ "nuttx" ], "reason": "not implemented for nuttx", "required-modules": [ "fs" ] }, { "name": "test_fs_open_read.js", "required-modules": [ "fs" ] }, { "name": "test_fs_open_read_sync_1.js", "skip": [ "nuttx" ], "reason": "not implemented for nuttx", "required-modules": [ "fs" ] }, { "name": "test_fs_open_read_sync_2.js", "required-modules": [ "fs" ] }, { "name": "test_fs_open_read_sync_3.js", "required-modules": [ "fs" ] }, { "name": "test_gpio_api.js", "skip": [ "linux", "nuttx", "tizen", "tizenrt", "windows" ], "reason": "need to setup test environment", "required-modules": [ "gpio" ] }, { "name": "test_gpio_direction.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "gpio" ] }, { "name": "test_gpio_input.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "gpio" ] }, { "name": "test_gpio_output.js", "skip": [ "linux", "nuttx", "tizen", "tizenrt", "windows" ], "reason": "need to setup test environment", "required-modules": [ "gpio" ] }, { "name": "test_http_signature.js", "required-modules": [ "http_signature" ] }, { "name": "test_i2c_api.js", "skip": [ "linux", "nuttx", "tizen", "tizenrt", "windows" ], "reason": "need to setup test environment", "required-modules": [ "i2c" ] }, { "name": "test_i2c_gy30.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "i2c" ] }, { "name": "test_iotjs_promise.js", "required-features": [ "Promise" ] }, { "name": "test_iotjs_promise_chain_calls.js", "required-modules": [ "fs" ], "required-features": [ "Promise" ] }, { "name": "test_module_cache.js" }, { "name": "test_module_json.js" }, { "name": "test_module_require.js" }, { "name": "test_mqtt.js", "required-modules": [ "mqtt" ] }, { "name": "test_mqtt_frags.js", "required-modules": [ "mqtt" ] }, { "name": "test_net_1.js", "required-modules": [ "net" ] }, { "name": "test_net_2.js", "required-modules": [ "net" ] }, { "name": "test_net_3.js", "skip": [ "nuttx" ], "reason": "[nuttx]: requires too many socket descriptors and too large buffers", "required-modules": [ "net" ] }, { "name": "test_net_4.js", "required-modules": [ "net", "timers" ] }, { "name": "test_net_5.js", "required-modules": [ "net", "timers" ] }, { "name": "test_net_6.js", "required-modules": [ "net", "timers" ] }, { "name": "test_net_7.js", "skip": [ "nuttx" ], "reason": "requires too many socket descriptors", "required-modules": [ "net", "timers" ] }, { "name": "test_net_8.js", "required-modules": [ "net", "timers" ] }, { "name": "test_net_9.js", "required-modules": [ "net" ] }, { "name": "test_net_10.js", "required-modules": [ "net" ] }, { "name": "test_net_connect.js", "required-modules": [ "net" ] }, { "name": "test_net_headers.js", "required-modules": [ "http" ] }, { "name": "test_net_http_get.js", "required-modules": [ "http" ] }, { "name": "test_net_http_outgoing_buffer.js", "required-modules": [ "http" ] }, { "name": "test_net_http_methods.js", "required-modules": [ "http" ] }, { "name": "test_net_http_response_twice.js", "required-modules": [ "http", "net" ] }, { "name": "test_net_http_request_response.js", "skip": [ "nuttx" ], "reason": "not implemented for nuttx", "required-modules": [ "http", "net" ] }, { "name": "test_net_http_request_http_version.js", "required-modules": [ "http" ] }, { "name": "test_net_http_status_codes.js", "required-modules": [ "http" ] }, { "name": "test_net_http_modified_request.js", "required-modules": [ "http" ] }, { "name": "test_net_http_modified_response.js", "required-modules": [ "http" ] }, { "name": "test_net_http_modified_req_resp.js", "required-modules": [ "http" ] }, { "name": "test_net_httpclient_error.js", "required-modules": [ "http" ] }, { "name": "test_net_httpclient_parse_error.js", "required-modules": [ "http", "net" ] }, { "name": "test_net_httpclient_timeout_1.js", "required-modules": [ "http", "net" ] }, { "name": "test_net_httpclient_timeout_2.js", "required-modules": [ "http" ] }, { "name": "test_net_http_server_timeout.js", "required-modules": [ "http" ] }, { "name": "test_net_http_server.js", "required-modules": [ "http" ] }, { "name": "test_net_https_get.js", "timeout": 10, "required-modules": [ "https" ] }, { "name": "test_net_https_post_status_codes.js", "timeout": 10, "required-modules": [ "https" ] }, { "name": "test_net_https_request_response.js", "timeout": 10, "required-modules": [ "https", "http", "net" ] }, { "name": "test_net_https_modified_req_resp.js", "required-modules": [ "https", "http", "net" ] }, { "name": "test_net_https_timeout.js", "timeout": 10, "required-modules": [ "https" ] }, { "name": "test_net_https_server.js", "timeout": 10, "required-modules": [ "https", "fs" ] }, { "name": "test_process.js" }, { "name": "test_process_chdir.js" }, { "name": "test_process_cwd.js" }, { "name": "test_process_exit.js" }, { "name": "test_process_experimental_off.js", "skip": [ "experimental" ], "reason": "needed if testing stablity is set with stable" }, { "name": "test_process_experimental_on.js", "skip": [ "stable" ], "reason": "needed if testing stablity is set with experimental" }, { "name": "test_process_next_tick.js" }, { "name": "test_process_uncaught_order.js" }, { "name": "test_process_uncaught_simple.js" }, { "name": "test_pwm_api.js", "skip": [ "linux", "nuttx", "tizen", "tizenrt", "windows" ], "reason": "need to setup test environment", "required-modules": [ "pwm" ] }, { "name": "test_pwm_async.js", "skip": [ "linux", "nuttx", "tizen", "tizenrt", "windows" ], "reason": "need to setup test environment", "required-modules": [ "pwm" ] }, { "name": "test_pwm_sync.js", "skip": [ "linux", "nuttx", "tizen", "tizenrt", "windows" ], "reason": "need to setup test environment", "required-modules": [ "pwm" ] }, { "name": "test_spi.js", "skip": [ "linux" ], "reason": "Different env on Linux desktop/travis/rpi", "required-modules": [ "spi" ] }, { "name": "test_spi_buffer_async.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "spi" ] }, { "name": "test_spi_buffer_sync.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "spi" ] }, { "name": "test_spi_mcp3008.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "spi" ] }, { "name": "test_stream.js", "required-modules": [ "stream" ] }, { "name": "test_stream_duplex.js", "required-modules": [ "stream" ] }, { "name": "test_stream_pipe.js", "required-modules": [ "stream" ] }, { "name": "test_timers_arguments.js" }, { "name": "test_timers_error.js" }, { "name": "test_timers_simple.js", "timeout": 10 }, { "name": "test_tizen_app_control.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "tizen" ] }, { "name": "test_tls_1.js", "required-modules": [ "tls", "fs" ] }, { "name": "test_tls_2.js", "required-modules": [ "tls", "fs" ] }, { "name": "test_tls_3.js", "required-modules": [ "tls", "fs" ] }, { "name": "test_tls_4.js", "required-modules": [ "tls", "fs" ] }, { "name": "test_tls_ca.js", "required-modules": [ "tls", "fs" ] }, { "name": "test_tls_stream_duplex.js", "required-modules": [ "tls", "fs", "stream" ] }, { "name": "test_uart.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "uart" ] }, { "name": "test_uart_api.js", "required-modules": [ "uart" ] }, { "name": "test_util.js", "required-modules": [ "util" ] }, { "name": "test_websocket.js", "required-modules": [ "websocket" ] }, { "name": "test_websocket_server.js", "required-modules": [ "websocket" ] }, { "name": "test_websocket_server_secure.js", "required-modules": [ "websocket", "tls" ] } ], "run_pass/issue": [ { "name": "issue-133.js" }, { "name": "issue-137.js" }, { "name": "issue-198.js" }, { "name": "issue-223.js", "required-modules": [ "net" ] }, { "name": "issue-266.js", "required-modules": [ "net" ] }, { "name": "issue-323.js", "required-modules": [ "fs" ] }, { "name": "issue-816.js", "required-modules": [ "buffer" ] }, { "name": "issue-1046.js", "required-modules": [ "buffer" ] }, { "name": "issue-1077.js" }, { "name": "issue-1101.js", "skip": [ "all" ], "reason": "need to setup test environment", "required-modules": [ "uart" ] }, { "name": "issue-1348.js" }, { "name": "issue-1463.js", "required-features": [ "Promise" ] }, { "name": "issue-1485.js" }, { "name": "issue-1507.js", "required-modules": [ "console" ] }, { "name": "issue-1557.js" }, { "name": "issue-1897.js", "required-modules": [ "websocket" ] }, { "name": "issue-1904.js", "required-modules": [ "dgram" ] } ], "run_fail": [ { "name": "test_assert_equal.js", "expected-failure": true }, { "name": "test_assert_fail.js", "expected-failure": true }, { "name": "test_assert_notequal.js", "expected-failure": true }, { "name": "test_events_emit_error.js", "expected-failure": true, "required-modules": [ "events" ] }, { "name": "test_fs_callbacks_called.js", "expected-failure": true, "required-modules": [ "fs" ] }, { "name": "test_iotjs_runtime_error.js", "expected-failure": true }, { "name": "test_iotjs_syntax_error.js", "expected-failure": true }, { "name": "test-issue-1349.js", "expected-failure": true, "required-modules": [ "dns" ] }, { "name": "test-issue-1360.js", "expected-failure": true }, { "name": "test-issue-1570.js", "expected-failure": true }, { "name": "test-issue-1915.js", "expected-failure": true, "required-modules": [ "uart" ] }, { "name": "test_module_require_invalid_file.js", "expected-failure": true }, { "name": "test_module_require_path_below_root.js", "expected-failure": true }, { "name": "test_process_exitcode_arg.js", "expected-failure": true }, { "name": "test_process_exitcode_var.js", "expected-failure": true }, { "name": "test_process_explicit_exit.js", "expected-failure": true }, { "name": "test_process_implicit_exit.js", "expected-failure": true }, { "name": "test_timers_issue_1353.js", "expected-failure": true }, { "name": "test-issue-1917.js", "expected-failure": true, "required-modules": [ "fs" ] } ], "node/parallel": [ { "name": "test-assert.js", "required-modules": [ "fs", "stream" ] }, { "name": "test-module-circular.js", "required-modules": [ "fs", "stream" ] }, { "name": "test-http-catch-uncaughtexception.js", "required-modules": [ "http", "fs", "stream" ] }, { "name": "test-http-status-message.js", "required-modules": [ "http", "net", "fs", "stream" ] }, { "name": "test-http-write-head.js", "required-modules": [ "http", "fs", "stream" ] }, { "name": "test-net-bind-twice.js", "required-modules": [ "net", "fs", "stream" ] }, { "name": "test-net-end-without-connect.js", "required-modules": [ "net", "fs", "stream" ] }, { "name": "test-net-keepalive.js", "required-modules": [ "net", "fs", "stream" ] }, { "name": "test-timers-clear-null-does-not-throw-error.js", "required-modules": [ "fs", "stream" ] } ], "external_modules": [ { "name": "test-external-module1.js", "required-modules": [ "mymodule1" ] }, { "name": "test-external-module2.js", "required-modules": [ "mymodule2" ] } ], "napi": [ { "name": "test_napi_arguments_return.js", "required-modules": [ "napi" ] }, { "name": "test_napi_arguments_return_this.js", "required-modules": [ "napi" ] }, { "name": "test_napi_arguments_throw.js", "required-modules": [ "napi" ] }, { "name": "test_napi_array.js", "required-modules": [ "napi" ] }, { "name": "test_napi_async.js", "required-modules": [ "napi" ] }, { "name": "test_napi_buffer.js", "required-modules": [ "napi" ] }, { "name": "test_napi_construct.js", "required-modules": [ "napi" ] }, { "name": "test_napi_conversions.js", "required-modules": [ "napi" ] }, { "name": "test_napi_create_error.js", "required-modules": [ "napi" ] }, { "name": "test_napi_dataview.js", "required-features": [ "ArrayBuffer", "DataView" ], "required-modules": [ "napi" ] }, { "name": "test_napi_env.js", "required-modules": [ "napi" ] }, { "name": "test_napi_exception.js", "required-modules": [ "napi" ] }, { "name": "test_napi_general.js", "required-modules": [ "napi" ] }, { "name": "test_napi_general_es2015.js", "required-features": [ "ArrayBuffer", "Promise", "Symbol", "TypedArray" ], "required-modules": [ "napi" ] }, { "name": "test_napi_handle_scope.js", "required-modules": [ "napi" ] }, { "name": "test_napi_is_error.js", "required-modules": [ "napi" ] }, { "name": "test_napi_make_callback.js", "required-modules": [ "napi" ] }, { "name": "test_napi_make_callback_error.js", "required-modules": [ "napi" ] }, { "name": "test_napi_object_wrap.js", "required-modules": [ "napi" ] }, { "name": "test_napi_properties.js", "required-modules": [ "napi" ] }, { "name": "test_napi_reference.js", "required-modules": [ "napi" ] }, { "name": "test_napi_promise.js", "required-modules": [ "napi" ], "required-features": [ "Promise" ] }, { "name": "test_napi_strictequal_and_instanceof.js", "required-modules": [ "napi" ] }, { "name": "test_napi_string.js", "required-modules": [ "napi" ] }, { "name": "test_napi_symbol.js", "required-features": [ "Symbol" ], "required-modules": [ "napi" ] }, { "name": "test_napi_throw_error.js", "required-modules": [ "napi" ] }, { "name": "test_napi_throw.js", "required-modules": [ "napi" ] }, { "name": "test_napi_typedarray.js", "required-features": [ "ArrayBuffer", "TypedArray" ], "required-modules": [ "napi" ] } ] } iotjs-1.0+715/test/tmp/000077500000000000000000000000001371177304000145745ustar00rootroot00000000000000iotjs-1.0+715/test/tmp/README000066400000000000000000000001131371177304000154470ustar00rootroot00000000000000This directory is for temporary files will be generated during build test. iotjs-1.0+715/test/tools/000077500000000000000000000000001371177304000151345ustar00rootroot00000000000000iotjs-1.0+715/test/tools/iotjs_build_info.js000066400000000000000000000037531371177304000210240ustar00rootroot00000000000000/* 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. */ /* Just for the testrunner to get runtime information about the build. */ var builtins = process.builtin_modules; if (process.env.IOTJS_ENV.indexOf("experimental") > -1) stability = "experimental" else stability = "stable" /* Check if certain es2015 features are available */ function hasFeatures(object, features) { supported = true; for (feature in features) { supported = supported && object.hasOwnProperty(features[feature]); } return supported; } function hasArrowFunction() { try { eval("a => {}"); return true; } catch(e) {} return false; } var features = {}; var typedArrayFeatures = [ 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array' ]; if (hasFeatures(global, ['Symbol'])) features.Symbol = true; if (hasFeatures(global, ['Promise'])) features.Promise = true; if (hasFeatures(global, ['ArrayBuffer'])) features.ArrayBuffer = true; if (hasFeatures(global, ['DataView'])) features.DataView = true; if (hasFeatures(global, typedArrayFeatures)) features.TypedArray = true; if (hasArrowFunction()) features.ArrowFunction = true; result = { 'builtins': builtins, 'features': features, 'stability': stability, 'debug': !!process.debug, 'arch': process.arch } console.log(JSON.stringify(result)) iotjs-1.0+715/test/tools/systemio_common.js000066400000000000000000000034541371177304000207240ustar00rootroot00000000000000/* 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 pin = {}; if (process.platform === 'linux') { pin.led = 20; pin.switch = 13; pin.pwm1 = 0; pin.i2c1 = '/dev/i2c-1'; pin.spi1 = '/dev/spidev0.0'; pin.uart1 = '/dev/ttyS0'; } else if (process.platform === 'tizen') { if (process.iotjs.board === 'rpi3') { pin.led = 20; pin.switch = 13; pin.spi1 = 0; pin.uart1 = 0; } else if (process.iotjs.board === 'artik530') { pin.led = 128; pin.switch = 27; pin.pwm1 = 2; pin.spi1 = 2; pin.uart1 = 4; } pin.i2c1 = 1; } else if (process.platform === 'nuttx') { var board = process.iotjs.board; var stm32_pin = require(board).pin; pin.led = stm32_pin.PA10; pin.switch = stm32_pin.PA15; pin.pwm1 = stm32_pin.PWM1.CH1_1; pin.i2c1 = 1; pin.spi1 = 1; pin.uart1 = '/dev/ttyS1'; } else if (process.platform === 'tizenrt') { pin.led = 41; pin.switch = 39; pin.pwm1 = 0; pin.i2c1 = 1; pin.spi1 = 1; pin.uart1 = '/dev/ttyS1'; } else { throw new Error('Unsupported platform'); } function checkError(err) { if (err) { console.log('Have an error: ' + err.message); assert.fail(); } } exports.pin = pin; exports.checkError = checkError; iotjs-1.0+715/tools/000077500000000000000000000000001371177304000141555ustar00rootroot00000000000000iotjs-1.0+715/tools/__init__.py000066400000000000000000000001001371177304000162550ustar00rootroot00000000000000# Required for Python to search this directory for module files iotjs-1.0+715/tools/apt-get-install-arm.sh000077500000000000000000000013431371177304000202770ustar00rootroot00000000000000#!/bin/bash # 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. sudo apt-get update -q sudo apt-get install -q -y \ gcc-arm-linux-gnueabihf libc6-dev-armhf-cross iotjs-1.0+715/tools/apt-get-install-deps.sh000077500000000000000000000013311371177304000204500ustar00rootroot00000000000000#!/bin/bash # 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. sudo apt-get update -q sudo apt-get install -q -y \ cmake gcc valgrind clang-format-3.9 iotjs-1.0+715/tools/apt-get-install-nuttx.sh000077500000000000000000000015011371177304000206760ustar00rootroot00000000000000#!/bin/bash # 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. sudo apt-get update -q sudo apt-get install -q -y \ autoconf libtool gperf flex bison autoconf2.13 \ cmake libncurses-dev libusb-1.0-0-dev genromfs \ libsgutils2-dev gcc-arm-none-eabi iotjs-1.0+715/tools/apt-get-install-tizen.sh000077500000000000000000000017561371177304000206610ustar00rootroot00000000000000#!/bin/bash # 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. wget https://releases.linaro.org/components/\ toolchain/binaries/4.9-2017.01/arm-linux-gnueabi/\ gcc-linaro-4.9.4-2017.01-x86_64_arm-linux-gnueabi.tar.xz tar Jxf gcc-linaro-4.9.4-2017.01-x86_64_arm-linux-gnueabi.tar.xz mv gcc-linaro-4.9.4-2017.01-x86_64_arm-linux-gnueabi arm-linux-gnueabi export PATH=$(pwd)/arm-linux-gnueabi/bin:$PATH arm-linux-gnueabi-gcc --version iotjs-1.0+715/tools/apt-get-install-tizenrt.sh000077500000000000000000000013251371177304000212170ustar00rootroot00000000000000#!/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. sudo apt-get update sudo apt-get install gcc-arm-none-eabi arm-none-eabi-gcc --version iotjs-1.0+715/tools/apt-get-install-travis-i686.sh000077500000000000000000000013531371177304000215230ustar00rootroot00000000000000#!/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. sudo dpkg --add-architecture i386 sudo apt-get update -q sudo apt-get install -q -y \ linux-libc-dev:i386 iotjs-1.0+715/tools/brew-install-deps.sh000077500000000000000000000014251371177304000200520ustar00rootroot00000000000000#!/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. brew update PKGS=" cmake " for pkg in $PKGS do if ! ( brew list -1 | grep -q "^${pkg}\$" ) then brew install $pkg fi done iotjs-1.0+715/tools/build.py000077500000000000000000000430571371177304000156420ustar00rootroot00000000000000#!/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 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.executor import Terminal from common_py.system.sys_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] build_config = {} with open(config_path, 'rb') as f: build_config = json.loads(f.read().decode('ascii')) # Read config file and apply it to argv. argv = [] list_with_commas = ['external-modules'] for opt_key in build_config: opt_val = build_config[opt_key] if (opt_key in list_with_commas) and isinstance(opt_val, list): opt_val and argv.append('--%s=%s' % (opt_key, ','.join(opt_val))) elif isinstance(opt_val, basestring) and opt_val != '': argv.append(str('--%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(description='Building tool for IoT.js ' 'JavaScript framework for embedded systems.') iotjs_group = parser.add_argument_group('Arguments of IoT.js', 'The following arguments are related to the IoT.js framework.') iotjs_group.add_argument('--buildtype', choices=['debug', 'release'], default='debug', type=str.lower, help='Specify the build type (default: %(default)s).') iotjs_group.add_argument('--builddir', default=path.BUILD_ROOT, help='Specify the build directory (default: %(default)s)') iotjs_group.add_argument('--buildlib', action='store_true', default=False, help='Build IoT.js static library only (default: %(default)s)') iotjs_group.add_argument('--create-shared-lib', action='store_true', default=False, help='Create shared library (default: %(default)s)') iotjs_group.add_argument('--cmake-param', action='append', default=[], help='Specify additional cmake parameters ' '(can be used multiple times)') iotjs_group.add_argument('--compile-flag', action='append', default=[], help='Specify additional compile flags (can be used multiple times)') iotjs_group.add_argument('--clean', action='store_true', default=False, help='Clean build directory before build (default: %(default)s)') iotjs_group.add_argument('--config', default=path.BUILD_CONFIG_PATH, help='Specify the config file (default: %(default)s)', dest='config_path') iotjs_group.add_argument('-e', '--experimental', action='store_true', default=False, help='Enable to build experimental features') iotjs_group.add_argument('--external-include-dir', action='append', default=[], help='Specify additional external include directory ' '(can be used multiple times)') iotjs_group.add_argument('--external-lib', action='append', default=[], help='Specify additional external library ' '(can be used multiple times)') iotjs_group.add_argument('--external-modules', action='store', default=set(), type=lambda x: set(x.split(',')), help='Specify the path of modules.json files which should be processed ' '(format: path1,path2,...)') iotjs_group.add_argument('--link-flag', action='append', default=[], help='Specify additional linker flags (can be used multiple times)') iotjs_group.add_argument('--n-api', action='store_true', default=False, help='Enable to build N-API feature') iotjs_group.add_argument('--no-check-valgrind', action='store_true', default=False, help='Disable test execution with valgrind after build') iotjs_group.add_argument('--no-init-submodule', action='store_true', default=False, help='Disable initialization of git submodules') iotjs_group.add_argument('--no-parallel-build', action='store_true', default=False, help='Disable parallel build') iotjs_group.add_argument('--no-snapshot', action='store_true', default=False, help='Disable snapshot generation for IoT.js') iotjs_group.add_argument('--nuttx-home', default=None, dest='sysroot', help='Specify the NuttX base directory (required for NuttX build)') iotjs_group.add_argument('--profile', help='Specify the module profile file for IoT.js') iotjs_group.add_argument('--run-test', nargs='?', default=False, const="quiet", choices=["full", "quiet"], help='Execute tests after build, optional argument specifies ' 'the level of output for the testrunner') iotjs_group.add_argument('--sysroot', action='store', help='The location of the development tree root directory (sysroot). ' 'Must be compatible with used toolchain.') iotjs_group.add_argument('--target-arch', choices=['arm', 'x86', 'i686', 'x86_64', 'x64', 'mips', 'noarch'], default=platform.arch(), help='Specify the target architecture (default: %(default)s).') iotjs_group.add_argument('--target-board', choices=[None, 'artik10', 'stm32f4dis', 'stm32f7nucleo', 'rpi2', 'rpi3', 'artik05x'], default=None, help='Specify the target board (default: %(default)s).') iotjs_group.add_argument('--target-os', choices=['linux', 'darwin', 'osx', 'mock', 'nuttx', 'tizen', 'tizenrt', 'openwrt', 'windows'], default=platform.os(), help='Specify the target OS (default: %(default)s).') iotjs_group.add_argument('--expose-gc', action='store_true', default=False, help='Expose the JerryScript\'s GC call to JavaScript') jerry_group = parser.add_argument_group('Arguments of JerryScript', 'The following arguments are related to the JavaScript engine under ' 'the framework. For example they can change the enabled features of ' 'the ECMA-262 standard.') jerry_group.add_argument('--jerry-cmake-param', action='append', default=[], help='Specify additional cmake parameters for JerryScript ' '(can be used multiple times)') jerry_group.add_argument('--jerry-compile-flag', action='append', default=[], help='Specify additional compile flags for JerryScript ' '(can be used multiple times)') jerry_group.add_argument('--jerry-debugger', action='store_true', default=False, help='Enable JerryScript-debugger') jerry_group.add_argument('--jerry-heaplimit', type=int, default=build_config['jerry-heaplimit'], help='Specify the size of the JerryScript max heap size ' '(default: %(default)s)') jerry_group.add_argument('--jerry-heap-section', action='store', default=None, help='Specify the name of the JerryScript heap section') jerry_group.add_argument('--jerry-lto', action='store_true', default=False, help='Build JerryScript with LTO enabled') jerry_group.add_argument('--jerry-memstat', action='store_true', default=False, help='Enable JerryScript heap statistics') jerry_group.add_argument('--jerry-profile', metavar='FILE', action='store', default='es5.1', help='Specify the profile for JerryScript (default: %(default)s). ' 'Possible values are "es5.1", "es.next" or an absolute ' 'path to a custom JerryScript profile file.') jerry_group.add_argument('--js-backtrace', choices=['ON', 'OFF'], type=str.upper, help='Enable/disable backtrace information of JavaScript code ' '(default: ON in debug and OFF in release build)') options = parser.parse_args(argv) options.config = build_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 %s target' % options.target_os) 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', 'rpi3', 'artik10', 'artik05x']: options.no_check_valgrind = 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) # Normalize the path of build directory. options.builddir = fs.normpath(options.builddir) options.build_root = fs.join(path.PROJECT_ROOT, options.builddir, options.target_tuple, options.buildtype) cmake_path = fs.join(path.PROJECT_ROOT, 'cmake', 'config', '%s.cmake') options.cmake_toolchain_file = cmake_path % options.target_tuple # Set the default value of '--js-backtrace' if it is not defined. if not options.js_backtrace: if options.buildtype == 'debug': options.js_backtrace = "ON" else: options.js_backtrace = "OFF" 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): cmake_args = [] # compile flags compile_flags = options.compile_flag compile_flags += options.jerry_compile_flag cmake_args.append("-DEXTERNAL_COMPILE_FLAGS='%s'" % (' '.join(compile_flags))) # link flags link_flags = options.link_flag if options.jerry_lto: link_flags.append('-flto') cmake_args.append("-DEXTERNAL_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) elif options.target_board == 'stm32f7nucleo': include_dirs.append('%s/arch/arm/src/stm32f7' % options.sysroot) if options.target_os == 'tizenrt': include_dirs.append('%s/../framework/include/iotbus' % options.sysroot) elif options.target_os == 'windows': cmake_args.append("-GVisual Studio 15 2017") if options.target_arch == "x86_64": cmake_args.append("-Ax64") 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_ARCH=%s' % options.target_arch, '-DTARGET_OS=%s' % options.target_os, '-DTARGET_BOARD=%s' % options.target_board, '-DENABLE_LTO=%s' % get_on_off(options.jerry_lto), # --jerry-lto '-DENABLE_MODULE_NAPI=%s' % get_on_off(options.n_api), # --n-api '-DENABLE_SNAPSHOT=%s' % get_on_off(not options.no_snapshot), '-DEXPOSE_GC=%s' % get_on_off(options.expose_gc), # --exposing gc '-DBUILD_LIB_ONLY=%s' % get_on_off(options.buildlib), # --buildlib '-DCREATE_SHARED_LIB=%s' % get_on_off(options.create_shared_lib), # --jerry-memstat '-DJERRY_MEM_STATS=%s' % get_on_off(options.jerry_memstat), # --external-modules "-DEXTERNAL_MODULES='%s'" % ';'.join(options.external_modules), # --jerry-profile "-DJERRY_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('-DJERRY_GLOBAL_HEAP_SIZE=%d' % options.jerry_heaplimit) if options.jerry_heaplimit > 512: cmake_opt.append("-DEXTRA_JERRY_CMAKE_PARAMS='%s'" % "-DJERRY_CPOINTER_32_BIT=ON") # --jerry-heap-section if options.jerry_heap_section: cmake_opt.append("-DJERRY_ATTR_GLOBAL_HEAP='%s'" % options.jerry_heap_section) # --jerry-debugger if options.jerry_debugger: cmake_opt.append("-DJERRY_DEBUGGER=ON") # --js-backtrace cmake_opt.append("-DJERRY_LINE_INFO=%s" % options.js_backtrace) # --cmake-param cmake_opt.extend(options.cmake_param) # --external-lib cmake_opt.append("-DEXTERNAL_LIBS='%s'" % (' '.join(options.external_lib))) # --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: cmake_opt.append('-DEXPERIMENTAL=ON') # --profile if options.profile: cmake_opt.append("-DIOTJS_PROFILE='%s'" % options.profile) # Add common cmake options. cmake_opt.extend(build_cmake_args(options)) # Run cmake. ex.check_run_cmd('cmake', cmake_opt) if options.target_os == 'windows': print("\nPlease open the iot.js solution file in Visual Studio!") else: run_make(options, options.build_root) def run_checktest(options): # IoT.js executable iotjs = fs.join(options.build_root, 'bin', 'iotjs') cmd = fs.join(path.TOOLS_ROOT, 'testrunner.py') args = [iotjs, "--platform=%s" % options.target_os] if options.run_test == "quiet": args.append('--quiet') fs.chdir(path.PROJECT_ROOT) code = ex.run_cmd(cmd, args) if code != 0: ex.fail('Failed to pass unit tests') if not options.no_check_valgrind: code = ex.run_cmd(cmd, ['--valgrind'] + args) 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) if options.clean: print_progress('Clear build directories') test_build_root = fs.join(path.TEST_ROOT, 'napi', 'build') fs.rmtree(test_build_root) fs.rmtree(options.build_root) # Perform init-submodule. if not options.no_init_submodule: print_progress('Initialize submodule') init_submodule() build_iotjs(options) Terminal.pprint("\nIoT.js Build Succeeded!!\n", Terminal.green) # Run tests. if options.run_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') or (options.host_tuple == 'x86_64-linux' and options.target_tuple == 'x86_64-mock')): run_checktest(options) else: print("Skip unit tests - target-host pair is not allowed\n") else: Terminal.pprint("\nTo run tests use '--run-test' " "or one of the following commands:", Terminal.blue) print("\n tools/testrunner.py %s/%s/%s/bin/iotjs\n" % (options.builddir, options.target_tuple, options.buildtype)) iotjs-1.0+715/tools/check_license.py000077500000000000000000000036021371177304000173120ustar00rootroot00000000000000#!/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. import re from common_py import path from common_py.system.filesystem import FileSystem as fs EXCLUDE_DIRS = [ 'test/napi' ] class CheckLicenser(object): _license = re.compile( r'((#|//|\*) Copyright .*\n' r')+\s?\2\n' r'\s?\2 Licensed under the Apache License, Version 2.0 \(the "License"\);\n' r'\s?\2 you may not use this file except in compliance with the License.\n' r'\s?\2 You may obtain a copy of the License at\n' r'\s?\2\n' r'\s?\2 http://www.apache.org/licenses/LICENSE-2.0\n' r'\s?\2\n' r'\s?\2 Unless required by applicable law or agreed to in writing, software\n' r'\s?\2 distributed under the License is distributed on an "AS IS" BASIS\n' r'\s?\2 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' r'\s?\2 See the License for the specific language governing permissions and\n' r'\s?\2 limitations under the License.\n' ) @staticmethod def check(filename): if any(fs.relpath(filename).startswith(exclude) for exclude in EXCLUDE_DIRS): return True with open(filename, 'r') as f: contents = f.read() return bool(CheckLicenser._license.search(contents)) iotjs-1.0+715/tools/check_signed_off.sh000077500000000000000000000066621371177304000177660ustar00rootroot00000000000000#!/bin/bash # Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors # Copyright 2016 University of Szeged # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Usage function print_usage { echo "Usage: $0 [--help] [--tolerant] [--travis]" } function print_help { echo "$0: Check Signed-off-by message of the latest commit" echo "" print_usage echo "" echo "Optional arguments:" echo " --help print this help message" echo " --tolerant check the existence of the message only but don't" echo " require the name and email address to match the author" echo " of the commit" echo " --travis perform check in tolerant mode if on Travis CI and not" echo " checking a pull request, perform strict check otherwise" echo "" echo "The last line of every commit message must follow the form of:" echo "'IoT.js-DCO-1.0-Signed-off-by: NAME EMAIL', where NAME and EMAIL must" echo "match the name and email address of the author of the commit (unless in" echo "tolerant mode)." } # Processing command line TOLERANT="no" while [ "$#" -gt 0 ] do if [ "$1" == "--help" ] then print_help exit 0 elif [ "$1" == "--tolerant" ] then TOLERANT="yes" shift elif [ "$1" == "--travis" ] then if [ "$TRAVIS_PULL_REQUEST" == "" ] then echo -e "\e[1;33mWarning! Travis-tolerant mode requested but not running on Travis CI! \e[0m" elif [ "$TRAVIS_PULL_REQUEST" == "false" ] then TOLERANT="yes" else TOLERANT="no" fi shift else print_usage exit 1 fi done # Determining latest commit parent_hashes=(`git show -s --format=%p HEAD | head -1`) if [ "${#parent_hashes[@]}" -eq 1 ] then commit_hash=`git show -s --format=%h HEAD | head -1` elif [ "${#parent_hashes[@]}" -eq 2 ] then commit_hash=${parent_hashes[1]} else echo "$0: cannot handle commit with ${#parent_hashes[@]} parents ${parent_hashes[@]}" exit 1 fi # Checking the last line actual_signed_off_by_line=`git show -s --format=%B $commit_hash | sed '/^$/d' | tr -d '\015' | tail -n 1` if [ "$TOLERANT" == "no" ] then author_name=`git show -s --format=%an $commit_hash` author_email=`git show -s --format=%ae $commit_hash` required_signed_off_by_line="IoT.js-DCO-1.0-Signed-off-by: $author_name $author_email" if [ "$actual_signed_off_by_line" != "$required_signed_off_by_line" ] then echo -e "\e[1;33mSigned-off-by message is incorrect. The following line should be at the end of the $commit_hash commit's message: '$required_signed_off_by_line'. \e[0m" exit 1 fi else echo -e "\e[1;33mWarning! The name and email address of the author of the $commit_hash commit is not checked in tolerant mode! \e[0m" if echo "$actual_signed_off_by_line" | grep -q -v '^IoT.js-DCO-1.0-Signed-off-by:' then echo -e "\e[1;33mSigned-off-by message is incorrect. The following line should be at the end of the $commit_hash commit's message: '$required_signed_off_by_line'. \e[0m" exit 1 fi fi exit 0 iotjs-1.0+715/tools/check_sonarqube.sh000077500000000000000000000020571371177304000176540ustar00rootroot00000000000000#!/bin/bash # Copyright 2018-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 [[ "${TRAVIS_REPO_SLUG}" == "jerryscript-project/iotjs" && ${TRAVIS_BRANCH} == "master" && ${TRAVIS_EVENT_TYPE} == "push" ]] then git fetch --unshallow build-wrapper-linux-x86-64 --out-dir bw-output ./tools/build.py sonar-scanner -Dsonar.projectVersion="${TRAVIS_COMMIT}" else echo "Skip: The pull request from ${TRAVIS_PULL_REQUEST_SLUG} is an \ external one. It's not supported yet in Travis-CI" fi iotjs-1.0+715/tools/check_tidy.py000077500000000000000000000220641371177304000166440ustar00rootroot00000000000000#!/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 import argparse import fileinput import functools import os import subprocess import tempfile import re from distutils import spawn from check_license import CheckLicenser from common_py.system.filesystem import FileSystem as fs from common_py.system.executor import Executor as ex from common_py.system.executor import Terminal def parse_option(): parser = argparse.ArgumentParser() parser.add_argument('--autoedit', action='store_true', default=False, help='Automatically edit the detected clang format and eslint errors.' 'No diffs will be displayed') option = parser.parse_args() return option class StyleChecker(object): column_limit = 80 def __init__(self): self.count_lines = 0 self.count_empty_lines = 0 self.errors = [] self.rules = [] self.err_msgs = [] @property def error_count(self): return len(self.errors) @property def count_valid_lines(self): return self.count_lines - self.count_empty_lines def report_error(self, msg): name = fileinput.filename() line = fileinput.filelineno() self.errors.append("%s:%d: %s" % (name, line, msg)) def set_rules(self): limit = StyleChecker.column_limit self.rules.append(re.compile(r"[\t]")) self.err_msgs.append("TAB character") self.rules.append(re.compile(r"[\r]")) self.err_msgs.append("CR character") self.rules.append(re.compile(r"[ \t]+[\n]$")) self.err_msgs.append("Trailing Whitespace") self.rules.append(re.compile(r"[^\n]\Z")) self.err_msgs.append("Line ends without NEW LINE character") self.rules.append(re.compile("^.{" + str(limit+1) + ",}")) self.err_msgs.append("Line exceeds %d characters" % limit) # append additional rules def check(self, files): for line in fileinput.input(files): for i, rule in enumerate(self.rules): mc = rule.search(line) if mc: self.report_error(self.err_msgs[i]) if fileinput.isfirstline(): if not CheckLicenser.check(fileinput.filename()): self.report_error('incorrect license') self.count_lines += 1 if not line.strip(): self.count_empty_lines += 1 class ClangFormat(object): def __init__(self, extensions, skip_files=None, options=None): self.diffs = [] self._extensions = extensions self._skip_files = skip_files self._options = options self._check_clang_format("clang-format-3.9") def _check_clang_format(self, base): clang_format = spawn.find_executable(base) if not clang_format: clang_format = spawn.find_executable("clang-format") if clang_format: Terminal.pprint( "Using %s instead of %s" % (clang_format, base), Terminal.yellow) else: Terminal.pprint("No %s found, skipping checks!" % base, Terminal.red) self._clang_format = clang_format @property def error_count(self): return len(self.diffs) def is_checked_by_clang(self, file): _, ext = fs.splitext(file) return ext in self._extensions and file not in self._skip_files def check(self, files): if not self._clang_format: return for file in filter(self.is_checked_by_clang, files): args = ['-style=file', file] if self._options and self._options.autoedit: args.append('-i') output = ex.check_run_cmd_output(self._clang_format, args, quiet=True) if output: with tempfile.NamedTemporaryFile() as temp: temp.write(output) temp.flush() # just to be really safe self._diff(file, temp.name) def _diff(self, original, formatted): try: subprocess.check_output(['diff', '-u', original, formatted]) except subprocess.CalledProcessError as error: # if there is a difference between the two files # this error will be generated and we can extract # the diff from that it. Otherwise nothing to do. self.diffs.append(error.output.decode()) class EslintChecker(object): def __init__(self, options=None): self._check_eslint() self._options = options def _check_eslint(self): self._node = spawn.find_executable('node') if not self._node: Terminal.pprint('No node found,', Terminal.red) return self._eslint = spawn.find_executable('node_modules/.bin/eslint') if not self._eslint: self._eslint = spawn.find_executable('eslint') if not self._eslint: Terminal.pprint('No eslint found.', Terminal.red) def check(self): self.error_count = 0 if not self._node or not self._eslint: return args = ['src', '-f', 'codeframe'] if self._options and self._options.autoedit: args.append('--fix') output = ex.run_cmd_output(self._eslint, args, quiet=True) match = re.search('(\d+) error', output) if match: self.error_count = int(match.group(1)) # Delete unnecessary error messages. self.errors = output.split('\n')[:-4] class FileFilter(object): def __init__(self, allowed_exts, allowed_files, skip_files): self._allowed_exts = allowed_exts self._allowed_files = allowed_files self._skip_files = skip_files def __call__(self, dir_path, file): if file in self._allowed_files: return True if file in self._skip_files: return False _, ext = fs.splitext(file) return ext in self._allowed_exts def check_tidy(src_dir, options=None): allowed_exts = ['.c', '.h', '.js', '.py', '.sh', '.cmake'] allowed_files = ['CMakeLists.txt'] clang_format_exts = ['.c', '.h'] skip_dirs = ['deps', 'build', '.git', 'node_modules', 'coverage', 'iotjs_modules', 'IoTjsApp'] skip_files = ['check_license.py', 'check_signed_off.sh', '__init__.py', 'iotjs_js.c', 'iotjs_js.h', 'iotjs_string_ext.inl.h', "iotjs_module_inl.h", 'ble.js', 'ble_hci_socket_acl_stream.js', 'ble_hci_socket_smp.js', 'ble_hci_socket_hci.js', 'ble_hci_socket_gap.js', 'ble_hci_socket_gatt.js', 'ble_hci_socket_mgmt.js', 'ble_hci_socket_bindings.js', 'ble_characteristic.js', 'node_api.h', 'node_api_types.h', 'test_ble_setservices.js', '.eslintrc.js', 'c_source_templates.py', 'cpp_source_templates.py' ] style = StyleChecker() style.set_rules() clang = ClangFormat(clang_format_exts, skip_files, options) eslint = EslintChecker(options) file_filter = FileFilter(allowed_exts, allowed_files, skip_files) files = fs.files_under(src_dir, skip_dirs, file_filter) clang.check(files) style.check(files) eslint.check() if clang.error_count: print("Detected clang-format problems:") print("".join(clang.diffs)) print() if style.error_count: print("Detected style problems:") print("\n".join(style.errors)) print() if eslint.error_count: print("Detected eslint problems:") print("\n".join(eslint.errors)) print() total_errors = style.error_count + clang.error_count + eslint.error_count print("* total lines of code: %d" % style.count_lines) print("* total non-blank lines of code: %d" % style.count_valid_lines) print("* style errors: %d" % style.error_count) print("* clang-format errors: %d" % clang.error_count) print("* eslint errors: %d" % eslint.error_count) msg_color = Terminal.red if total_errors > 0 else Terminal.green Terminal.pprint("* total errors: %d" % (total_errors), msg_color) print() if total_errors: ex.fail("Failed tidy check") if __name__ == '__main__': from common_py import path options = parse_option() check_tidy(path.PROJECT_ROOT, options) iotjs-1.0+715/tools/common_py/000077500000000000000000000000001371177304000161555ustar00rootroot00000000000000iotjs-1.0+715/tools/common_py/__init__.py000066400000000000000000000001001371177304000202550ustar00rootroot00000000000000# Required for Python to search this directory for module files iotjs-1.0+715/tools/common_py/path.py000066400000000000000000000035351371177304000174710ustar00rootroot00000000000000# 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. """ common path for scripts """ from common_py.system.filesystem import FileSystem as fs # Root directory for the project. PROJECT_ROOT = fs.abspath(fs.join(fs.dirname(__file__), fs.pardir, fs.pardir)) # Source code directory. SRC_ROOT = fs.join(PROJECT_ROOT, 'src') # Root Build directory. BUILD_ROOT = fs.join(PROJECT_ROOT, 'build') # Root Build directory. TOOLS_ROOT = fs.join(PROJECT_ROOT, 'tools') # Root directory for dependencies. DEPS_ROOT = fs.join(PROJECT_ROOT, 'deps') # Root directory for test. TEST_ROOT = fs.join(PROJECT_ROOT, 'test') RUN_PASS_DIR = fs.join(TEST_ROOT, 'run_pass') RUN_FAIL_DIR = fs.join(TEST_ROOT, 'run_fail') RESOURCE_DIR = fs.join(TEST_ROOT, 'resources') # Root directory for JerryScript submodule. JERRY_ROOT = fs.join(DEPS_ROOT, 'jerry') # Root directory of JerryScript profiles. JERRY_PROFILE_ROOT = fs.join(JERRY_ROOT, 'jerry-core', 'profiles') # Root directory for libtuv submodule. TUV_ROOT = fs.join(DEPS_ROOT, 'libtuv') # Root directory for http-parser submodule. HTTPPARSER_ROOT = fs.join(DEPS_ROOT, 'http-parser') # Build configuration file path. BUILD_CONFIG_PATH = fs.join(PROJECT_ROOT, 'build.config') # IoT.js build information. BUILD_INFO_PATH = fs.join(TEST_ROOT, 'tools', 'iotjs_build_info.js') iotjs-1.0+715/tools/common_py/system/000077500000000000000000000000001371177304000175015ustar00rootroot00000000000000iotjs-1.0+715/tools/common_py/system/__init__.py000066400000000000000000000001001371177304000216010ustar00rootroot00000000000000# Required for Python to search this directory for module files iotjs-1.0+715/tools/common_py/system/executor.py000066400000000000000000000056631371177304000217230ustar00rootroot00000000000000# 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. from __future__ import print_function import collections import os import subprocess _colors = { "empty": "\033[0m", "red": "\033[1;31m", "green": "\033[1;32m", "yellow": "\033[1;33m", "blue": "\033[1;34m" } if "TERM" not in os.environ: # if there is no "TERM" environment variable # assume that we can't output colors. # So reset the ANSI color escapes. _colors = _colors.fromkeys(_colors, "") _TerminalType = collections.namedtuple('Terminal', _colors.keys()) class _Terminal(_TerminalType): def pprint(self, text, color=_colors["empty"]): print("%s%s%s" % (color, text, self.empty)) Terminal = _Terminal(**_colors) class Executor(object): @staticmethod def cmd_line(cmd, args=[]): return ' '.join([cmd] + args) @staticmethod def print_cmd_line(cmd, args=[]): Terminal.pprint(Executor.cmd_line(cmd, args), Terminal.blue) print() @staticmethod def fail(msg): print() Terminal.pprint(msg, Terminal.red) print() exit(1) @staticmethod def run_cmd(cmd, args=[], quiet=False, cwd=None): if not quiet: Executor.print_cmd_line(cmd, args) try: return subprocess.call([cmd] + args, cwd=cwd) except OSError as e: Executor.fail("[Failed - %s] %s" % (cmd, e.strerror)) @staticmethod def run_cmd_output(cmd, args=[], quiet=False): if not quiet: Executor.print_cmd_line(cmd, args) try: process = subprocess.Popen([cmd] + args, stdout=subprocess.PIPE) output = process.communicate()[0] return output except OSError as e: Executor.fail("[Failed - %s] %s" % (cmd, e.strerror)) @staticmethod def check_run_cmd_output(cmd, args=[], quiet=False): if not quiet: Executor.print_cmd_line(cmd, args) try: return subprocess.check_output([cmd] + args) except OSError as e: Executor.fail("[Failed - %s] %s" % (cmd, e.strerror)) @staticmethod def check_run_cmd(cmd, args=[], quiet=False, cwd=None): retcode = Executor.run_cmd(cmd, args, quiet, cwd) if retcode != 0: Executor.fail("[Failed - %d] %s" % (retcode, Executor.cmd_line(cmd, args))) iotjs-1.0+715/tools/common_py/system/filesystem.py000066400000000000000000000305401371177304000222410ustar00rootroot00000000000000# 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. # Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimecd r. # * 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. # * Neither the name of Google Inc. 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. """ Wrapper object for the file system """ import codecs import errno import filecmp import glob import hashlib import os import shutil import sys import tempfile import time try: import exceptions except ImportError: class exceptions(object): OSError = OSError class FileSystem(object): """FileSystem interface for IoT.js. Unless otherwise noted, all paths are allowed to be either absolute or relative.""" sep = os.sep pardir = os.pardir @staticmethod def abspath(path): # FIXME: This gross hack is needed while we transition from Cygwin # to native Windows, because we have some mixing of file conventions # from different tools: if sys.platform == 'cygwin': path = os.path.normpath(path) path_components = path.split(os.sep) if (path_components and len(path_components[0]) == 2 and path_components[0][1] == ':'): path_components[0] = path_components[0][0] path = os.path.join('/', 'cygdrive', *path_components) return os.path.abspath(path) @staticmethod def realpath(path): return os.path.realpath(path) @staticmethod def path_to_module(module_name): """A wrapper for all calls to __file__ to allow easy unit testing.""" # FIXME: This is the only use of sys in this file. It's possible this # function should move elsewhere. # __file__ is always an absolute path. return sys.modules[module_name].__file__ @staticmethod def expanduser(path): return os.path.expanduser(path) @staticmethod def basename(path): return os.path.basename(path) @staticmethod def chdir(path): return os.chdir(path) @staticmethod def copy(source, destination): shutil.copy(source, destination) @staticmethod def copyfile(source, destination): shutil.copyfile(source, destination) @staticmethod def dirname(path): return os.path.dirname(path) @staticmethod def exists(path): return os.path.exists(path) @staticmethod def dirs_under(path, dir_filter=None): """Return the list of all directories under the given path in topdown order. Args: dir_filter: if not None, the filter will be invoked with the filesystem object and the path of each dirfound. The dir is included in the result if the callback returns True. """ def filter_all(dirpath): return True dir_filter = dir_filter or filter_all dirs = [] for (dirpath, dirnames, filenames) in os.walk(path): if dir_filter(dirpath): dirs.append(dirpath) return dirs @staticmethod def files_under(path, dirs_to_skip=[], file_filter=None): """Return the list of all files under the given path in topdown order. Args: dirs_to_skip: a list of directories to skip over during the traversal (e.g., .svn, resources, etc.) file_filter: if not None, the filter will be invoked with the filesystem object and the dirname and basename of each file found. The file is included in the result if the callback returns True. """ def filter_all(dirpath, basename): return True file_filter = file_filter or filter_all files = [] if FileSystem.isfile(path): if file_filter(dirname(path), FileSystem.basename(path)): files.append(path) return files if FileSystem.basename(path) in dirs_to_skip: return [] for (dirpath, dirnames, filenames) in os.walk(path): for d in dirs_to_skip: if d in dirnames: dirnames.remove(d) for filename in filenames: if file_filter(dirpath, filename): files.append(FileSystem.join(dirpath, filename)) return files @staticmethod def getcwd(): return os.getcwd() @staticmethod def glob(path): return glob.glob(path) @staticmethod def isabs(path): return os.path.isabs(path) @staticmethod def isfile(path): return os.path.isfile(path) @staticmethod def getsize(path): return os.path.getsize(path) @staticmethod def isdir(path): return os.path.isdir(path) @staticmethod def join(*comps): return os.path.join(*comps) @staticmethod def listdir(path): return os.listdir(path) @staticmethod def mkdtemp(**kwargs): """Create and return a uniquely named directory. This is like tempfile.mkdtemp, but if used in a with statement the directory will self-delete at the end of the block (if the directory is empty; non-empty directories raise errors). The directory can be safely deleted inside the block as well, if so desired. Note that the object returned is not a string and does not support all of the string methods. If you need a string, coerce the object to a string and go from there. """ class TemporaryDirectory(object): def __init__(self, **kwargs): self._kwargs = kwargs self._directory_path = tempfile.mkdtemp(**self._kwargs) def __str__(self): return self._directory_path def __enter__(self): return self._directory_path def __exit__(self, type, value, traceback): # Only self-delete if necessary. # FIXME: Should we delete non-empty directories? if os.path.exists(self._directory_path): os.rmdir(self._directory_path) return TemporaryDirectory(**kwargs) @staticmethod def maybe_make_directory(*path): """Create the specified directory if it doesn't already exist.""" try: os.makedirs(FileSystem.join(*path)) except OSError as e: if e.errno != errno.EEXIST: raise @staticmethod def move(source, destination): shutil.move(source, destination) @staticmethod def mtime(path): return os.stat(path).st_mtime @staticmethod def normpath(path): return os.path.normpath(path) @staticmethod def open_binary_tempfile(suffix): """Create, open, and return a binary temp file. Returns a tuple of the file and the name.""" temp_fd, temp_name = tempfile.mkstemp(suffix) f = os.fdopen(temp_fd, 'wb') return f, temp_name @staticmethod def open_binary_file_for_reading(path): return codecs.open(path, 'rb') @staticmethod def read_binary_file(path): """Return the contents of the file at the given path as a byte string.""" with file(path, 'rb') as f: return f.read() @staticmethod def write_binary_file(path, contents): with file(path, 'wb') as f: f.write(contents) @staticmethod def open_text_file_for_reading(path, errors='strict'): # Note: There appears to be an issue with the returned file objects # not being seekable. See http://stackoverflow.com/questions/1510188/ # can-seek-and-tell-work-with-utf-8-encoded-documents-in-python . return codecs.open(path, 'r', 'utf8', errors) @staticmethod def open_text_file_for_writing(path): return codecs.open(path, 'w', 'utf8') @staticmethod def open_stdin(): return codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') @staticmethod def read_text_file(path): """Return the contents of the file at the given path as a Unicode string. The file is read assuming it is a UTF-8 encoded file with no BOM.""" with codecs.open(path, 'r', 'utf8') as f: return f.read() @staticmethod def write_text_file(path, contents): """Write the contents to the file at the given location. The file is written encoded as UTF-8 with no BOM.""" with codecs.open(path, 'w', 'utf-8') as f: f.write(contents.decode('utf-8') if type(contents) == str else contents) @staticmethod def sha1(path): contents = FileSystem.read_binary_file(path) return hashlib.sha1(contents).hexdigest() @staticmethod def relpath(path, start='.'): return os.path.relpath(path, start) class _WindowsError(exceptions.OSError): """Fake exception for Linux and Mac.""" pass @staticmethod def remove(path, osremove=os.remove): """On Windows, if a process was recently killed and it held on to a file, the OS will hold on to the file for a short while. This makes attempts to delete the file fail. To work around that, this method will retry for a few seconds until Windows is done with the file.""" try: exceptions.WindowsError except AttributeError: exceptions.WindowsError = FileSystem._WindowsError retry_timeout_sec = 3.0 sleep_interval = 0.1 while True: try: osremove(path) return True except exceptions.WindowsError as e: time.sleep(sleep_interval) retry_timeout_sec -= sleep_interval if retry_timeout_sec < 0: raise e @staticmethod def rmtree(path): """Delete the directory rooted at path, whether empty or not.""" shutil.rmtree(path, ignore_errors=True) @staticmethod def copytree(source, destination): shutil.copytree(source, destination) @staticmethod def split(path): """Return (dirname, basename + '.' + ext)""" return os.path.split(path) @staticmethod def splitext(path): """Return (dirname + os.sep + basename, '.' + ext)""" return os.path.splitext(path) @staticmethod def compare(path1, path2): return filecmp.cmp(path1, path2) iotjs-1.0+715/tools/common_py/system/sys_platform.py000066400000000000000000000024011371177304000225720ustar00rootroot00000000000000# 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. import os import platform import sys class Platform(object): def __init__(self): if sys.platform == "win32": _os = "windows" if platform.architecture()[0] == "64bit": _arch = "x86_64" else: _arch = "i686" else: _os, _, _, _, _arch = os.uname() self._os = _os self._arch = _arch def os(self): """ Retrieve host OS name. """ return self._os.lower() def arch(self): """ Retrieve host arch name. """ arch = self._arch.lower() if arch in ["armv7l"]: arch = "arm" return arch iotjs-1.0+715/tools/iotjs-create-module.py000077500000000000000000000073401371177304000204120ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2018-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 import os import re IOTJS_BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) TEMPLATE_BASE_DIR = os.path.join(os.path.dirname(__file__), 'module_templates') MODULE_NAME_RE = "^[a-z0-9][a-z0-9\._]*$" def load_templates(template_dir): for root, dirs, files in os.walk(template_dir): for fp in files: yield os.path.relpath(os.path.join(root, fp), template_dir) def replace_contents(input_file, module_name): with open(input_file) as fp: data = fp.read() data = data.replace("$MODULE_NAME$", module_name) data = data.replace("$IOTJS_PATH$", IOTJS_BASE_DIR) return data def create_module(output_dir, module_name, template_dir, template_files): module_path = os.path.join(output_dir, module_name) print("Creating module in {}".format(module_path)) if os.path.exists(module_path): print("Module path ({}) already exists! Exiting".format(module_path)) return False for file_name in template_files: file_path = os.path.join(template_dir, file_name) print("loading template file: {}".format(file_path)) contents = replace_contents(file_path, module_name) output_path = os.path.join(module_path, file_name) # create sub-dir if required base_dir = os.path.dirname(output_path) if not os.path.exists(base_dir): os.mkdir(base_dir) with open(output_path, "w") as fp: fp.write(contents) return True def valid_module_name(value): if not re.match(MODULE_NAME_RE, value): msg = "Invalid module name, should match regexp: %s" % MODULE_NAME_RE raise argparse.ArgumentTypeError(msg) return value if __name__ == "__main__": import argparse import sys desc = "Create an IoT.js external module using a template" parser = argparse.ArgumentParser(description=desc) parser.add_argument("module_name", metavar="", nargs=1, type=valid_module_name, help="name of the new module ((must be in lowercase " + "and should match regexp: %s)" % MODULE_NAME_RE) parser.add_argument("--path", default=".", help="directory where the module will be created " + "(default: %(default)s)") parser.add_argument("--template", default="basic", choices=["basic", "shared"], help="type of the template which should be used " "(default: %(default)s)") args = parser.parse_args() template_dir = os.path.join(TEMPLATE_BASE_DIR, "%s_module_template" % args.template) template_files = load_templates(template_dir) created = create_module(args.path, args.module_name[0], template_dir, template_files) if created: module_path = os.path.join(args.path, args.module_name[0]) print("Module created in: {}".format(os.path.abspath(module_path))) iotjs-1.0+715/tools/iotjs-generate-module.py000077500000000000000000000165741371177304000207520ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2019-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. import os import sys from common_py import path from common_py.system.filesystem import FileSystem as fs from module_generator.source_generator import CSourceGenerator, \ CppSourceGenerator from module_generator.clang_translation_unit_visitor import ClangTUVisitor def generate_c_source(header, api_headers, dirname, args): visit_args = [] if args.define: visit_args += ['-D' + defs for defs in args.define] if args.defines: visit_args += ['-D' + defs for defs in args.defines.read().splitlines()] if args.include: visit_args += ['-I' + inc for inc in args.include] if args.includes: visit_args += ['-I' + inc for inc in args.includes.read().splitlines()] visitor = ClangTUVisitor(args.lang, header, api_headers, args.check_all, visit_args, args.verbose) visitor.visit() if args.check or args.check_all: visitor.check(visitor) if args.lang == 'c': generator = CSourceGenerator() elif args.lang == 'c++': generator = CppSourceGenerator() generated_source = [INCLUDE.format(HEADER=dirname + '_js_binding.h')] if 'macros' not in args.off: generator.macros = visitor.macro_defs def visit_namespace(namespace): generator.create_ns_obj() if 'records' not in args.off: for record in namespace.record_decls: generated_source.append(generator.create_record(record)) if 'functions' not in args.off: for function in namespace.function_decls: generated_source.append(generator.create_ext_function(function)) if 'enums' not in args.off: for decl in namespace.enum_constant_decls: generator.enums += decl.enums if 'variables' not in args.off: for var in namespace.var_decls: generated_source.append(generator.create_getter_setter(var)) generator.create_init_function_body() for ns in namespace.namespaces: generator.namespace.append(ns.name) visit_namespace(ns) generator.regist_ns_obj() generator.namespace.pop() visit_namespace(visitor) generated_source.append(generator.create_init_function(dirname)) return ('\n').join(generated_source) def generate_header(directory): includes = [] api_headers = [] for root, dirs, files in os.walk(directory): for file in files: if file.endswith('.h'): api_headers.append(os.path.abspath(os.path.join(root, file))) includes.append('#include "' + os.path.abspath(os.path.join(root, file)) + '"') return ('\n').join(includes), api_headers def search_for_lib(directory): for root, dirs, files in os.walk(directory): for file in files: if file.startswith('lib') and file.endswith('.a'): return (root, file) def generate_module(args): directory = args.directory if fs.isdir(directory): # handle strings end with '/' if directory[-1] == '/': directory = directory[:-1] dirname = fs.basename(directory) else: sys.exit('Please give an existing directory.') if args.out_dir: output_dir = args.out_dir else: output_dir = fs.join(fs.join(path.TOOLS_ROOT, 'module_generator'), 'output') if not fs.isdir(output_dir): os.mkdir(output_dir) output_dir = fs.join(output_dir, dirname + '_module') if not fs.isdir(output_dir): os.mkdir(output_dir) src_dir = fs.join(output_dir, 'src') if not fs.isdir(src_dir): os.mkdir(src_dir) header_file = fs.join(src_dir, dirname + '_js_binding.h') header_text, api_headers = generate_header(directory) with open(header_file, 'w') as h: h.write(header_text) c_file = generate_c_source(header_file, api_headers, dirname, args) extension = 'cpp' if args.lang == 'c++' else 'c' with open(fs.join(src_dir, dirname + '_js_binding.' + extension), 'w') as c: c.write(c_file) library = search_for_lib(directory) if not library: print ('\033[93mWARNING: Cannot find library file. ' + 'Only the binding layer source has generated.\033[00m') return lib_root, lib_name = library cmake_file = MODULE_CMAKE.format(NAME=dirname, LIBRARY=lib_name[3:-2]) with open(fs.join(output_dir, 'module.cmake'), 'w') as cmake: cmake.write(cmake_file) fs.copyfile(fs.join(lib_root, lib_name), fs.join(output_dir, lib_name)) json_file = MODULES_JSON.format(NAME=dirname, CMAKE='module.cmake') if args.lang == 'c++': cmake_lists = CMAKE_LISTS.format(NAME=dirname) with open(fs.join(src_dir, 'CMakeLists.txt'), 'w') as cmake: cmake.write(cmake_lists) with open(fs.join(output_dir, 'modules.json'), 'w') as json: json.write(json_file) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('directory', help='Root directory of the C/C++ API.') parser.add_argument('lang', choices=['c', 'c++'], help='Specify the language of the API. (default: %(default)s)') parser.add_argument('--out-dir', help='Output directory for the module. ' + '(default: tools/module_generator/output)') parser.add_argument('--off', choices=['functions', 'variables', 'enums', 'macros', 'records'], action='append', default=[], help='Turn off source generating.') parser.add_argument('--define', action='append', default=[], help='Add macro definition.') parser.add_argument('--defines', type=argparse.FileType('r'), help='A file, which contains macro definitions.') parser.add_argument('--include', action='append', default=[], help='Add path to include file.') parser.add_argument('--includes', type=argparse.FileType('r'), help='A file, which contains paths to include files.') parser.add_argument('--check', action='store_true', default=False, help='Check the C API headers. Print the unsupported parts.') parser.add_argument('--check-all', action='store_true', default=False, help='Check the C API headers.') parser.add_argument('-v' , '--verbose', action='store_true', default=False, help='Print errors, detected by clang.') args = parser.parse_args() if args.lang == 'c': from module_generator.c_source_templates import INCLUDE, MODULES_JSON, \ MODULE_CMAKE elif args.lang == 'c++': from module_generator.cpp_source_templates import INCLUDE, \ MODULES_JSON, MODULE_CMAKE, CMAKE_LISTS generate_module(args) iotjs-1.0+715/tools/js2c.py000077500000000000000000000324351371177304000154020ustar00rootroot00000000000000#!/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. # # This file converts src/js/*.js to a C-array in src/iotjs_js.[h|c] file. # And this file also generates magic string list in src/iotjs_string_ext.inl.h # file to reduce JerryScript heap usage. import os import re import subprocess import struct from common_py.system.filesystem import FileSystem as fs from common_py import path def normalize_str(text): if not isinstance(text, str): return text.decode('utf-8') return text def regroup(l, n): return [l[i:i+n] for i in range(0, len(l), n)] def remove_comments(code): pattern = r'(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*$)' regex = re.compile(pattern, re.MULTILINE | re.DOTALL) def _replacer(match): if match.group(2) is not None: return "" else: return match.group(1) return regex.sub(_replacer, code) def remove_whitespaces(code): return re.sub('\n+', '\n', re.sub('\n +', '\n', code)) LICENSE = ''' /* 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. * * This file is generated by tools/js2c.py * Do not modify this. */ ''' HEADER1 = '''#ifndef IOTJS_JS_H #define IOTJS_JS_H ''' FOOTER1 = ''' #endif ''' HEADER2 = '''#include #include #include "iotjs_js.h" ''' EMPTY_LINE = '\n' MAGIC_STRINGS_HEADER = '#define JERRY_MAGIC_STRING_ITEMS \\\n' MODULE_SNAPSHOT_VARIABLES_H = ''' extern const char module_{NAME}[]; extern const uint32_t module_{NAME}_idx; ''' MODULE_SNAPSHOT_VARIABLES_C = ''' #define MODULE_{NAME}_IDX ({IDX}) const char module_{NAME}[] = "{NAME}"; const uint32_t module_{NAME}_idx = MODULE_{NAME}_IDX; ''' NATIVE_SNAPSHOT_STRUCT_H = ''' typedef struct { const char* name; const uint32_t idx; } iotjs_js_module_t; extern const iotjs_js_module_t js_modules[]; ''' MODULE_VARIABLES_H = ''' extern const char {NAME}_n[]; extern const uint8_t {NAME}_s[]; extern const size_t {NAME}_l; ''' MODULE_VARIABLES_C = ''' #define SIZE_{NAME_UPPER} {SIZE} const size_t {NAME}_l = SIZE_{NAME_UPPER}; const char {NAME}_n[] = "{NAME}"; const uint8_t {NAME}_s[] = {{ {CODE} }}; ''' NATIVE_STRUCT_H = ''' typedef struct { const char* name; const void* code; const size_t length; } iotjs_js_module_t; extern const iotjs_js_module_t js_modules[]; ''' NATIVE_STRUCT_C = ''' const iotjs_js_module_t js_modules[] = {{ {MODULES} }}; ''' def hex_format(ch): if isinstance(ch, str): ch = ord(ch) return "0x{:02x}".format(ch) def format_code(code, indent): lines = [] # convert all characters to hex format converted_code = map(hex_format, code) # 10 hex number per line for line in regroup(", ".join(converted_code), 10 * 6): lines.append((' ' * indent) + line.strip()) return "\n".join(lines) def merge_snapshots(snapshot_infos, snapshot_tool): output_path = fs.join(path.SRC_ROOT, 'js','merged.modules') cmd = [snapshot_tool, "merge", "-o", output_path] cmd.extend([item['path'] for item in snapshot_infos]) ret = subprocess.call(cmd) if ret != 0: msg = "Failed to merge %s: - %d" % (snapshot_infos, ret) print("%s%s%s" % ("\033[1;31m", msg, "\033[0m")) exit(1) for item in snapshot_infos: fs.remove(item['path']) with open(output_path, 'rb') as snapshot: code = snapshot.read() fs.remove(output_path) return code def get_snapshot_contents(js_path, snapshot_tool, literals=None): """ Convert the given module with the snapshot generator and return the resulting bytes. """ wrapped_path = js_path + ".wrapped" snapshot_path = js_path + ".snapshot" module_name = os.path.splitext(os.path.basename(js_path))[0] with open(wrapped_path, 'w') as fwrapped, open(js_path, "r") as fmodule: if module_name != "iotjs": fwrapped.write("(function(exports, require, module, native) {\n") fwrapped.write(fmodule.read()) if module_name != "iotjs": fwrapped.write("});\n") cmd = [snapshot_tool, "generate", "-o", snapshot_path] if literals: cmd.extend(["--static", "--load-literals-list-format", literals]) ret = subprocess.call(cmd + [wrapped_path]) fs.remove(wrapped_path) if ret != 0: if literals == None: msg = "Failed to dump %s: - %d" % (js_path, ret) print("%s%s%s" % ("\033[1;31m", msg, "\033[0m")) exit(1) else: print("Unable to create static snapshot from '%s'. Falling back " "to normal snapshot." % js_path) return snapshot_path def get_js_contents(js_path, is_debug_mode=False): """ Read the contents of the given js module. """ with open(js_path, "r") as f: code = f.read() # minimize code when in release mode if not is_debug_mode: code = remove_comments(code) code = remove_whitespaces(code) return code def get_literals_from_snapshots(snapshot_tool, snapshot_list): literals_path = fs.join(path.SRC_ROOT, 'js', 'literals.list') cmd = [snapshot_tool, "litdump", "-o", literals_path] cmd.extend(snapshot_list) ret = subprocess.call(cmd) if ret != 0: msg = "Failed to dump the literals: - %d" % ret print("%s%s%s" % ("\033[1;31m", msg, "\033[0m")) exit(1) return literals_path def read_literals(literals_path): literals_set = set() with open(literals_path, 'rb') as fin: num = '' while True: c = normalize_str(fin.read(1)) if not c: break elif c == ' ': text = normalize_str(fin.read(int(num))) literals_set.add(text) num = '' else: num += c return literals_set def write_literals_to_file(literals_set, literals_path): sorted_lit = sorted(literals_set, key=lambda x: (len(x), x)) with open(literals_path, 'wb') as flit: for lit in sorted_lit: entry = "%d %s\n" % (len(lit), lit) flit.write(entry.encode('utf-8')) def js2c(options, js_modules): is_debug_mode = (options.buildtype == "debug") snapshot_tool = options.snapshot_tool no_snapshot = (snapshot_tool == None) verbose = options.verbose magic_string_set = set() str_const_regex = re.compile('^#define IOTJS_MAGIC_STRING_\w+\s+"(\w+)"$') with open(fs.join(path.SRC_ROOT, 'iotjs_magic_strings.in'), 'r') as fin_h: for line in fin_h: result = str_const_regex.search(line) if result: magic_string_set.add(result.group(1)) # generate the code for the modules with open(fs.join(path.SRC_ROOT, 'iotjs_js.h'), 'w') as fout_h, \ open(fs.join(path.SRC_ROOT, 'iotjs_js.c'), 'w') as fout_c: fout_h.write(LICENSE) fout_h.write(HEADER1) fout_c.write(LICENSE) fout_c.write(HEADER2) snapshot_infos = [] js_module_names = [] if no_snapshot: for idx, module in enumerate(sorted(js_modules)): [name, js_path] = module.split('=', 1) js_module_names.append(name) if verbose: print('Processing module: %s' % name) code = get_js_contents(js_path, is_debug_mode) code_string = format_code(code, 1) fout_h.write(MODULE_VARIABLES_H.format(NAME=name)) fout_c.write(MODULE_VARIABLES_C.format(NAME=name, NAME_UPPER=name.upper(), SIZE=len(code), CODE=code_string)) modules_struct = [ ' {{ {0}_n, {0}_s, SIZE_{1} }},'.format(name, name.upper()) for name in sorted(js_module_names) ] modules_struct.append(' { NULL, NULL, 0 }') native_struct_h = NATIVE_STRUCT_H else: # Generate snapshot files from JS files for idx, module in enumerate(sorted(js_modules)): [name, js_path] = module.split('=', 1) js_module_names.append(name) if verbose: print('Processing (1st phase) module: %s' % name) code_path = get_snapshot_contents(js_path, snapshot_tool) info = {'name': name, 'path': code_path, 'idx': idx} snapshot_infos.append(info) # Get the literal list from the snapshots if verbose: print('Creating literal list file for static snapshot ' 'creation') literals_path = get_literals_from_snapshots(snapshot_tool, [info['path'] for info in snapshot_infos]) magic_string_set |= read_literals(literals_path) # Update the literals list file write_literals_to_file(magic_string_set, literals_path) # Generate static-snapshots if possible for idx, module in enumerate(sorted(js_modules)): [name, js_path] = module.split('=', 1) if verbose: print('Processing (2nd phase) module: %s' % name) get_snapshot_contents(js_path, snapshot_tool, literals_path) fout_h.write(MODULE_SNAPSHOT_VARIABLES_H.format(NAME=name)) fout_c.write(MODULE_SNAPSHOT_VARIABLES_C.format(NAME=name, IDX=idx)) fs.remove(literals_path) # Merge the snapshot files code = merge_snapshots(snapshot_infos, snapshot_tool) code_string = format_code(code, 1) name = 'iotjs_js_modules' fout_h.write(MODULE_VARIABLES_H.format(NAME=name)) fout_c.write(MODULE_VARIABLES_C.format(NAME=name, NAME_UPPER=name.upper(), SIZE=len(code), CODE=code_string)) modules_struct = [ ' {{ module_{0}, MODULE_{0}_IDX }},'.format(info['name']) for info in snapshot_infos ] modules_struct.append(' { NULL, 0 }') native_struct_h = NATIVE_SNAPSHOT_STRUCT_H fout_h.write(native_struct_h) fout_h.write(FOOTER1) fout_c.write(NATIVE_STRUCT_C.format(MODULES="\n".join(modules_struct))) fout_c.write(EMPTY_LINE) # Write out the external magic strings magic_str_path = fs.join(path.SRC_ROOT, 'iotjs_string_ext.inl.h') with open(magic_str_path, 'w') as fout_magic_str: fout_magic_str.write(LICENSE) fout_magic_str.write(MAGIC_STRINGS_HEADER) sorted_strings = sorted(magic_string_set, key=lambda x: (len(x), x)) for idx, magic_string in enumerate(sorted_strings): magic_text = repr(magic_string)[1:-1] magic_text = magic_text.replace('"', '\\"') fout_magic_str.write(' MAGICSTR_EX_DEF(MAGIC_STR_%d, "%s") \\\n' % (idx, magic_text)) # an empty line is required to avoid compile warning fout_magic_str.write(EMPTY_LINE) if __name__ == "__main__": import argparse 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('--modules', required=True, help='List of JS files to process. Format: ' '=,=,...') parser.add_argument('--snapshot-tool', default=None, help='Executable to use for generating snapshots and merging them ' '(ex.: the JerryScript snapshot tool). ' 'If not specified the JS files will be directly processed.') parser.add_argument('-v', '--verbose', default=False, help='Enable verbose output.') options = parser.parse_args() if not options.snapshot_tool: print('Converting JS modules to C arrays (no snapshot)') else: print('Using "%s" as snapshot tool' % options.snapshot_tool) modules = options.modules.split(',') js2c(options, modules) iotjs-1.0+715/tools/measure_coverage.sh000077500000000000000000000126211371177304000200320ustar00rootroot00000000000000#!/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. print_dep() { echo "The following dependencies are required:" echo " sudo apt install lcov gcc-multilib" echo "" } print_nvm_dep() { echo "The nvm (node version manager) is required to install node and npm." echo "Use the following command to install nvm:" echo " curl \ https://raw.githubusercontent.com/creationix/nvm/v0.33.1/install.sh | bash" echo "" } print_npm_dep() { echo "The following node dependencies are required: " echo " npm install babel-cli nyc babel-plugin-istanbul merge-source-map" echo "" } print_usage() { echo "Measure JavaScript and C coverage and create a html report" echo "out of the results" echo "" echo "Usage: measure_coverage.sh [ARGUMENTS]" echo "" echo "Optional Arguments:" echo " --node-modules-dir Specifies the node_module directory, where" echo " the nodejs dependencies are installed." echo "" echo " --target-board Specifies the target board, where the" echo " coverage measurement will happen." echo " Possible values: rpi2" echo "" echo "The created html reports can be found in the 'coverage' directory," echo "which will be created in the IoT.js project source dir. The C and" echo "JavaScript coverage reports are in the 'c' and 'js' subdirectories" echo "respectively. The reports can be viewed by opening the 'index.html'" echo "file in a web browser of your choice." echo "" echo "Running the script will require some additional dependencies." echo "" print_dep print_nvm_dep print_npm_dep exit 0 } fail_with_msg() { echo "$1" exit 1 } # Parse the given arguments. while [[ $# -gt 0 ]] do key="$1" case $key in --node-modules-dir) node_modules_dir="$2" shift ;; --target-board) target_board="$2" shift ;; *) print_usage ;; esac shift done tools_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" iotjs_root=$(readlink -f "$tools_dir/..") test -e ~/.nvm if [ "$?" -ne "0" ]; then print_nvm_dep exit 1 fi # Make available the nvm command. . ~/.nvm/nvm.sh . ~/.profile # Istanbul and babel require node version > 4.0. nvm ls 4.0.0 >> /dev/null 2>&1 if [ "$?" -ne "0" ]; then nvm install 4.0 else nvm use 4.0 fi dpkg -l lcov >> /dev/null 2>&1 && \ dpkg -l gcc-multilib >> /dev/null 2>&1 if [ "$?" -ne "0" ]; then print_dep exit 1 fi modules_dir=$(readlink -f "$(npm bin)/..") if [ -v node_modules_dir ]; then path=$(readlink -f $node_modules_dir) if [ ! -d "$path" ] || [ $(basename "$path") != "node_modules" ]; then fail_with_msg "'$node_modules_dir' is not a node_modules directory" fi test -e $path/.bin/nyc && \ test -e $path/.bin/babel if [ "$?" -ne "0" ]; then print_npm_dep exit 1 fi modules_dir="$path" else test -e $modules_dir/.bin/nyc && \ test -e $modules_dir/.bin/babel if [ "$?" -ne "0" ]; then print_npm_dep exit 1 fi fi cd $iotjs_root # Transpile JS files to provide line counters $modules_dir/.bin/babel --plugins="babel-plugin-istanbul" \ src/js/ --out-dir src/cover_js/ # Backup original module files, and replace them with the transpiled files mv src/js src/orig_js mv src/cover_js src/js # Build iot.js # We need to use the system allocator to have enough memory, for now this can # only be done with a 32-bit build common_build_opts="--jerry-cmake-param=-DJERRY_SYSTEM_ALLOCATOR=ON --compile-flag=-coverage --no-snapshot" if ! [ -v target_board ]; then tools/build.py $common_build_opts --target-arch=x86 \ --profile=test/profiles/host-linux.profile if [ $? -ne 0 ]; then fail_with_msg "x86 build failed." fi build_path=${PWD}/build/i686-linux/debug elif [ $target_board = "rpi2" ]; then tools/build.py $common_build_opts --target-arch=arm --target-board=rpi2 \ --profile=test/profiles/rpi2-linux.profile if [ $? -ne 0 ]; then fail_with_msg "RPi2 build failed." fi build_path=${PWD}/build/arm-linux/debug else fail_with_msg "Not supported target-board: $target_board" fi # Run the appropriate testrunner. python tools/testrunner.py ${build_path}/bin/iotjs --quiet --coverage # Revert to original module files rm -rf src/js mv src/orig_js src/js # Generate js coverage report mkdir -p .coverage_output $modules_dir/.bin/nyc report --reporter=lcov \ --report-dir=coverage --temp-directory=.coverage_output rm -rf .coverage_output rm -rf coverage/js mv coverage/lcov-report coverage/js # Generate c coverage report lcov -t "c_coverage" -o ".c-coverage.info" -c -d $build_path lcov --remove ".c-coverage.info" 'iotjs/deps/*' -o ".c-coverage.info" genhtml -o coverage/c .c-coverage.info rm .c-coverage.info cd - iotjs-1.0+715/tools/measure_js_heap.py000077500000000000000000000044531371177304000176720ustar00rootroot00000000000000#!/usr/bin/env python # 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. from __future__ import print_function import argparse import os import re import subprocess import sys from common_py import path from common_py.system.filesystem import FileSystem as fs def get_arguments(): parser = argparse.ArgumentParser() parser.add_argument('--base', required=True, help='Path to the base IoT.js binary') parser.add_argument('--new', required=True, help='Path to the new IoT.js binary') script_args = parser.parse_args() return script_args def run_iotjs(cmd): pattern = re.compile(r'Peak allocated = (\d+) bytes') try: output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: return "" match = pattern.search(str(output)) if match: return match.group(1) else: return "" if __name__ == "__main__": script_args = get_arguments() print("**JS heap peak (bytes)**\n") print("| {0:^40} | {1:^10} | {2:^10} |".format("Test file", "base", "new")) print("| {0} | {1} | {2} |".format("-"*40, "-"*10, "-"*10)) for test_file in os.listdir(path.RUN_PASS_DIR): if test_file.endswith(".js"): line = "| " + test_file + " | " cmd = [script_args.base, '--memstat', os.path.join(path.RUN_PASS_DIR, test_file) ] base_out = run_iotjs(cmd) cmd = [script_args.new, '--memstat', os.path.join(path.RUN_PASS_DIR, test_file) ] new_out = run_iotjs(cmd) if base_out or new_out: print("| {0:40} | {1:^10} | {2:^10} |" .format(test_file, base_out, new_out)) iotjs-1.0+715/tools/mem_stats.sh000077500000000000000000000066721371177304000165230ustar00rootroot00000000000000#!/bin/bash # 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. # Usage if [ "$#" -lt 3 ] then echo "$0: Benchmark memory usage of IoT.js" echo "" echo "Usage: $0 [-d] IOTJS IOTJS_MEMSTATS BENCHMARK..." echo "" echo "Positional arguments:" echo " IOTJS path to IoT.js engine built without memory" echo " statistics support" echo " IOTJS_MEMSTATS path to IoT.js engine built with memory statistics" echo " support" echo " BENCHMARK... paths to JavaScript programs to be used as the" echo " benchmark suite" echo "" echo "Optional arguments:" echo " -d generate semicolon-delimited output (default:" echo " formatted human-readable output)" echo "" echo "The tool benchmarks the memory usage of IoT.js with the help of two" echo "different builds and a suite of JavaScript programs. Each benchmark" echo "script is executed by both builds: the \"memstats\" build reports" echo "statistics retrieved from JerryScript, while the \"normal\" build" echo "reports RSS results." exit 1 fi # Choosing table or semicolon-separated output mode if [ "$1" == "-d" ] then TABLE="no" PRINT_TEST_NAME_AWK_SCRIPT='{printf "%s;", $1}' PRINT_TOTAL_AWK_SCRIPT='{printf "%d;%d\n", $1, $2 * 1024}' shift else PRINT_TEST_NAME_AWK_SCRIPT='{printf "%30s", $1}' PRINT_TOTAL_AWK_SCRIPT='{printf "%25d%25d\n", $1, $2 * 1024}' TABLE="yes" fi function fail_msg { echo "$1" exit 1 } # Engine # Check if the specified build supports memory statistics options function is_mem_stats_build { [ -x "$1" ] || fail_msg "Engine '$1' is not executable" tmpfile=`mktemp` "$1" --memstat $tmpfile 2>&1 | \ grep -- "Ignoring memory statistics option" 2>&1 > /dev/null code=$? rm $tmpfile return $code } IOTJS=$(readlink -f "$1") shift is_mem_stats_build "$IOTJS" || fail_msg \ "First engine specified should be built without memory statistics support" IOTJS_MEM_STATS=$(readlink -f "$1") shift is_mem_stats_build "$IOTJS_MEM_STATS" && fail_msg \ "Second engine specified should be built with memory statistics support" # Benchmarks list BENCHMARKS="" while [ $# -ne 0 ] do BENCHMARKS="$BENCHMARKS $1" shift done # Running if [ "$TABLE" == "yes" ] then awk 'BEGIN {printf "%30s%25s%25s\n", "Test name", "Peak Heap (jerry)", \ "Maximum RSS"}' echo fi STARTDIR=$(pwd) for bench in $BENCHMARKS do bench_name=$(basename -s '.js' $bench) bench_canon=$(readlink -f $bench) cd `dirname $bench_canon` echo "$bench_name" | awk "$PRINT_TEST_NAME_AWK_SCRIPT" MEM_STATS=$("$IOTJS_MEM_STATS" --memstat $bench_canon | \ grep -e "Peak allocated =" | grep -o "[0-9]*") RSS=$($STARTDIR/deps/jerry/tools/rss-measure.sh "$IOTJS" $bench_canon | \ tail -n 1 | grep -o "[0-9]*") echo $MEM_STATS $RSS | xargs | awk "$PRINT_TOTAL_AWK_SCRIPT" cd $STARTDIR done iotjs-1.0+715/tools/module_generator/000077500000000000000000000000001371177304000175105ustar00rootroot00000000000000iotjs-1.0+715/tools/module_generator/__init__.py000066400000000000000000000001001371177304000216100ustar00rootroot00000000000000# Required for Python to search this directory for module files iotjs-1.0+715/tools/module_generator/c_source_templates.py000066400000000000000000000603271371177304000237520ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2019-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. # Templates for create/set a C variable # one length String to char JS_TO_CHAR = ''' // create a character value from a jerry_value_t {TYPE} {NAME}; jerry_string_to_char_buffer ({JVAL}, (jerry_char_t*)(&{NAME}), 1); ''' # Set a char variable JS_SET_CHAR = ''' // set the value of {NAME} jerry_string_to_char_buffer ({JVAL}, (jerry_char_t*)(&{NAME}), 1); ''' # Number to int/float/enum JS_TO_NUMBER = ''' // create an integer / floating point number from a jerry_value_t {TYPE} {NAME} = ({TYPE})jerry_get_number_value ({JVAL}); ''' # Set an int/float/enum variable JS_SET_NUMBER = ''' // set the value of {NAME} {NAME} = jerry_get_number_value ({JVAL}); ''' # Boolean to _Bool JS_TO_BOOL = ''' // create a _Bool value from a jerry_value_t {TYPE} {NAME} = jerry_value_to_boolean ({JVAL}); ''' # Set a _Bool variable JS_SET_BOOL = ''' // set the value of {NAME} {NAME} = jerry_value_to_boolean ({JVAL}); ''' # String to char[] JS_TO_STRING = ''' // create an array of characters from a jerry_value_t {TYPE} * {NAME} = NULL; if (jerry_value_is_string ({JVAL})) {{ jerry_size_t {NAME}_size = jerry_get_string_size ({JVAL}); {NAME} = malloc ({NAME}_size + 1); if({NAME} == NULL) {{ return jerry_create_error (JERRY_ERROR_COMMON, (const jerry_char_t*)"Fail to allocate memory."); }} jerry_string_to_char_buffer ({JVAL}, (jerry_char_t*){NAME}, {NAME}_size); {NAME}[{NAME}_size] = '\\0'; }} ''' JS_FREE_STRING = ''' // TODO: if you won't use {NAME} pointer, uncomment the lines below //if (jerry_value_is_string ({JVAL})) // free ({NAME}); ''' # Set a char* variable JS_SET_CHAR_PTR = ''' // set the value of {NAME} jerry_size_t size = jerry_get_string_size ({JVAL}); if ({NAME} == NULL) {{ {NAME} = ({TYPE}*) malloc (size + 1); }} jerry_string_to_char_buffer ({JVAL}, (jerry_char_t*){NAME}, size); {NAME}[size] = '\\0'; ''' # Set a char[] variable JS_SET_CHAR_ARR = ''' // set the value of {NAME} jerry_string_to_char_buffer ({JVAL}, (jerry_char_t*){NAME}, {SIZE}); {NAME}[{SIZE}] = '\\0'; ''' # TypedArray to number pointer JS_TO_TYPEDARRAY = ''' // create a pointer to number from a jerry_value_t {TYPE} * {NAME} = NULL; jerry_length_t {NAME}_byteLength = 0; jerry_length_t {NAME}_byteOffset = 0; jerry_value_t {NAME}_buffer; if (jerry_value_is_typedarray ({JVAL})) {{ {NAME}_buffer = jerry_get_typedarray_buffer ({JVAL}, &{NAME}_byteOffset, &{NAME}_byteLength); {NAME} = ({TYPE}*) malloc ({NAME}_byteLength); if({NAME} == NULL) {{ jerry_release_value ({NAME}_buffer); return jerry_create_error (JERRY_ERROR_COMMON, (const jerry_char_t*)"Fail to allocate memory."); }} jerry_arraybuffer_read ({NAME}_buffer, {NAME}_byteOffset, (uint8_t*){NAME}, {NAME}_byteLength); }} ''' JS_FREE_BUFFER = ''' jerry_release_value ({NAME}_buffer); // TODO: if you won't use {NAME} pointer, uncomment the line below //free ({NAME}); ''' JS_FREE_WRITE_BUFFER = ''' // write the values back into an arraybuffer from a pointer if (jerry_value_is_typedarray ({JVAL})) {{ jerry_arraybuffer_write ({NAME}_buffer, {NAME}_byteOffset, (uint8_t*){NAME}, {NAME}_byteLength); jerry_release_value ({NAME}_buffer); // TODO: if you won't use {NAME} pointer, uncomment the line below //free ({NAME}); }} ''' # Set a number pointer JS_SET_TYPEDARRAY = ''' // set the value of {NAME} jerry_length_t byteLength = 0; jerry_length_t byteOffset = 0; jerry_value_t buffer; if (jerry_value_is_typedarray ({JVAL})) {{ buffer = jerry_get_typedarray_buffer ({JVAL}, &byteOffset, &byteLength); if ({NAME} == NULL) {{ {NAME} = ({TYPE}*) malloc (byteLength); }} jerry_arraybuffer_read (buffer, byteOffset, (uint8_t*){NAME}, byteLength); jerry_release_value (buffer); }} else {{ {NAME} = NULL; }} ''' # Object to struct/union JS_TO_RECORD = ''' // create a record from a jerry_value_t void* {NAME}_void_ptr; const jerry_object_native_info_t* {NAME}_type_ptr; bool {NAME}_has_ptr = jerry_get_object_native_pointer({JVAL}, &{NAME}_void_ptr, &{NAME}_type_ptr); if (!{NAME}_has_ptr || ({NAME}_type_ptr != &{RECORD}_type_info && {NAME}_type_ptr != &{RECORD}_type_info_static)) {{ char const *msg = "Failed to get native {TYPE} pointer"; return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t *)msg); }} {TYPE} {NAME} = *(({TYPE}*){NAME}_void_ptr); ''' # Set a struct/union JS_SET_RECORD = ''' // set the value of {NAME} void* {RECORD}_void_ptr; const jerry_object_native_info_t* {RECORD}_type_ptr; bool {RECORD}_has_ptr = jerry_get_object_native_pointer({JVAL}, &{RECORD}_void_ptr, &{RECORD}_type_ptr); if (!{RECORD}_has_ptr || ({RECORD}_type_ptr != &{RECORD}_type_info && {RECORD}_type_ptr != &{RECORD}_type_info_static)) {{ char const *msg = "Failed to get native {RECORD} pointer"; return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t *)msg); }} {NAME} = *(({TYPE}*){RECORD}_void_ptr); ''' # Set a const struct/union JS_SET_CONST_RECORD = ''' // set the value of {NAME} void* {RECORD}_void_ptr; const jerry_object_native_info_t* {RECORD}_type_ptr; bool {RECORD}_has_ptr = jerry_get_object_native_pointer({JVAL}, &{RECORD}_void_ptr, &{RECORD}_type_ptr); if (!{RECORD}_has_ptr || ({RECORD}_type_ptr != &{RECORD}_type_info && {RECORD}_type_ptr != &{RECORD}_type_info_static)) {{ char const *msg = "Failed to get native {RECORD} pointer"; return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t *)msg); }} memcpy(&{NAME}, {RECORD}_void_ptr, sizeof({TYPE})); ''' # Object to struct/union pointer JS_TO_RECORD_PTR = ''' // create a record pointer from a jerry_value_t void* {NAME}_void_ptr; const jerry_object_native_info_t* {NAME}_type_ptr; bool {NAME}_has_ptr = jerry_get_object_native_pointer({JVAL}, &{NAME}_void_ptr, &{NAME}_type_ptr); if (!{NAME}_has_ptr || ({NAME}_type_ptr != &{RECORD}_type_info && {NAME}_type_ptr != &{RECORD}_type_info_static)) {{ char const *msg = "Failed to get native {TYPE} pointer"; return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t *)msg); }} {TYPE} * {NAME} = ({TYPE}*){NAME}_void_ptr; ''' # Function to C function JS_TO_FUNCTION = ''' // create a function pointer from a jerry_value_t {TYPE} (*{NAME})({PARAMS}) = NULL; if (jerry_value_is_function({JVAL})) {{ {FUNC}_{NAME}_js = {JVAL}; {NAME} = {FUNC}_{NAME}; }} ''' JS_CB_FUNCTION = ''' // native callback function jerry_value_t {FUNC}_{NAME}_js; {RET_TYPE} {FUNC}_{NAME} ({PARAMS}) {{ jerry_value_t args[{LENGTH}]; {CREATE_VAL} jerry_value_t this_val = jerry_create_undefined(); jerry_value_t result = jerry_call_function({FUNC}_{NAME}_js, this_val, args, {LENGTH}); {RESULT} jerry_release_value(result); jerry_release_value(this_val); for (int i = 0; i < {LENGTH}; i++) {{ jerry_release_value(args[i]); }} return {RET}; }} ''' # Unsupported C type JS_TO_UNSUPPORTED = ''' // TODO: Define the right value of the variable. {TYPE} {NAME}; ''' # Templates for create a jerry_value_t variable # Create Undefined/Bool/Number/Object JS_CREATE_VAL = ''' jerry_value_t {NAME} = jerry_create_{TYPE} ({FROM}); ''' # Create one length String JS_CREATE_CHAR = ''' jerry_value_t {NAME} = jerry_create_string_sz ((jerry_char_t*)(&{FROM}), 1); ''' # Create String JS_CREATE_STRING = ''' jerry_value_t {NAME}; if ({FROM} != NULL) {{ {NAME} = jerry_create_string ((jerry_char_t*){FROM}); }} else {{ {NAME} = jerry_create_null (); }} ''' # Create TypedArray or Null JS_CREATE_TYPEDARRAY = ''' // create a typedarray or null from a pointer jerry_value_t {NAME}; if ({FROM} != NULL) {{ jerry_length_t {NAME}_byteLength = sizeof({TYPE}); jerry_value_t {NAME}_buffer = jerry_create_arraybuffer ({NAME}_byteLength); jerry_arraybuffer_write ({NAME}_buffer, 0, (uint8_t*){FROM}, {NAME}_byteLength); {NAME} = jerry_create_typedarray_for_arraybuffer_sz (JERRY_TYPEDARRAY_{ARRAY_TYPE}, {NAME}_buffer, 0, 1); jerry_release_value ({NAME}_buffer); }} else {{ {NAME} = jerry_create_null (); }} ''' TYPEDARRAYS = { 'signed char': 'INT8', 'unsigned char': 'UINT8', 'short': 'INT16', 'unsigned short': 'UINT16', 'int': 'INT32', 'unsigned int': 'UINT32', 'long': 'INT32', 'unsigned long': 'UINT32', 'long long': 'INT32', 'unsigned long long': 'UINT32', 'float': 'FLOAT32', 'double': 'FLOAT64', 'long double': 'FLOAT64' } # Create Object JS_CREATE_OBJECT = ''' // create object from record {TYPE}* {RECORD}_native_ptr = ({TYPE}*)calloc(1, sizeof({TYPE})); *{RECORD}_native_ptr = {FROM}; jerry_value_t {NAME} = {RECORD}_js_creator({RECORD}_native_ptr); jerry_set_object_native_pointer({NAME}, {RECORD}_native_ptr, &{RECORD}_type_info); ''' # Create Object JS_CREATE_CONST_OBJECT = ''' // create object from record {TYPE}* {RECORD}_native_ptr = ({TYPE}*)calloc(1, sizeof({TYPE})); memcpy({RECORD}_native_ptr, &{FROM}, sizeof({TYPE})); jerry_value_t {NAME} = {RECORD}_js_creator({RECORD}_native_ptr); jerry_set_object_native_pointer({NAME}, {RECORD}_native_ptr, &{RECORD}_type_info); ''' # Unsupported C type JS_CREATE_UNSUPPORTED = ''' // TODO: Create a valid jerry_value_t from '{FROM}'. jerry_value_t {NAME} = jerry_create_undefined (); ''' # Templates for record types # Record destructor JS_RECORD_DESTRUCTOR = ''' void {RECORD}_js_destructor(void* ptr) {{ free(({TYPE}*)ptr); }} static const jerry_object_native_info_t {RECORD}_type_info = {{ .free_cb = {RECORD}_js_destructor }}; static const jerry_object_native_info_t {RECORD}_type_info_static = {{ .free_cb = NULL }}; ''' # Member getter/setter template JS_RECORD_MEMBER = ''' // external function for getter/setter of record member jerry_value_t {RECORD}_{NAME} (const jerry_value_t function_obj, const jerry_value_t this_val, const jerry_value_t args_p[], const jerry_length_t args_cnt) {{ void* void_ptr; const jerry_object_native_info_t* type_ptr; bool has_ptr = jerry_get_object_native_pointer(this_val, &void_ptr, &type_ptr); if (!has_ptr || (type_ptr != &{RECORD}_type_info && type_ptr != &{RECORD}_type_info_static)) {{ char const *msg = "Failed to get native {RECORD} pointer"; return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t *)msg); }} {TYPE}* native_ptr = ({TYPE}*)(void_ptr); {BODY} return ret_val; }} ''' JS_RECORD_GETTER = ''' // external function for record getter jerry_value_t {RECORD}{NAME}_getter (const jerry_value_t function_obj, const jerry_value_t this_val, const jerry_value_t args_p[], const jerry_length_t args_cnt) {{ jerry_value_t {NAME}_name = jerry_create_string((const jerry_char_t *) "_{NAME}"); jerry_value_t {NAME}_value = jerry_get_property(this_val, {NAME}_name); jerry_release_value({NAME}_name); return {NAME}_value; }} ''' # Record constructor JS_RECORD_CONSTRUCTOR = ''' // external function for record constructor jerry_value_t {RECORD}_js_constructor (const jerry_value_t function_obj, const jerry_value_t this_val, const jerry_value_t args_p[], const jerry_length_t args_cnt) {{ (void) {RECORD}_type_info_static; {TYPE}* native_ptr = ({TYPE}*)calloc(1, sizeof({TYPE})); if (args_cnt == 0) {{ jerry_value_t ret_val = {RECORD}_js_creator(native_ptr); jerry_set_object_native_pointer(ret_val, native_ptr, &{RECORD}_type_info); return ret_val; }} if (args_cnt != 1 || !jerry_value_is_object (args_p[0])) {{ char const *msg = "Wrong argument for {RECORD}(), expected an object."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); }} {BODY} jerry_value_t ret_val = {RECORD}_js_creator(native_ptr); jerry_set_object_native_pointer(ret_val, native_ptr, &{RECORD}_type_info); return ret_val; }} ''' JS_RECORD_RETURN = ''' jerry_value_t ret_val = {RECORD}_js_creator(native_ptr); jerry_set_object_native_pointer(ret_val, native_ptr, &{RECORD}_type_info); return ret_val; ''' JS_GET_PROP_STRUCT = ''' {TYPE} {NAME}{INIT}; jerry_value_t {NAME}_name = jerry_create_string((const jerry_char_t *) "{NAME}"); jerry_value_t {NAME}_value = jerry_get_property(args_p[0], {NAME}_name); jerry_release_value({NAME}_name); if (!jerry_value_is_undefined({NAME}_value)) {{ {GET_VAL} }} jerry_release_value({NAME}_value); ''' JS_GET_PROP_UNION = ''' jerry_value_t {NAME}_name = jerry_create_string((const jerry_char_t *) "{NAME}"); jerry_value_t {NAME}_value = jerry_get_property(args_p[0], {NAME}_name); jerry_release_value({NAME}_name); if (!jerry_value_is_undefined({NAME}_value)) {{ {TYPE} {NAME}{INIT}; {GET_VAL} jerry_release_value({NAME}_value); {RET} }} jerry_release_value({NAME}_value); ''' JS_INIT_MEMBERS = ''' *native_ptr = ({TYPE}){{{MEMBERS}}}; ''' JS_INIT_MEMBERS_CONST = ''' {TYPE} native = {{{MEMBERS}}}; memcpy(native_ptr, &native, sizeof({TYPE})); ''' JS_RECORD_CREATOR = ''' jerry_value_t {RECORD}_js_creator ({TYPE}* native_ptr) {{ jerry_value_t js_obj = jerry_create_object(); {REGIST} return js_obj; }} ''' JS_REGIST_MEMBER = ''' // set record's member as a property to the object jerry_property_descriptor_t {RECORD}_{NAME}_prop_desc; jerry_init_property_descriptor_fields (&{RECORD}_{NAME}_prop_desc); {RECORD}_{NAME}_prop_desc.is_get_defined = true; {RECORD}_{NAME}_prop_desc.is_set_defined = true; {RECORD}_{NAME}_prop_desc.getter = jerry_create_external_function ({RECORD}_{NAME}_getter); {RECORD}_{NAME}_prop_desc.setter = jerry_create_external_function ({RECORD}_{NAME}_setter); jerry_value_t {RECORD}_{NAME}_prop_name = jerry_create_string ((const jerry_char_t *)"{NAME}"); jerry_value_t {RECORD}_{NAME}_return_value = jerry_define_own_property (js_obj, {RECORD}_{NAME}_prop_name, &{RECORD}_{NAME}_prop_desc); jerry_release_value ({RECORD}_{NAME}_return_value); jerry_release_value ({RECORD}_{NAME}_prop_name); jerry_free_property_descriptor_fields (&{RECORD}_{NAME}_prop_desc); ''' JS_REGIST_RECORD = ''' // set record as a property to the object jerry_value_t {NAME}_js = {RECORD}_js_creator (&{REF}); jerry_set_object_native_pointer({NAME}_js, &{REF}, &{RECORD}_type_info_static); jerry_property_descriptor_t {NAME}_js_prop_desc; jerry_init_property_descriptor_fields (&{NAME}_js_prop_desc); {NAME}_js_prop_desc.is_value_defined = true; {NAME}_js_prop_desc.value = {NAME}_js; jerry_value_t {NAME}_js_prop_name = jerry_create_string ((const jerry_char_t *)"_{NAME}"); jerry_value_t {NAME}_js_return_value = jerry_define_own_property ({OBJECT}, {NAME}_js_prop_name, &{NAME}_js_prop_desc); jerry_release_value ({NAME}_js_return_value); jerry_release_value ({NAME}_js_prop_name); jerry_free_property_descriptor_fields (&{NAME}_js_prop_desc); ''' JS_REGIST_CONST_MEMBER = ''' // set a constant member as a property to the object jerry_property_descriptor_t {NAME}_prop_desc; jerry_init_property_descriptor_fields (&{NAME}_prop_desc); {NAME}_prop_desc.is_value_defined = true; {NAME}_prop_desc.value = {NAME}_js; jerry_value_t {NAME}_prop_name = jerry_create_string ((const jerry_char_t *)"{NAME}"); jerry_value_t {NAME}_return_value = jerry_define_own_property (js_obj, {NAME}_prop_name, &{NAME}_prop_desc); jerry_release_value ({NAME}_return_value); jerry_release_value ({NAME}_prop_name); jerry_free_property_descriptor_fields (&{NAME}_prop_desc); ''' JS_REGIST_CONST_RECORD = ''' // set a constant record as a property to the object jerry_property_descriptor_t {NAME}_prop_desc; jerry_init_property_descriptor_fields (&{NAME}_prop_desc); {NAME}_prop_desc.is_get_defined = true; {NAME}_prop_desc.getter = jerry_create_external_function ({NAME}_getter); jerry_value_t {NAME}_prop_name = jerry_create_string ((const jerry_char_t *)"{VALUE}"); jerry_value_t {NAME}_return_value = jerry_define_own_property ({OBJECT}, {NAME}_prop_name, &{NAME}_prop_desc); jerry_release_value ({NAME}_return_value); jerry_release_value ({NAME}_prop_name); jerry_free_property_descriptor_fields (&{NAME}_prop_desc); ''' JS_REGIST_ARR_MEMBER = ''' // set a numeric array member as a property to the object jerry_value_t {NAME}_buffer = jerry_create_arraybuffer_external (sizeof({TYPE}) * {SIZE}, (uint8_t*)native_ptr->{NAME}, NULL); jerry_value_t {NAME}_typedarray = jerry_create_typedarray_for_arraybuffer_sz (JERRY_TYPEDARRAY_{ARRAY_TYPE}, {NAME}_buffer, 0, {SIZE}); jerry_property_descriptor_t {NAME}_prop_desc; jerry_init_property_descriptor_fields (&{NAME}_prop_desc); {NAME}_prop_desc.is_value_defined = true; {NAME}_prop_desc.value = {NAME}_typedarray; jerry_value_t {NAME}_prop_name = jerry_create_string ((const jerry_char_t *)"{NAME}"); jerry_value_t {NAME}_return_value = jerry_define_own_property (js_obj, {NAME}_prop_name, &{NAME}_prop_desc); jerry_release_value ({NAME}_return_value); jerry_release_value ({NAME}_prop_name); jerry_release_value ({NAME}_buffer); jerry_free_property_descriptor_fields (&{NAME}_prop_desc); ''' # Template for a jerry_external_handler_t type function JS_EXT_FUNC = ''' // external function for API functions or for getters / setters jerry_value_t {NAME} (const jerry_value_t function_obj, const jerry_value_t this_val, const jerry_value_t args_p[], const jerry_length_t args_cnt) {{ {BODY} return ret_val; }} ''' # Template for check the count of the external function's arguments JS_CHECK_ARG_COUNT = ''' // check the count of the external function's arguments if (args_cnt != {COUNT}) {{ char const *msg = "Wrong argument count for {FUNC}(), expected {COUNT}."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); }} ''' # Templates for check the type of a jerry_value_t variable JS_CHECK_TYPE = ''' // check the type of a jerry_value_t variable if (!jerry_value_is_{TYPE} ({JVAL})) {{ char const *msg = "Wrong argument type for {FUNC}(), expected {TYPE}."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); }} ''' JS_CHECK_POINTER = ''' // check the type of a jerry_value_t variable if (!jerry_value_is_{TYPE} ({JVAL}) && !jerry_value_is_null ({JVAL})) {{ char const *msg = "Wrong argument type for {FUNC}(), expected {TYPE} or null."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); }} ''' # Templates for the module initialization function INIT_FUNC = ''' // init function for the module jerry_value_t Init_{NAME}() {{ {BODY} return object; }} ''' INIT_REGIST_FUNC = ''' // set an external function as a property to the module object jerry_value_t {NAME}_name = jerry_create_string ((const jerry_char_t*)"{FUNC}"); jerry_value_t {NAME}_func = jerry_create_external_function ({NAME}_handler); jerry_value_t {NAME}_ret = jerry_set_property ({OBJECT}, {NAME}_name, {NAME}_func); jerry_release_value ({NAME}_name); jerry_release_value ({NAME}_func); jerry_release_value ({NAME}_ret); ''' INIT_REGIST_RECORD = ''' // set a constructor as a property to the module object jerry_value_t {NAME}_name = jerry_create_string ((const jerry_char_t*)"{RECORD}"); jerry_value_t {NAME}_func = jerry_create_external_function ({NAME}_js_constructor); jerry_value_t {NAME}_ret = jerry_set_property ({OBJECT}, {NAME}_name, {NAME}_func); jerry_release_value ({NAME}_name); jerry_release_value ({NAME}_func); jerry_release_value ({NAME}_ret); ''' INIT_REGIST_ENUM = ''' // set an enum constant as a property to the module object jerry_property_descriptor_t {NAME}_prop_desc; jerry_init_property_descriptor_fields (&{NAME}_prop_desc); {NAME}_prop_desc.is_value_defined = true; {NAME}_prop_desc.value = jerry_create_number ({REF}); jerry_value_t {NAME}_name = jerry_create_string ((const jerry_char_t *)"{ENUM}"); jerry_value_t {NAME}_ret = jerry_define_own_property ({OBJECT}, {NAME}_name, &{NAME}_prop_desc); jerry_release_value ({NAME}_ret); jerry_release_value ({NAME}_name); jerry_free_property_descriptor_fields (&{NAME}_prop_desc); ''' INIT_REGIST_VALUE = ''' // set a global variable as a property to the module object jerry_property_descriptor_t {NAME}_prop_desc; jerry_init_property_descriptor_fields (&{NAME}_prop_desc); {NAME}_prop_desc.is_get_defined = true; {NAME}_prop_desc.is_set_defined = true; {NAME}_prop_desc.getter = jerry_create_external_function ({NAME}_getter); {NAME}_prop_desc.setter = jerry_create_external_function ({NAME}_setter); jerry_value_t {NAME}_prop_name = jerry_create_string ((const jerry_char_t *)"{VALUE}"); jerry_value_t {NAME}_return_value = jerry_define_own_property ({OBJECT}, {NAME}_prop_name, &{NAME}_prop_desc); jerry_release_value ({NAME}_return_value); jerry_release_value ({NAME}_prop_name); jerry_free_property_descriptor_fields (&{NAME}_prop_desc); ''' INIT_REGIST_CONST = ''' // set a global constant or a macro as a property to the module object jerry_property_descriptor_t {NAME}_prop_desc; jerry_init_property_descriptor_fields (&{NAME}_prop_desc); {NAME}_prop_desc.is_value_defined = true; {NAME}_prop_desc.value = {NAME}_js; jerry_value_t {NAME}_prop_name = jerry_create_string ((const jerry_char_t *)"{VALUE}"); jerry_value_t {NAME}_return_value = jerry_define_own_property ({OBJECT}, {NAME}_prop_name, &{NAME}_prop_desc); jerry_release_value ({NAME}_return_value); jerry_release_value ({NAME}_prop_name); jerry_free_property_descriptor_fields (&{NAME}_prop_desc); ''' INIT_REGIST_NUM_ARR = ''' // set a global numeric array as a property to the module object jerry_value_t {NAME}_buffer = jerry_create_arraybuffer_external (sizeof({TYPE}) * {SIZE}, (uint8_t*){REF}, NULL); jerry_value_t {NAME}_typedarray = jerry_create_typedarray_for_arraybuffer_sz (JERRY_TYPEDARRAY_{ARRAY_TYPE}, {NAME}_buffer, 0, {SIZE}); jerry_property_descriptor_t {NAME}_prop_desc; jerry_init_property_descriptor_fields (&{NAME}_prop_desc); {NAME}_prop_desc.is_value_defined = true; {NAME}_prop_desc.value = {NAME}_typedarray; jerry_value_t {NAME}_prop_name = jerry_create_string ((const jerry_char_t *)"{ARR}"); jerry_value_t {NAME}_return_value = jerry_define_own_property ({OBJECT}, {NAME}_prop_name, &{NAME}_prop_desc); jerry_release_value ({NAME}_return_value); jerry_release_value ({NAME}_prop_name); jerry_release_value ({NAME}_buffer); jerry_free_property_descriptor_fields (&{NAME}_prop_desc); ''' INIT_CREATE_OBJECT = ''' jerry_value_t {NAME}object = jerry_create_object(); ''' INIT_REGIST_OBJECT = ''' // set a namespace as a property to another namespace object jerry_property_descriptor_t {NAME}_prop_desc; jerry_init_property_descriptor_fields (&{NAME}_prop_desc); {NAME}_prop_desc.is_value_defined = true; {NAME}_prop_desc.value = {NAME}object; jerry_value_t {NAME}_prop_name = jerry_create_string ((const jerry_char_t *)"{REF}"); jerry_value_t {NAME}_return_value = jerry_define_own_property ({OBJECT}, {NAME}_prop_name, &{NAME}_prop_desc); jerry_release_value ({NAME}_return_value); jerry_release_value ({NAME}_prop_name); jerry_free_property_descriptor_fields (&{NAME}_prop_desc); ''' # Template for include the right headers INCLUDE = ''' #include #include #include "jerryscript.h" #include "{HEADER}" ''' # Templates for modules.json and module.cmake MODULES_JSON = ''' {{ "modules": {{ "{NAME}_module": {{ "native_files": ["src/{NAME}_js_binding.c"], "init": "Init_{NAME}", "cmakefile": "{CMAKE}" }} }} }} ''' MODULE_CMAKE = ''' set(MODULE_NAME "{NAME}_module") link_directories(${{MODULE_DIR}}) list(APPEND MODULE_LIBS {LIBRARY}) ''' iotjs-1.0+715/tools/module_generator/clang_translation_unit_visitor.py000077500000000000000000000745551371177304000264250ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2019-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 clang.cindex import Index, conf, CursorKind, TypeKind, AccessSpecifier # This class is a wrapper for the TypeKind and Type classes. class ClangASTNodeType: char_type_kinds = [ TypeKind.CHAR_U, TypeKind.CHAR16, TypeKind.CHAR32, TypeKind.CHAR_S, TypeKind.WCHAR ] number_type_kinds = [ TypeKind.UCHAR, TypeKind.SCHAR, TypeKind.USHORT, TypeKind.UINT, TypeKind.ULONG, TypeKind.ULONGLONG, TypeKind.UINT128, TypeKind.SHORT, TypeKind.INT, TypeKind.LONG, TypeKind.LONGLONG, TypeKind.INT128, TypeKind.FLOAT, TypeKind.DOUBLE, TypeKind.LONGDOUBLE ] def __init__(self, clang_type): # We are only interested in the underlying canonical types. self._canonical_type = clang_type.get_canonical() self._type_name = clang_type.spelling.replace('const ', '') @property def name(self): return self._type_name @property def canonical_name(self): return self._canonical_type.spelling def is_bool(self): return self._canonical_type.kind == TypeKind.BOOL def is_char(self): return self._canonical_type.kind in ClangASTNodeType.char_type_kinds def is_number(self): return self._canonical_type.kind in ClangASTNodeType.number_type_kinds def is_enum(self): return self._canonical_type.kind == TypeKind.ENUM def is_void(self): return self._canonical_type.kind == TypeKind.VOID def is_pointer(self): return (self._canonical_type.kind == TypeKind.POINTER or self._canonical_type.kind == TypeKind.CONSTANTARRAY or self._canonical_type.kind == TypeKind.INCOMPLETEARRAY) def is_array(self): return (self._canonical_type.kind == TypeKind.CONSTANTARRAY or self._canonical_type.kind == TypeKind.INCOMPLETEARRAY) def is_record(self): return self._canonical_type.kind == TypeKind.RECORD def is_struct(self): return (self._canonical_type.get_declaration().kind == CursorKind.STRUCT_DECL) def is_union(self): return (self._canonical_type.get_declaration().kind == CursorKind.UNION_DECL) def is_function(self): return (self._canonical_type.kind == TypeKind.FUNCTIONPROTO or self._canonical_type.kind == TypeKind.FUNCTIONNOPROTO) def is_const(self): return self._canonical_type.is_const_qualified() def get_array_type(self): return ClangASTNodeType(self._canonical_type.get_array_element_type()) def get_array_size(self): assert self.is_array() return self._canonical_type.element_count def get_pointee_type(self): if self.is_array(): array_type = self._canonical_type.get_array_element_type() return ClangASTNodeType(array_type) if self.is_pointer(): return ClangASTNodeType(self._canonical_type.get_pointee()) def get_declaration(self): return ClangASTNode(self._canonical_type.get_declaration()) def get_as_record_decl(self): assert (self.is_record()) return ClangRecordDecl(self._canonical_type.get_declaration()) def has_const_member(self): ret = False decl = self._canonical_type.get_declaration() for child in decl.get_children(): if child.kind == CursorKind.FIELD_DECL: if child.type.get_canonical().kind == TypeKind.RECORD: ret = ClangASTNodeType(child.type).has_const_member() if child.type.is_const_qualified(): ret = True return ret # This class is a wrapper for the Cursor type. class ClangASTNode: def __init__(self, cursor): self._cursor = cursor self._type = ClangASTNodeType(cursor.type) self._kind = cursor.kind @property def name(self): return self._cursor.spelling @property def type(self): return self._type @property def kind(self): return self._kind def get_as_record_decl(self): assert (self.type.is_record()) return ClangRecordDecl(self._cursor) def get_as_function(self): return ClangFunctionDecl(self._cursor) # This class represents enum declarations in libclang. class ClangEnumDecl: def __init__(self, cursor): self._enum_constant_decls = [] for child in cursor.get_children(): if child.kind == CursorKind.ENUM_CONSTANT_DECL: self._enum_constant_decls.append(child.spelling) @property def enums(self): return self._enum_constant_decls # This class represents function declarations in libclang. class ClangFunctionDecl(ClangASTNode): def __init__(self, cursor): ClangASTNode.__init__(self, cursor) if cursor.type.get_canonical().kind == TypeKind.POINTER: return_type = cursor.type.get_canonical().get_pointee().get_result() else: return_type = cursor.type.get_canonical().get_result() self._return_type = ClangASTNodeType(return_type) self._parm_decls = [] if cursor.type.kind == TypeKind.TYPEDEF: children = cursor.type.get_declaration().get_children() else: children = cursor.get_children() for arg in children: if arg.kind == CursorKind.PARM_DECL: arg = ClangASTNode(arg) self._parm_decls.append(arg) @property def return_type(self): return self._return_type @property def params(self): return self._parm_decls # This class represents macro definitions in libclang. # TokenKinds: # 'PUNCTUATION' = 0 # 'KEYWORD' = 1 # 'IDENTIFIER' = 2 # 'LITERAL' = 3 # 'COMMENT' = 4 class ClangMacroDef(ClangASTNode): def __init__(self, cursor): ClangASTNode.__init__(self, cursor) self.tokens = [] self.token_kinds = [] for token in cursor.get_tokens(): self.tokens.append(token.spelling) self.token_kinds.append(token.kind.value) @property def content(self): return (' ').join(self.tokens[1:]) def is_char(self): if (self.token_kinds == [2, 3] and # "#define CH 'a'" like macros "'" in self.tokens[1]): # char literal return True return False def is_string(self): if (self.token_kinds == [2, 3] and # '#define STR "abc"' like macros '"' in self.tokens[1]): # string literal return True return False # macro contains only number literals and punctuations def is_number(self): if (self.content and not [x for x in self.token_kinds[1:] if x in [1, 2, 4]] and "'" not in self.content and '"' not in self.content): return True return False def is_valid(self): return self.is_char() or self.is_string() or self.is_number() def is_function(self): return conf.lib.clang_Cursor_isMacroFunctionLike(self._cursor) class ClangRecordConstructor: def __init__(self, cursor_list, is_constructor = True, func_list = []): self._suffix = '' if cursor_list: self._cursor = cursor_list[0] self._parm_decls = {} param_lists = [] for i, cursor in enumerate(cursor_list): arguments = list(cursor.get_arguments()) param_lists.append(([ClangASTNode(a) for a in arguments], i)) # handle default arguments for arg in reversed(arguments): if '=' in [t.spelling for t in arg.get_tokens()]: arguments = arguments[:-1] param_lists.append(([ClangASTNode(a) for a in arguments], i)) # Codes: # String - 0 # Number - 1 # Boolean - 2 # TypedArray - 3 # Function - 4 # Object - name of the object # Other - 5 coded_param_lists = [] for param_list, _ in param_lists: coded_params = [] for param in param_list: param_t = param.type if (param_t.is_char() or (param_t.is_pointer() and param_t.get_pointee_type().is_char())): coded_params.append(0) elif param_t.is_number() or param_t.is_enum(): coded_params.append(1) elif param_t.is_bool(): coded_params.append(2) elif param_t.is_function(): coded_params.append(4) elif param_t.is_record(): record = param_t.get_as_record_decl().ns_name coded_params.append(record) elif param_t.is_pointer(): pointee_t = param_t.get_pointee_type() if pointee_t.is_char(): coded_params.append(0) elif pointee_t.is_number(): coded_params.append(3) elif pointee_t.is_function(): coded_params.append(4) elif pointee_t.is_record(): record = pointee_t.get_as_record_decl().ns_name coded_params.append(record) else: coded_params.append(5) else: coded_params.append(5) coded_param_lists.append(coded_params) # Remove lists from `param_lists`, # which have the same JS types of parameters j = 0 same_types_params = [] for i, coded_params in enumerate(coded_param_lists): if coded_params in coded_param_lists[:i] + coded_param_lists[i+1:]: same_types_params.append(param_lists.pop(j)) j -= 1 j += 1 for param_list, _ in param_lists: if len(param_list) in self._parm_decls: self._parm_decls[len(param_list)].append(param_list) else: self._parm_decls[len(param_list)] = [param_list] for j, (params, i) in enumerate(same_types_params): if is_constructor: f = ClangRecordConstructor([cursor_list[i]]) else: f = ClangRecordMethod(self._cursor.spelling, [cursor_list[i]]) f._suffix = '_$' + str(j) func_list.append(f) func_name = cursor_list[i].spelling print ('\033[93mWARN: The following overload of ' + func_name + ' has been renamed to ' + func_name + f._suffix + ' :\033[00m') print ' '.join(t.spelling for t in cursor_list[i].get_tokens()) @property def params(self): return self._parm_decls @property def suffix(self): return self._suffix class ClangRecordMethod(ClangRecordConstructor): def __init__(self, name, cursor_list, func_list = []): ClangRecordConstructor.__init__(self, cursor_list, False, func_list) self._method_name = name return_type = cursor_list[0].type.get_canonical().get_result() self._return_type = ClangASTNodeType(return_type) @property def name(self): return self._method_name @property def return_type(self): return self._return_type # This class represents struct/union/class declarations in libclang. class ClangRecordDecl(ClangASTNode): def __init__(self, cursor): ClangASTNode.__init__(self, cursor) self._field_decls = [] self._has_constructor = True self._has_default_constructor = True self._has_copy_constructor = True self._constructors = [] if cursor.spelling: self._name = cursor.spelling else: self._name = self.type.name.split('::')[-1] constructors = [] methods = {} for child in cursor.get_children(): if child.access_specifier == AccessSpecifier.PUBLIC: if child.kind == CursorKind.CONSTRUCTOR: constructors.append(child) if child.kind == CursorKind.FIELD_DECL: self._field_decls.append(ClangASTNode(child)) if child.kind == CursorKind.CXX_METHOD: if child.spelling in methods: methods[child.spelling].append(child) else: methods[child.spelling] = [child] if not constructors and self.type.has_const_member(): self._has_constructor = False self._has_default_constructor = False self._has_copy_constructor = False elif constructors: constructor = ClangRecordConstructor(constructors, True, self._constructors) if constructor.params: self._constructors.append(constructor) self._methods = [] for name, cursor_list in methods.items(): method = ClangRecordMethod(name, cursor_list, self._methods) if method.params: self._methods.append(method) @property def name(self): return self._name @property def ns_name(self): return self.type.name.replace('::', '_') @property def constructors(self): return self._constructors def has_constructor(self): return self._has_constructor def has_default_constructor(self): return self._has_default_constructor def has_copy_constructor(self): return self._has_copy_constructor @property def field_decls(self): return self._field_decls @property def methods(self): return self._methods class ClangNamespace: def __init__(self, name, cursor_list): self.name = name self.enum_constant_decls = [] self.function_decls = [] self.var_decls = [] self.record_decls = [] self.namespaces = [] cpp_funcs = {} namespaces = {} for cursor in cursor_list: children = cursor.get_children() for child in children: if child.kind == CursorKind.ENUM_DECL: self.enum_constant_decls.append(ClangEnumDecl(child)) elif child.kind == CursorKind.FUNCTION_DECL: if child.spelling in cpp_funcs: cpp_funcs[child.spelling].append(child) else: cpp_funcs[child.spelling] = [child] elif child.kind == CursorKind.VAR_DECL: self.var_decls.append(ClangASTNode(child)) elif (child.kind == CursorKind.CLASS_DECL or child.kind == CursorKind.STRUCT_DECL or child.kind == CursorKind.UNION_DECL): self.record_decls.append(ClangRecordDecl(child)) elif child.kind == CursorKind.NAMESPACE: if child.spelling in namespaces: namespaces[child.spelling].append(child) else: namespaces[child.spelling] = [child] for name, cursor_list in cpp_funcs.items(): func = ClangRecordMethod(name, cursor_list, self.function_decls) if func.params: self.function_decls.append() for name, cursor_list in namespaces.items(): self.namespaces.append(ClangNamespace(name, cursor_list)) # This class responsible for initializing and visiting # the AST provided by libclang. class ClangTUVisitor: def __init__(self, lang, header, api_headers, check_all, args, verbose): index = Index.create() self.is_cpp = True if lang == 'c++' else False self.clang_args = ['-x', lang] self.translation_unit = index.parse(header, args + self.clang_args, options=1) if verbose: for diag in self.translation_unit.diagnostics: if diag.severity == 2: msg = '\033[93mWARNING : ' elif diag.severity == 3: msg = '\033[91mERROR : ' elif diag.severity == 4: msg = '\033[91mFATAL : ' msg += '{} at {} line {}, column {}\033[00m' print (msg.format(diag.spelling, diag.location.file, diag.location.line, diag.location.column)) self.api_headers = api_headers self.check_all = check_all self.enum_constant_decls = [] self.function_decls = [] self.var_decls = [] self.macro_defs = [] self.record_decls = [] self.namespaces = [] def visit(self): children = self.translation_unit.cursor.get_children() cpp_funcs = {} namespaces = {} for cursor in children: if (cursor.location.file != None and cursor.location.file.name in self.api_headers): if cursor.kind == CursorKind.ENUM_DECL: self.enum_constant_decls.append(ClangEnumDecl(cursor)) elif cursor.kind == CursorKind.FUNCTION_DECL: if self.is_cpp: if cursor.spelling in cpp_funcs: cpp_funcs[cursor.spelling].append(cursor) else: cpp_funcs[cursor.spelling] = [cursor] else: self.function_decls.append(ClangFunctionDecl(cursor)) elif cursor.kind == CursorKind.VAR_DECL: self.var_decls.append(ClangASTNode(cursor)) elif cursor.kind == CursorKind.MACRO_DEFINITION: self.macro_defs.append(ClangMacroDef(cursor)) elif (cursor.kind == CursorKind.CLASS_DECL or cursor.kind == CursorKind.STRUCT_DECL or cursor.kind == CursorKind.UNION_DECL): self.record_decls.append(ClangRecordDecl(cursor)) elif cursor.kind == CursorKind.NAMESPACE: if cursor.spelling in namespaces: namespaces[cursor.spelling].append(cursor) else: namespaces[cursor.spelling] = [cursor] for name, cursor_list in cpp_funcs.items(): func = ClangRecordMethod(name, cursor_list, self.function_decls) if func.params: self.function_decls.append(func) for name, cursor_list in namespaces.items(): self.namespaces.append(ClangNamespace(name, cursor_list)) # Resolve other macros in macro definition for first in self.macro_defs: for second in self.macro_defs: for i, token in enumerate(second.tokens): if i and first.name == token: second.tokens = (second.tokens[:i] + first.tokens[1:] + second.tokens[i+1:]) second.token_kinds = (second.token_kinds[:i] + first.token_kinds[1:] + second.token_kinds[i+1:]) def ok(self, msg): return '\033[92m{}\033[00m'.format(msg) def warn(self, msg): return '\033[91m{}\033[00m'.format(msg) def check(self, namespace): if namespace == self: self.check_macros() self.check_variables(namespace) for record in namespace.record_decls: record_is_ok, record_msg = self.check_record(record) if not record_is_ok: print(record_msg) print(str(record._cursor.location) + '\n') elif self.check_all: print(self.ok('Supported record: ' + record.name) + '\n') for func in namespace.function_decls: if self.is_cpp: param_msg = [] param_is_ok = True for _, param_lists in func.params.items(): for p_list in param_lists: is_ok, msg = self.check_parameters(p_list) if not is_ok: param_is_ok = False p_types = ', '.join([p.type.name for p in p_list]) warn = self.warn( 'Unsupported overload: {}({})'.format(func.name, p_types)) param_msg.append(warn) param_msg.append(msg) param_msg = '\n'.join(param_msg) else: param_is_ok, param_msg = self.check_parameters(func.params) ret_is_ok, ret_msg = self.check_return_type(func.return_type) if not (param_is_ok and ret_is_ok): print(self.warn('Unsupported function: ' + func.name)) if param_msg: print(param_msg) if ret_msg: print(ret_msg) print(str(func._cursor.location) + '\n') elif self.check_all: print(self.ok('Supported function: ' + func.name) + '\n') for ns in namespace.namespaces: self.check(ns) def check_macros(self): for macro in self.macro_defs: if not macro.is_valid(): print(self.warn('Unsupported macro: ' + macro.name)) print(str(macro._cursor.location) + '\n') elif self.check_all: print(self.ok('Supported macro: ' + macro.name) + '\n') def check_variables(self, namespace): for var in namespace.var_decls: is_supported = False msg = '' if (var.type.is_char() or var.type.is_number() or var.type.is_enum() or var.type.is_bool()): is_supported = True elif var.type.is_pointer(): pointee = var.type.get_pointee_type() if pointee.is_char() or pointee.is_number(): is_supported = True elif var.type.is_record(): var_record = var.type.get_as_record_decl() is_supported, msg = self.check_record(var_record) if not is_supported: print(self.warn( 'Unsupported variable: {} {}'.format(var.type.name, var.name))) if msg: print(msg) print(str(var._cursor.location) + '\n') elif self.check_all: print(self.ok( 'Supported variable: {} {}'.format(var.type.name, var.name)) + '\n') def check_record(self, record): record_msg = '' # Check fields field_msg = [] field_is_ok = True for field in record.field_decls: is_supported = False msg = '' if (field.type.is_char() or field.type.is_number() or field.type.is_enum() or field.type.is_bool()): is_supported = True elif field.type.is_pointer(): pointee = field.type.get_pointee_type() if pointee.is_char() or pointee.is_number(): is_supported = True elif field.type.is_record(): field_record = field.type.get_as_record_decl() is_supported, msg = self.check_record(field_record) if not is_supported: field_is_ok = False warn = self.warn( 'Unsupported field: {} {}'.format(field.type.name, field.name)) field_msg.append(warn) if msg: field_msg.append(msg) # Check constructor constructor_msg = [] constructor_is_ok = True for _, param_lists in record.constructor.params.items(): for param_list in param_lists: param_is_ok, param_msg = self.check_parameters(param_list) if not param_is_ok: constructor_is_ok = False p_types = ', '.join([p.type.name for p in param_list]) warn = self.warn( 'Unsupported constructor: {}({})'.format(record.name, p_types)) constructor_msg.append(warn) constructor_msg.append(param_msg) # Check methods method_msg = [] method_is_ok = True for method in record.methods: for _, param_lists in method.params.items(): for param_list in param_lists: param_is_ok, param_msg = self.check_parameters(param_list) if not param_is_ok: method_is_ok = False p_types = ', '.join([p.type.name for p in param_list]) warn = self.warn( 'Unsupported overload: {}({})'.format(method.name, p_types)) method_msg.append(warn) method_msg.append(param_msg) ret_is_ok, ret_msg = self.check_return_type(method.return_type) if not ret_is_ok: method_is_ok = False method_msg.append(ret_msg) if not method_is_ok: warn = self.warn('Unsupported method: ' + method.name) method_msg.insert(0, warn) record_msg = ('\n'.join(field_msg) + '\n'.join(constructor_msg) + '\n'.join(method_msg)) record_is_ok = field_is_ok and constructor_is_ok and method_is_ok if not record_is_ok: record_msg = (self.warn('Unsupported record: ' + record.name) + '\n' + record_msg) return record_is_ok, record_msg def check_parameters(self, param_list): param_msg = [] param_is_ok = True for param in param_list: is_supported = False msg = '' if (param.type.is_char() or param.type.is_number() or param.type.is_enum() or param.type.is_bool()): is_supported = True elif param.type.is_pointer(): pointee = param.type.get_pointee_type() if pointee.is_char() or pointee.is_number(): is_supported = True elif pointee.is_record(): record = pointee.get_as_record_decl() is_supported, msg = self.check_record(record) elif pointee.is_function(): is_supported = self.check_func_ptr(param.get_as_function()) elif param.type.is_record(): record = param.get_as_record_decl() is_supported, msg = self.check_record(record) elif param.type.is_function(): is_supported = self.check_func_ptr(param.get_as_function()) if not is_supported: param_is_ok = False warn = self.warn( 'Unsupported parameter: {} {}'.format(param.type.name, param.name)) param_msg.append(warn) if msg: param_msg.append(msg) return param_is_ok, '\n'.join(param_msg) def check_return_type(self, return_type): msg = '' return_type_is_ok = False if (return_type.is_void() or return_type.is_char() or return_type.is_number() or return_type.is_enum() or return_type.is_bool()): return_type_is_ok = True elif return_type.is_pointer(): pointee = return_type.get_pointee_type() if pointee.is_char() or pointee.is_number(): return_type_is_ok = True elif return_type.is_record(): record = return_type.get_as_record_decl() return_type_is_ok, msg = self.check_record(record) if not return_type_is_ok: warn = self.warn('Unsupported return type: ' + return_type.name) if msg: msg = warn + '\n' + msg else: msg = warn return return_type_is_ok, msg def check_func_ptr(self, function): param_is_ok = True for param in function.params: is_supported = False if (param.type.is_char() or param.type.is_number() or param.type.is_enum() or param.type.is_bool()): is_supported = True elif param.type.is_pointer(): pointee = param.type.get_pointee_type() if pointee.is_char() or pointee.is_number(): is_supported = True elif param.type.is_record(): record = param.get_as_record_decl() is_supported, _ = self.check_record(record) if not is_supported: param_is_ok = False break ret_type = function.return_type ret_is_ok = False if (ret_type.is_void() or ret_type.is_char() or ret_type.is_number() or ret_type.is_enum() or ret_type.is_bool()): ret_is_ok = True elif ret_type.is_pointer(): pointee = ret_type.get_pointee_type() if pointee.is_char() or pointee.is_number(): ret_is_ok = True elif pointee.is_record(): record = pointee.get_as_record_decl() ret_is_ok, _ = self.check_record(record) elif ret_type.is_record(): record = ret_type.get_as_record_decl() ret_is_ok, _ = self.check_record(record) return (param_is_ok and ret_is_ok) iotjs-1.0+715/tools/module_generator/cpp_source_templates.py000066400000000000000000000241241371177304000243050ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2019-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. # Templates for create/set a C++ variable # String to char[] JS_TO_STRING = ''' // create an array of characters from a jerry_value_t {TYPE} * {NAME} = NULL; if (jerry_value_is_string ({JVAL})) {{ jerry_size_t {NAME}_size = jerry_get_string_size ({JVAL}); {NAME} = new {TYPE}[{NAME}_size + 1]; jerry_string_to_char_buffer ({JVAL}, (jerry_char_t*){NAME}, {NAME}_size); {NAME}[{NAME}_size] = '\\0'; }} ''' JS_FREE_STRING = ''' // TODO: if you won't use {NAME} pointer, uncomment the line below //if (jerry_value_is_string ({JVAL})) // delete[] {NAME}; ''' # Set a char* variable JS_SET_CHAR_PTR = ''' // set the value of {NAME} jerry_size_t size = jerry_get_string_size ({JVAL}); if ({NAME} == NULL) {{ {NAME} = new {TYPE}[size + 1]; }} jerry_string_to_char_buffer ({JVAL}, (jerry_char_t*){NAME}, size); {NAME}[size] = '\\0'; ''' # TypedArray to number pointer JS_TO_TYPEDARRAY = ''' // create a pointer to number from a jerry_value_t {TYPE} * {NAME} = NULL; jerry_length_t {NAME}_byteLength = 0; jerry_length_t {NAME}_byteOffset = 0; jerry_value_t {NAME}_buffer; if (jerry_value_is_typedarray ({JVAL})) {{ {NAME}_buffer = jerry_get_typedarray_buffer ({JVAL}, &{NAME}_byteOffset, &{NAME}_byteLength); {NAME} = new {TYPE}[{NAME}_byteLength / sizeof({TYPE})]; jerry_arraybuffer_read ({NAME}_buffer, {NAME}_byteOffset, (uint8_t*){NAME}, {NAME}_byteLength); }} ''' JS_FREE_WRITE_BUFFER = ''' // write the values back into an arraybuffer from a pointer if (jerry_value_is_typedarray ({JVAL})) {{ jerry_arraybuffer_write ({NAME}_buffer, {NAME}_byteOffset, (uint8_t*){NAME}, {NAME}_byteLength); jerry_release_value ({NAME}_buffer); // TODO: if you won't use {NAME} pointer, uncomment the line below //delete[] {NAME}; }} ''' # Set a number pointer JS_SET_TYPEDARRAY = ''' // set the value of {NAME} jerry_length_t byteLength = 0; jerry_length_t byteOffset = 0; jerry_value_t buffer; if (jerry_value_is_typedarray ({JVAL})) {{ buffer = jerry_get_typedarray_buffer ({JVAL}, &byteOffset, &byteLength); if ({NAME} == NULL) {{ {NAME} = new {TYPE}[byteLength / sizeof({TYPE})]; }} jerry_arraybuffer_read (buffer, byteOffset, (uint8_t*){NAME}, byteLength); jerry_release_value (buffer); }} else {{ {NAME} = NULL; }} ''' # Return Object JS_RETURN_OBJECT = ''' // create object from record jerry_value_t {NAME} = {RECORD}_js_creator({FROM}); jerry_set_object_native_pointer({NAME}, {FROM}, &{RECORD}_type_info); ''' # Alloc record JS_ALLOC_RECORD = ''' {RECORD}* {NAME} = ({RECORD}*)calloc(1, sizeof({RECORD})); ''' # Template for check js type JS_VALUE_IS = '''jerry_value_is_{TYPE} ({JVAL})''' JS_POINTER_IS = '''(jerry_value_is_{TYPE} ({JVAL}) || jerry_value_is_null ({JVAL}))''' JS_CHECK_RECORD = ''' bool jerry_value_is_{RECORD} (jerry_value_t jval) {{ if (!jerry_value_is_object (jval)) {{ return false; }} void* ptr; const jerry_object_native_info_t* type_ptr; bool has_ptr = jerry_get_object_native_pointer(jval, &ptr, &type_ptr); if (!has_ptr || (type_ptr != &{RECORD}_type_info && type_ptr != &{RECORD}_type_info_static)) {{ return false; }} return true; }} ''' # Templates for record types # Record destructor JS_RECORD_DESTRUCTOR = ''' void {RECORD}_js_destructor(void* ptr) {{ delete ({TYPE}*)ptr; }} static const jerry_object_native_info_t {RECORD}_type_info = {{ .free_cb = {RECORD}_js_destructor }}; static const jerry_object_native_info_t {RECORD}_type_info_static = {{ .free_cb = NULL }}; ''' # Record constructor JS_RECORD_CONSTRUCTOR = ''' // external function for record constructor jerry_value_t {RECORD}{SUFF}_js_constructor (const jerry_value_t function_obj, const jerry_value_t this_val, const jerry_value_t args_p[], const jerry_length_t args_cnt) {{ {TYPE}* native_ptr; switch (args_cnt) {{ {CASE} default: {{ char const *msg = "Wrong argument count for {RECORD} constructor."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); }} }} jerry_value_t ret_val = {RECORD}_js_creator(native_ptr); jerry_set_object_native_pointer(ret_val, native_ptr, &{RECORD}_type_info); return ret_val; }} ''' JS_CONSTR_CALL = ''' if ({CONDITION}) {{ {GET_VAL} native_ptr = new {NAME}({PARAMS}); {FREE} break; }} ''' JS_CONSTR_CASE_0 = ''' case 0: {{ native_ptr = new {NAME}(); break; }} ''' JS_CONSTR_CASE = ''' case {NUM}: {{ {CALLS} char const *msg = "Wrong argument type for {NAME} constructor."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); }} ''' JS_REGIST_METHOD = ''' // set record method as a property to the object jerry_value_t {NAME}_name = jerry_create_string ((const jerry_char_t*)"{NAME}"); jerry_value_t {NAME}_func = jerry_create_external_function ({RECORD}_{NAME}_handler); jerry_value_t {NAME}_ret = jerry_set_property (js_obj, {NAME}_name, {NAME}_func); jerry_release_value ({NAME}_name); jerry_release_value ({NAME}_func); jerry_release_value ({NAME}_ret); ''' JS_REGIST_CONST_MEMBER = ''' // set a constant record member as a property to the object jerry_property_descriptor_t {RECORD}_{NAME}_prop_desc; jerry_init_property_descriptor_fields (&{RECORD}_{NAME}_prop_desc); {RECORD}_{NAME}_prop_desc.is_value_defined = true; {RECORD}_{NAME}_prop_desc.value = {RECORD}_{NAME}_js; jerry_value_t {RECORD}_{NAME}_prop_name = jerry_create_string ((const jerry_char_t *)"{NAME}"); jerry_value_t {RECORD}_{NAME}_return_value = jerry_define_own_property (js_obj, {RECORD}_{NAME}_prop_name, &{RECORD}_{NAME}_prop_desc); jerry_release_value ({RECORD}_{NAME}_return_value); jerry_release_value ({RECORD}_{NAME}_prop_name); jerry_free_property_descriptor_fields (&{RECORD}_{NAME}_prop_desc); ''' # Record method JS_RECORD_METHOD = ''' // external function for record method jerry_value_t {RECORD}_{NAME}{SUFF}_handler (const jerry_value_t function_obj, const jerry_value_t this_val, const jerry_value_t args_p[], const jerry_length_t args_cnt) {{ void* void_ptr; const jerry_object_native_info_t* type_ptr; bool has_ptr = jerry_get_object_native_pointer(this_val, &void_ptr, &type_ptr); if (!has_ptr || (type_ptr != &{RECORD}_type_info && type_ptr != &{RECORD}_type_info_static)) {{ char const *msg = "Failed to get native {RECORD} pointer"; return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t *)msg); }} {TYPE}* native_ptr = ({TYPE}*)(void_ptr); {RESULT} switch (args_cnt) {{ {CASE} default: {{ char const *msg = "Wrong argument count for {RECORD}.{NAME}()."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); }} }} {RET_VAL} return ret_val; }} ''' JS_METHOD_CALL = ''' if ({CONDITION}) {{ {GET_VAL} {RESULT}native_ptr->{NAME}({PARAMS}); {FREE} break; }} ''' JS_METHOD_CASE_0 = ''' case 0: {{ {RESULT}native_ptr->{NAME}(); break; }} ''' JS_METHOD_CASE = ''' case {NUM}: {{ {CALLS} char const *msg = "Wrong argument type for {RECORD}.{NAME}()."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); }} ''' # Templates for C++ functions # Function JS_EXT_CPP_FUNC = ''' // external function for API functions jerry_value_t {NAME}{SUFF}_handler (const jerry_value_t function_obj, const jerry_value_t this_val, const jerry_value_t args_p[], const jerry_length_t args_cnt) {{ {RESULT} switch (args_cnt) {{ {CASE} default: {{ char const *msg = "Wrong argument count for {NAME}()."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); }} }} {RET_VAL} return ret_val; }} ''' JS_FUNC_CALL = ''' if ({CONDITION}) {{ {GET_VAL} {RESULT}{NAME}({PARAMS}); {FREE} break; }} ''' JS_FUNC_CASE_0 = ''' case 0: {{ {RESULT}{NAME}(); break; }} ''' JS_FUNC_CASE = ''' case {NUM}: {{ {CALLS} char const *msg = "Wrong argument type for {NAME}()."; return jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t*)msg); }} ''' # Templates for the module initialization function INIT_FUNC = ''' // init function for the module extern "C" jerry_value_t Init_{NAME}() {{ {BODY} return object; }} ''' # Template for include the right headers INCLUDE = ''' #include #include #include "jerryscript.h" #include "{HEADER}" ''' # Templates for modules.json, module.cmake and CMakeLists.txt MODULES_JSON = ''' {{ "modules": {{ "{NAME}_module": {{ "native_files": [], "init": "Init_{NAME}", "cmakefile": "{CMAKE}" }} }} }} ''' MODULE_CMAKE = ''' set(MODULE_NAME "{NAME}_module") add_subdirectory(${{MODULE_DIR}}/src/ ${{MODULE_BINARY_DIR}}/${{MODULE_NAME}}) link_directories(${{MODULE_DIR}}) list(APPEND MODULE_LIBS {NAME}_binding {LIBRARY} stdc++) ''' CMAKE_LISTS = ''' project({NAME} CXX) add_library({NAME}_binding STATIC {NAME}_js_binding.cpp ) target_include_directories({NAME}_binding PRIVATE ${{JERRY_INCLUDE_DIR}}) target_link_libraries({NAME}_binding PUBLIC stdc++) ''' iotjs-1.0+715/tools/module_generator/source_generator.py000066400000000000000000001237201371177304000234350ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2019-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. import c_source_templates as c import cpp_source_templates as cpp class CSourceGenerator(object): def __init__(self): self.function_names = [] self.record_names = [] self.variable_names = [] self.enums = [] self.constant_variables = [] self.number_arrays = [] self.namespace = [] self.macros = [] self.init_func_body = [] self.global_records = [] self.global_const_records = [] @property def ns_name(self): if self.namespace: return '_'.join(self.namespace) + '_' return '' @property def parent_ns_name(self): if self.namespace[:-1]: return '_'.join(self.namespace[:-1]) + '_' return '' @property def scope_name(self): if self.namespace: return '::'.join(self.namespace) + '::' return '' # methods for create/set a C variable def js_to_char(self, _type, name, jval): return c.JS_TO_CHAR.format(TYPE=_type, NAME=name, JVAL=jval) def js_set_char(self, name, jval): return c.JS_SET_CHAR.format(NAME=name, JVAL=jval) def js_to_number(self, _type, name, jval): return c.JS_TO_NUMBER.format(TYPE=_type, NAME=name, JVAL=jval) def js_set_number(self, name, jval): return c.JS_SET_NUMBER.format(NAME=name, JVAL=jval) def js_to_bool(self, _type, name, jval): return c.JS_TO_BOOL.format(TYPE=_type, NAME=name, JVAL=jval) def js_set_bool(self, name, jval): return c.JS_SET_BOOL.format(NAME=name, JVAL=jval) def js_to_string(self, _type, name, jval): return c.JS_TO_STRING.format(TYPE=_type, NAME=name, JVAL=jval) def js_free_string(self, name, jval): return c.JS_FREE_STRING.format(NAME=name, JVAL=jval) def js_set_char_pointer(self, _type, name, jval): return c.JS_SET_CHAR_PTR.format(TYPE=_type, NAME=name, JVAL=jval) def js_set_char_array(self, name, jval, size): return c.JS_SET_CHAR_ARR.format(NAME=name, JVAL=jval, SIZE=size) def js_to_num_pointer(self, _type, name, jval): return c.JS_TO_TYPEDARRAY.format(TYPE=_type, NAME=name, JVAL=jval) def js_free_buffer(self, name, jval): return c.JS_FREE_BUFFER.format(NAME=name, JVAL=jval) def js_free_write_buffer(self, name, jval): return c.JS_FREE_WRITE_BUFFER.format(NAME=name, JVAL=jval) def js_set_num_pointer(self, _type, name, jval): return c.JS_SET_TYPEDARRAY.format(TYPE=_type, NAME=name, JVAL=jval) def js_to_record(self, _type, name, jval, record): return c.JS_TO_RECORD.format(TYPE=_type, NAME=name, JVAL=jval, RECORD=record) def js_set_record(self, _type, name, jval, record): return c.JS_SET_RECORD.format(TYPE=_type, NAME=name, JVAL=jval, RECORD=record) def js_set_const_record(self, _type, name, jval, record): return c.JS_SET_CONST_RECORD.format(TYPE=_type, NAME=name, JVAL=jval, RECORD=record) def js_to_record_ptr(self, _type, name, jval, record): return c.JS_TO_RECORD_PTR.format(TYPE=_type, NAME=name, JVAL=jval, RECORD=record) def js_to_function(self, func, name, jval, _type, params): return c.JS_TO_FUNCTION.format(FUNC=func, NAME=name, JVAL=jval, TYPE=_type, PARAMS=params) def js_cb_function(self, func, name, ret_t, params, length, create_val, result, ret): return c.JS_CB_FUNCTION.format(FUNC=func, NAME=name, RET_TYPE=ret_t, PARAMS=params, LENGTH=length, RET=ret, CREATE_VAL=create_val, RESULT=result) def js_to_unsupported(self, _type, name): return c.JS_TO_UNSUPPORTED.format(TYPE=_type, NAME=name) def js_to_c(self, c_type, name, jval): if c_type.is_char(): return self.js_to_char(c_type.name, name, jval) elif c_type.is_number() or c_type.is_enum(): return self.js_to_number(c_type.name, name, jval) elif c_type.is_bool(): return self.js_to_bool(c_type.name, name, jval) elif c_type.is_pointer(): pointee = c_type.get_pointee_type() if pointee.is_char(): return self.js_to_string(pointee.name, name, jval) elif pointee.is_number(): return self.js_to_num_pointer(pointee.name, name, jval) elif pointee.is_record(): record = pointee.get_as_record_decl().ns_name return self.js_to_record_ptr(pointee.name, name, jval, record) elif c_type.is_record(): record = c_type.get_as_record_decl().ns_name return self.js_to_record(c_type.name, name, jval, record) return self.js_to_unsupported(c_type.name, name) def js_set_c(self, c_type, name, jval): if c_type.is_char(): return self.js_set_char(name, jval) elif c_type.is_number() or c_type.is_enum(): return self.js_set_number(name, jval) elif c_type.is_bool(): return self.js_set_bool(name, jval) elif c_type.is_pointer(): pointee = c_type.get_pointee_type() if c_type.is_array(): size = c_type.get_array_size() - 1 if pointee.is_char(): return self.js_set_char_array(name, jval, size) elif pointee.is_number(): return self.js_set_num_pointer(pointee.name, name, jval) else: if pointee.is_char(): return self.js_set_char_pointer(pointee.name, name, jval) elif pointee.is_number(): return self.js_set_num_pointer(pointee.name, name, jval) elif c_type.is_record(): record = c_type.get_as_record_decl().ns_name if c_type.has_const_member(): return self.js_set_const_record(c_type.name, name, jval, record) return self.js_set_record(c_type.name, name, jval, record) return self.js_to_unsupported(c_type.name, name) # methods for create a JS variable def void_to_js(self, name): return c.JS_CREATE_VAL.format(NAME=name, TYPE='undefined', FROM='') def char_to_js(self, name, cval): return c.JS_CREATE_CHAR.format(NAME=name, FROM=cval) def number_to_js(self, name, cval): return c.JS_CREATE_VAL.format(NAME=name, TYPE='number', FROM=cval) def bool_to_js(self, name, cval): return c.JS_CREATE_VAL.format(NAME=name, TYPE='boolean', FROM=cval) def string_to_js(self, name, cval): return c.JS_CREATE_STRING.format(NAME=name, FROM=cval) def num_pointer_to_js(self, name, cval, _type): return c.JS_CREATE_TYPEDARRAY.format(NAME=name, FROM=cval, TYPE=_type, ARRAY_TYPE=c.TYPEDARRAYS[_type]) def record_to_js(self, name, cval, _type, record): return c.JS_CREATE_OBJECT.format(NAME=name, FROM=cval, TYPE=_type, RECORD=record) def const_record_to_js(self, name, cval, _type, record): return c.JS_CREATE_CONST_OBJECT.format(NAME=name, FROM=cval, TYPE=_type, RECORD=record) def unsupported_to_js(self, name, cval): return c.JS_CREATE_UNSUPPORTED.format(NAME=name, FROM=cval) def c_to_js(self, c_type, cval, name): if c_type.is_void(): return self.void_to_js(name) elif c_type.is_char(): return self.char_to_js(name, cval) elif c_type.is_number() or c_type.is_enum(): return self.number_to_js(name, cval) elif c_type.is_bool(): return self.bool_to_js(name, cval) elif c_type.is_pointer(): pointee = c_type.get_pointee_type() if pointee.is_char(): return self.string_to_js(name, cval) elif pointee.is_number(): return self.num_pointer_to_js(name, cval, pointee.name) elif c_type.is_record(): record = c_type.get_as_record_decl().ns_name if c_type.has_const_member(): return self.const_record_to_js(name, cval, c_type.name, record) return self.record_to_js(name, cval, c_type.name, record) return self.unsupported_to_js(name, cval) def js_record_destructor(self, _type, record): return c.JS_RECORD_DESTRUCTOR.format(TYPE=_type, RECORD=record) def js_record_member(self, _type, record, name, body): return c.JS_RECORD_MEMBER.format(TYPE=_type, RECORD=record, NAME=name, BODY=body) def js_record_getter(self, name, record): return c.JS_RECORD_GETTER.format(NAME=name, RECORD=record) def js_record_creator(self, _type, record, regist): return c.JS_RECORD_CREATOR.format(TYPE=_type, RECORD=record, REGIST=regist) def js_record_constructor_c(self, _type, record, body): return c.JS_RECORD_CONSTRUCTOR.format(TYPE=_type, RECORD=record, BODY=body) def js_record_return(self, record): return c.JS_RECORD_RETURN.format(RECORD=record) def js_get_prop_struct(self, name, _type, get_val, init=''): return c.JS_GET_PROP_STRUCT.format(NAME=name, TYPE=_type, GET_VAL=get_val, INIT=init) def js_get_prop_union(self, name, _type, get_val, ret, init=''): return c.JS_GET_PROP_UNION.format(NAME=name, TYPE=_type, GET_VAL=get_val, RET=ret, INIT=init) def js_init_members(self, _type, members): return c.JS_INIT_MEMBERS.format(TYPE=_type, MEMBERS=members) def js_init_members_const(self, _type, members): return c.JS_INIT_MEMBERS_CONST.format(TYPE=_type, MEMBERS=members) def js_regist_member(self, record, name): return c.JS_REGIST_MEMBER.format(RECORD=record, NAME=name) def js_regist_record(self, name, record, ref, object): return c.JS_REGIST_RECORD.format(NAME=name, RECORD=record, REF=ref, OBJECT=object) def js_regist_const_member(self, name): return c.JS_REGIST_CONST_MEMBER.format(NAME=name) def js_regist_const_record(self, name, object, value): return c.JS_REGIST_CONST_RECORD.format(NAME=name, OBJECT=object, VALUE=value) def js_regist_num_arr_member(self, name, _type, size): return c.JS_REGIST_ARR_MEMBER.format(NAME=name, TYPE=_type, SIZE=size, ARRAY_TYPE=c.TYPEDARRAYS[_type]) def create_member_getter_setter(self, member, record): name = 'native_ptr->' + member.name record_name = self.ns_name + record.name if member.type.is_record(): getter = self.js_record_getter(member.name, record_name + '_') if member.type.has_const_member(): return getter else: get_result = self.c_to_js(member.type, name, 'ret_val') getter = self.js_record_member(record.type.name, record_name, member.name + '_getter', get_result) set_result = self.js_check_type(member.type, 'args_p[0]', member.name + '_setter') set_result += self.js_set_c(member.type, name, 'args_p[0]') set_result += ' jerry_value_t ret_val = jerry_create_undefined();' setter = self.js_record_member(record.type.name, record_name, member.name + '_setter', set_result) return getter + setter def create_record_constructor(self, record): name = self.ns_name + record.name type_name = record.type.name is_struct = record.type.is_struct() is_union = record.type.is_union() has_const_member = record.type.has_const_member() constructor = [] members = [] free = [] for member in record.field_decls: m_name = member.name m_type = member.type jval = '{}_value'.format(m_name) init = '' get_val = self.js_set_c(m_type, m_name, jval) if m_type.is_array(): size = m_type.get_array_size() init_array = ['{' + m_name + '[0]'] for i in range(size-2): init_array.append('{}[{}]'.format(m_name, i+1)) init_array.append('{}[{}]}}'.format(m_name, size-1)) init_array = (', ').join(init_array) members.append(init_array) m_type = m_type.get_array_type() init = '[{}]'.format(size) if is_union: if has_const_member: get_val += self.js_init_members_const(type_name, init_array) else: get_val += self.js_init_members(type_name, init_array) else: members.append(m_name) if member.type.is_record(): if not member.type.get_as_record_decl().has_constructor(): init = ' = {}' if is_union: if has_const_member: get_val += self.js_init_members_const(type_name, m_name) else: get_val += self.js_init_members(type_name, m_name) if m_type.is_pointer(): if m_type.get_pointee_type().is_char(): free.append(self.js_free_string(m_name, jval)) if is_union: get_val += self.js_free_string(m_name, jval) elif m_type.get_pointee_type().is_number(): free.append(self.js_free_buffer(m_name, jval)) if is_union: get_val += self.js_free_buffer(m_name, jval) if is_struct: constructor.append(self.js_get_prop_struct(m_name, m_type.name, get_val, init)) elif is_union: ret = self.js_record_return(name) constructor.append(self.js_get_prop_union(m_name, m_type.name, get_val, ret, init)) constructor = ('').join(constructor) members = (', ').join(members) free = ('').join(free) if has_const_member: members = self.js_init_members_const(type_name, members) else: members = self.js_init_members(type_name, members) if is_struct: body = constructor + members + free elif is_union: body = constructor return self.js_record_constructor_c(type_name, name, body) def create_record(self, record): name = record.name type_name = record.type.name self.record_names.append(name) result = [self.js_record_destructor(type_name, name)] regist = [] for member in record.field_decls: m_name = member.name m_type = member.type if m_type.is_const(): cval = 'native_ptr->' + m_name jval = m_name + '_js' regist.append(self.c_to_js(m_type, cval, jval)) regist.append(self.js_regist_const_member(m_name)) elif m_type.get_array_type().is_number(): arr_name = m_type.get_array_type().name size = m_type.get_array_size() regist.append(self.js_regist_num_arr_member(m_name, arr_name, size)) else: get_set = self.create_member_getter_setter(member, record) result.append(get_set) if m_type.is_record(): r_name = m_type.get_as_record_decl().ns_name ref = 'native_ptr->{}'.format(m_name) regist.append(self.js_regist_record(m_name, r_name, ref, 'js_obj')) if m_type.has_const_member(): r_name = name + '_' + m_name regist.append(self.js_regist_const_record(r_name, 'js_obj', m_name)) else: regist.append(self.js_regist_member(name, m_name)) else: regist.append(self.js_regist_member(name, m_name)) regist = ('').join(regist) result.append(self.js_record_creator(type_name, name, regist)) result.append(self.create_record_constructor(record)) return '\n'.join(result) def create_c_function(self, func, funcname, name): params = [] create_val = [] res= '' ret = '' for index, param in enumerate(func.params): param_name = 'p_{}'.format(index) arg_name = 'arg_{}'.format(index) params.append(param.type.name + ' ' + param_name) create_val.append(self.c_to_js(param.type, param_name, arg_name)) create_val.append(' args[{}] = {};'.format(index, arg_name)) if not func.return_type.is_void(): res = self.js_to_c(func.return_type, 'ret', 'result') ret = 'ret' return self.js_cb_function(funcname, name, func.return_type.name, (', ').join(params), len(func.params), ('\n').join(create_val), res, ret) def js_ext_func(self, name, body): return c.JS_EXT_FUNC.format(NAME=name, BODY=body) def js_check_arg_count(self, count, func): return c.JS_CHECK_ARG_COUNT.format(COUNT=count, FUNC=func) def js_check_type(self, c_type, jval, func): _type = '' template = c.JS_CHECK_TYPE if c_type.is_char(): _type = 'string' elif c_type.is_number() or c_type.is_enum(): _type = 'number' elif c_type.is_record(): _type = 'object' elif c_type.is_function(): template = c.JS_CHECK_POINTER _type = 'function' elif c_type.is_pointer(): template = c.JS_CHECK_POINTER if c_type.get_pointee_type().is_char(): _type = 'string' elif c_type.get_pointee_type().is_number(): _type = 'typedarray' elif c_type.get_pointee_type().is_function(): _type = 'function' elif c_type.get_pointee_type().is_record(): _type = 'object' if _type: return template.format(TYPE=_type, JVAL=jval, FUNC=func) return '' def get_val_from_param(self, param, funcname, name, jval): buff = [] callback = '' if (param.type.is_pointer() and param.type.get_pointee_type().is_function()): func = param.get_as_function() ret_type = func.return_type.name params = ', '.join([p.type.name for p in func.params]) result = self.js_to_function(funcname, name, jval, ret_type, params) callback = self.create_c_function(func, funcname, name) elif param.type.is_function(): func = param.get_as_function() ret_type = func.return_type.name params = ', '.join([p.type.name for p in func.params]) result = self.js_to_function(funcname, name, jval, ret_type, params) callback = self.create_c_function(func, funcname, name) else: result = self.js_to_c(param.type, name, jval) if param.type.is_pointer(): if param.type.get_pointee_type().is_char(): buff.append(self.js_free_string(name, jval)) if param.type.get_pointee_type().is_number(): buff.append(self.js_free_write_buffer(name, jval)) return result, buff, callback def create_ext_function(self, function): self.function_names.append(function.name) funcname = function.name params = function.params return_type = function.return_type jerry_function = [] native_params = [] buffers_to_free = [] callbacks = [] jerry_function.append(self.js_check_arg_count(len(params), funcname)) for index, param in enumerate(params): jval = 'args_p[{}]'.format(index) native_name = 'arg_{}'.format(index) check_type = self.js_check_type(param.type, jval, funcname) result = self.get_val_from_param(param, funcname, native_name, jval) buffers_to_free += result[1] callbacks.append(result[2]) native_params.append(native_name) jerry_function.append(check_type + result[0]) native_params = (', ').join(native_params) if return_type.is_void(): native_call = ' {} ({});\n'.format(funcname, native_params) else: native_call = ' {} {} = {} ({});\n'.format(return_type.name, 'result', funcname, native_params) jerry_function.append(' // native function call\n' + native_call) jerry_function += buffers_to_free result = self.c_to_js(return_type, 'result', 'ret_val') jerry_function.append(result) callbacks = '\n'.join(callbacks) jerry_function = '\n'.join(jerry_function) ext_func = self.js_ext_func(funcname + '_handler', jerry_function) return callbacks + ext_func def create_getter_setter(self, var): if var.type.is_const(): self.constant_variables.append(var) return '' elif var.type.get_array_type().is_number(): self.number_arrays.append(var) return '' ns_name = self.ns_name + var.name scope_name = self.scope_name + var.name if var.type.is_record(): record = var.type.get_as_record_decl().ns_name self.global_records.append((var.name, record)) getter = self.js_record_getter(ns_name, '') if var.type.has_const_member(): self.global_const_records.append(var.name) return getter else: get_result = self.c_to_js(var.type, scope_name, 'ret_val') getter = self.js_ext_func(ns_name + '_getter', get_result) self.variable_names.append(var.name) set_result = self.js_check_type(var.type, 'args_p[0]', ns_name + '_setter') set_result += self.js_set_c(var.type, scope_name, 'args_p[0]') set_result += ' jerry_value_t ret_val = jerry_create_undefined();' setter = self.js_ext_func(ns_name + '_setter', set_result) return getter + setter def init_func(self, name, body): return c.INIT_FUNC.format(NAME=name, BODY=body) def init_regist_func(self, name, object, func): return c.INIT_REGIST_FUNC.format(NAME=name, OBJECT=object, FUNC=func) def init_regist_record(self, name, object, record): return c.INIT_REGIST_RECORD.format(NAME=name, OBJECT=object, RECORD=record) def init_regist_enum(self, name, object, ref, enum): return c.INIT_REGIST_ENUM.format(NAME=name, OBJECT=object, REF=ref, ENUM=enum) def init_regist_value(self, name, object, value): return c.INIT_REGIST_VALUE.format(NAME=name, OBJECT=object, VALUE=value) def init_regist_const(self, name, object, value): return c.INIT_REGIST_CONST.format(NAME=name, OBJECT=object, VALUE=value) def init_regist_num_arr(self, name, object, ref, arr, _type, size): return c.INIT_REGIST_NUM_ARR.format(NAME=name, OBJECT=object, REF=ref, ARR=arr, TYPE=_type, SIZE=size, ARRAY_TYPE=c.TYPEDARRAYS[_type]) def init_create_object(self, name): return c.INIT_CREATE_OBJECT.format(NAME=name) def init_regist_object(self, name, ref, object): return c.INIT_REGIST_OBJECT.format(NAME=name, REF=ref, OBJECT=object) def create_ns_obj(self): self.init_func_body.append(self.init_create_object(self.ns_name)) def regist_ns_obj(self): if self.namespace: name = self.ns_name ref = self.namespace[-1] object = '{}object'.format(self.parent_ns_name) self.init_func_body.append(self.init_regist_object(name, ref, object)) def create_init_function_body(self): object = '{}object'.format(self.ns_name) for funcname in self.function_names: name = self.ns_name + funcname self.init_func_body.append(self.init_regist_func(name, object, funcname)) for record in self.record_names: name = self.ns_name + record self.init_func_body.append(self.init_regist_record(name, object, record)) for varname in self.variable_names: name = self.ns_name + varname self.init_func_body.append(self.init_regist_value(name, object, varname)) for glob_record in self.global_records: name = self.ns_name + glob_record[0] ref = self.scope_name + glob_record[0] record = glob_record[1] self.init_func_body.append(self.js_regist_record(name, record, ref, object)) for c_record in self.global_const_records: name = self.ns_name + c_record self.init_func_body.append(self.js_regist_const_record(name, object, c_record)) for array in self.number_arrays: name = self.ns_name + array.name ref = self.scope_name + array.name typename = array.type.get_array_type().name size = array.type.get_array_size() self.init_func_body.append(self.init_regist_num_arr(name, object, ref, array.name, typename, size)) for var in self.constant_variables: name = self.ns_name + var.name ref = self.scope_name + var.name jval = '{}_js'.format(name) self.init_func_body.append(self.c_to_js(var.type, ref, jval)) self.init_func_body.append(self.init_regist_const(name, object, var.name)) for enum in self.enums: name = self.ns_name + enum ref = self.scope_name + enum self.init_func_body.append(self.init_regist_enum(name, object, ref, enum)) for macro in self.macros: name = macro.name jval = '{}_js'.format(name) if macro.is_char(): create_val = ' char {N}_value = {N};'.format(N=name) value = '{}_value'.format(name) self.init_func_body.append(create_val) self.init_func_body.append(self.char_to_js(jval, value)) self.init_func_body.append(self.init_regist_const(name, object, name)) elif macro.is_string(): self.init_func_body.append(self.string_to_js(jval, name)) self.init_func_body.append(self.init_regist_const(name, object, name)) elif macro.is_number(): self.init_func_body.append(self.number_to_js(jval, name)) self.init_func_body.append(self.init_regist_const(name, object, name)) del self.function_names[:] del self.record_names[:] del self.variable_names[:] del self.global_records[:] del self.global_const_records[:] del self.number_arrays[:] del self.constant_variables[:] del self.enums[:] del self.macros[:] def create_init_function(self, dirname): return self.init_func(dirname, ('\n').join(self.init_func_body)) class CppSourceGenerator(CSourceGenerator): def __init__(self): CSourceGenerator.__init__(self) self.class_names = [] def js_to_string(self, _type, name, jval): return cpp.JS_TO_STRING.format(TYPE=_type, NAME=name, JVAL=jval) def js_free_string(self, name, jval): return cpp.JS_FREE_STRING.format(NAME=name, JVAL=jval) def js_set_char_pointer(self, _type, name, jval): return cpp.JS_SET_CHAR_PTR.format(TYPE=_type, NAME=name, JVAL=jval) def js_to_num_pointer(self, _type, name, jval): return cpp.JS_TO_TYPEDARRAY.format(TYPE=_type, NAME=name, JVAL=jval) def js_free_write_buffer(self, name, jval): return cpp.JS_FREE_WRITE_BUFFER.format(NAME=name, JVAL=jval) def js_set_num_pointer(self, _type, name, jval): return cpp.JS_SET_TYPEDARRAY.format(TYPE=_type, NAME=name, JVAL=jval) def js_return_object(self, name, record, cval): return cpp.JS_RETURN_OBJECT.format(NAME=name, RECORD=record, FROM=cval) def js_alloc_record(self, record, name): return cpp.JS_ALLOC_RECORD.format(RECORD=record, NAME=name) def js_value_is(self, c_type, jval): if c_type.is_char(): return cpp.JS_VALUE_IS.format(TYPE='string', JVAL=jval) elif c_type.is_number() or c_type.is_enum(): return cpp.JS_VALUE_IS.format(TYPE='number', JVAL=jval) elif c_type.is_bool(): return cpp.JS_VALUE_IS.format(TYPE='boolean', JVAL=jval) elif c_type.is_record(): record = c_type.get_as_record_decl().ns_name return cpp.JS_VALUE_IS.format(TYPE=record, JVAL=jval) elif c_type.is_function(): return cpp.JS_POINTER_IS.format(TYPE='function', JVAL=jval) elif c_type.is_pointer(): if c_type.get_pointee_type().is_char(): return cpp.JS_POINTER_IS.format(TYPE='string', JVAL=jval) elif c_type.get_pointee_type().is_number(): return cpp.JS_POINTER_IS.format(TYPE='typedarray', JVAL=jval) elif c_type.get_pointee_type().is_function(): return cpp.JS_POINTER_IS.format(TYPE='function', JVAL=jval) elif c_type.get_pointee_type().is_record(): record = c_type.get_pointee_type().get_as_record_decl().ns_name return cpp.JS_POINTER_IS.format(TYPE=record, JVAL=jval) return '' def js_check_record(self, record): return cpp.JS_CHECK_RECORD.format(RECORD=record) def js_record_destructor(self, _type, record): return cpp.JS_RECORD_DESTRUCTOR.format(TYPE=_type, RECORD=record) def js_record_constructor_cpp(self, _type, record, case, suff = ''): return cpp.JS_RECORD_CONSTRUCTOR.format(TYPE=_type, RECORD=record, CASE=case, SUFF=suff) def js_constr_call(self, condition, get_val, name, params, free): return cpp.JS_CONSTR_CALL.format(CONDITION=condition, GET_VAL=get_val, NAME=name, PARAMS=params, FREE=free) def js_constr_case_0(self, name): return cpp.JS_CONSTR_CASE_0.format(NAME=name) def js_constr_case(self, num, calls, name): return cpp.JS_CONSTR_CASE.format(NUM=num, CALLS=calls, NAME=name) def js_regist_method(self, record, name): return cpp.JS_REGIST_METHOD.format(RECORD=record, NAME=name) def js_regist_const_member(self, record, name): return cpp.JS_REGIST_CONST_MEMBER.format(RECORD=record, NAME=name) def js_record_method(self, record, name, _type, result, case, ret_val, suff): return cpp.JS_RECORD_METHOD.format(RECORD=record, NAME=name, TYPE=_type, RESULT=result, CASE=case, RET_VAL=ret_val, SUFF=suff) def js_method_call(self, condition, get_val, result, name, params, free): return cpp.JS_METHOD_CALL.format(CONDITION=condition, GET_VAL=get_val, RESULT=result, NAME=name, PARAMS=params, FREE=free) def js_method_case_0(self, result, name): return cpp.JS_METHOD_CASE_0.format(RESULT=result, NAME=name) def js_method_case(self, num, calls, record, name): return cpp.JS_METHOD_CASE.format(NUM=num, CALLS=calls, RECORD=record, NAME=name) def js_ext_cpp_func(self, name, result, case, ret_val, suff): return cpp.JS_EXT_CPP_FUNC.format(NAME=name, RESULT=result, CASE=case, RET_VAL=ret_val, SUFF=suff) def js_func_call(self, condition, get_val, result, name, params, free): return cpp.JS_FUNC_CALL.format(CONDITION=condition, GET_VAL=get_val, RESULT=result, NAME=name, PARAMS=params, FREE=free) def js_func_case_0(self, result, name): return cpp.JS_FUNC_CASE_0.format(RESULT=result, NAME=name) def js_func_case(self, num, calls, name): return cpp.JS_FUNC_CASE.format(NUM=num, CALLS=calls, NAME=name) def create_record(self, record): name = record.name ns_name = self.ns_name + name record_type = record.type.name result = [self.js_record_destructor(record_type, ns_name), self.js_check_record(ns_name)] regist = [] for member in record.field_decls: m_name = member.name if member.type.is_const(): cval = 'native_ptr->' + m_name jval = name + '_' + m_name + '_js' regist.append(self.c_to_js(member.type, cval, jval)) regist.append(self.js_regist_const_member(name, m_name)) elif member.type.get_array_type().is_number(): arr_name = member.type.get_array_type().name size = member.type.get_array_size() regist.append(self.js_regist_num_arr_member(m_name, arr_name, size)) else: get_set = self.create_member_getter_setter(member, record) result.append(get_set) if member.type.is_record(): r_name = member.type.get_as_record_decl().ns_name ref = 'native_ptr->{}'.format(m_name) regist.append(self.js_regist_record(m_name, r_name, ref, 'js_obj')) if member.type.has_const_member(): r_name = ns_name + '_' + m_name regist.append(self.js_regist_const_record(r_name, 'js_obj', m_name)) else: regist.append(self.js_regist_member(ns_name, m_name)) else: regist.append(self.js_regist_member(ns_name, m_name)) for method in record.methods: result.append(self.create_ext_function(method, name, record_type, is_method=True)) regist.append(self.js_regist_method(ns_name, method.name + method.suffix)) regist = ('\n').join(regist) result.append(self.js_record_creator(record_type, ns_name, regist)) if record.has_constructor(): if not record.constructors: self.record_names.append(name) cases = self.js_constr_case_0(self.scope_name + name) result.append(self.js_record_constructor_cpp(record_type, ns_name, cases)) else: for constr in record.constructors: self.record_names.append(name + constr.suffix) cases = self.create_ext_function(constr, name, is_constructor=True) result.append(self.js_record_constructor_cpp(record_type, ns_name, cases, constr.suffix)) else: self.record_names.append(name) result.append(self.create_record_constructor(record)) return '\n'.join(result) def create_ext_function(self, func, record_name = None, record_type = None, is_constructor = False, is_method = False): name = func.name if not is_constructor else record_name scope_name = self.scope_name + name cases = [] callbacks = [] if not is_constructor: ret_type = func.return_type if ret_type.is_void(): result = '' elif ret_type.is_record(): result = '*result = ' else: result = 'result = ' if is_constructor and 0 in func.params: cases.append(self.js_constr_case_0(scope_name)) if func.params: del func.params[0] elif is_method and 0 in func.params: cases.append(self.js_method_case_0(result, name)) del func.params[0] elif 0 in func.params: cases.append(self.js_func_case_0(result, scope_name)) del func.params[0] for parm_len, param_lists in func.params.items(): calls = [] for param_list in param_lists: get_val = '' condition = [] native_params = [] free_buffers = [] for index, param in enumerate(param_list): jval = 'args_p[{}]'.format(index) p_name = 'arg_{}'.format(index) condition.append(self.js_value_is(param.type, jval)) res = self.get_val_from_param(param, name, p_name, jval) get_val += res[0] free_buffers += res[1] callbacks.append(res[2]) native_params.append(p_name) native_params = (', ').join(native_params) condition = (' && ').join(condition) free_buffers = ('\n').join(free_buffers) if is_constructor: calls.append(self.js_constr_call(condition, get_val, scope_name, native_params, free_buffers)) elif is_method: calls.append(self.js_method_call(condition, get_val, result, name, native_params, free_buffers)) else: calls.append(self.js_func_call(condition, get_val, result, scope_name, native_params, free_buffers)) calls = ('\n').join(calls) if is_constructor: cases.append(self.js_constr_case(parm_len, calls, name)) elif is_method: cases.append(self.js_method_case(parm_len, calls, record_name, name)) else: cases.append(self.js_func_case(parm_len, calls, name)) callbacks = '\n'.join(callbacks) cases = ''.join(cases) if is_constructor: return cases if ret_type.is_record(): record = ret_type.get_as_record_decl() if record.has_default_constructor(): result = '{T}* result = new {T}();'.format(T=ret_type.name) else: result = self.js_alloc_record(ret_type.name, 'result') ns_name = self.ns_name + record.name ret_val = self.js_return_object('ret_val', ns_name, 'result') else: if not ret_type.is_void(): result = '{} result;'.format(ret_type.name) ret_val = self.c_to_js(ret_type, 'result', 'ret_val') if is_method: return self.js_record_method(self.ns_name + record_name, name, record_type, result, cases, ret_val, func.suffix) else: self.function_names.append(name + func.suffix) return callbacks + self.js_ext_cpp_func(self.ns_name + name, result, cases, ret_val, func.suffix) def init_func(self, name, body): return cpp.INIT_FUNC.format(NAME=name, BODY=body) iotjs-1.0+715/tools/module_templates/000077500000000000000000000000001371177304000175205ustar00rootroot00000000000000iotjs-1.0+715/tools/module_templates/basic_module_template/000077500000000000000000000000001371177304000240415ustar00rootroot00000000000000iotjs-1.0+715/tools/module_templates/basic_module_template/js/000077500000000000000000000000001371177304000244555ustar00rootroot00000000000000iotjs-1.0+715/tools/module_templates/basic_module_template/js/module.js000066400000000000000000000017701371177304000263050ustar00rootroot00000000000000/* Copyright 2018-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. */ /** * To export an object/value use the 'module.exports' object. */ var demo_value = "Hello"; /* Export an object with two properties. */ module.exports = { /* the 'native' means the object returned by the C init method. */ demo2: function() { return native.message; }, add: native.add } /* Export a local variable. */ module.exports.demo_value = demo_value; iotjs-1.0+715/tools/module_templates/basic_module_template/module.cmake000066400000000000000000000032351371177304000263330ustar00rootroot00000000000000# Copyright 2018-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. # General variables usable from IoT.js cmake: # - TARGET_ARCH - the target architecture (as specified during cmake step) # - TARGET_BOARD - the target board(/device) # - TARGET_OS - the target operating system # # Module related variables usable from IoT.js cmake: # - MODULE_DIR - the modules root directory # - MODULE_BINARY_DIR - the build directory for the current module # - MODULE_LIBS - list of libraries to use during linking (set this) set(MODULE_NAME "$MODULE_NAME$") # DO NOT include the source files which are already in the modules.json file. # If the module builds its own files into a lib please use the line below. # Note: the subdir 'lib' should contain the CMakeLists.txt describing how the # module should be built. #add_subdirectory(${MODULE_DIR}/lib/ ${MODULE_BINARY_DIR}/${MODULE_NAME}) # If you wish to link external libraries please add it to # the MODULE_LIBS list. # # IMPORTANT! # if the module builds its own library that should also be specified! # # Example (to add the 'demo' library for linking): # # list(APPEND MODULE_LIBS demo) iotjs-1.0+715/tools/module_templates/basic_module_template/modules.json000066400000000000000000000003021371177304000263770ustar00rootroot00000000000000{ "modules": { "$MODULE_NAME$": { "js_file": "js/module.js", "native_files": ["src/module.c"], "init": "Init$MODULE_NAME$", "cmakefile": "module.cmake" } } } iotjs-1.0+715/tools/module_templates/basic_module_template/src/000077500000000000000000000000001371177304000246305ustar00rootroot00000000000000iotjs-1.0+715/tools/module_templates/basic_module_template/src/module.c000066400000000000000000000034731371177304000262700ustar00rootroot00000000000000/* Copyright 2018-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" /** * Demo method */ static jerry_value_t demo_method( const jerry_value_t func_value, /**< function object */ const jerry_value_t this_value, /**< this arg */ const jerry_value_t *args_p, /**< function arguments */ const jerry_length_t args_cnt) /**< number of function arguments */ { if (args_cnt < 2) { static char *error_msg = "Incorrect parameter count"; return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t *)error_msg); } if (!jerry_value_is_number(args_p[0]) || !jerry_value_is_number(args_p[1])) { static char *error_msg = "Incorrect parameter type(s)"; return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t *)error_msg); } int arg_a = jerry_get_number_value(args_p[0]); int arg_b = jerry_get_number_value(args_p[1]); return jerry_create_number(arg_a + arg_b); } /** * Init method called by IoT.js */ jerry_value_t Init$MODULE_NAME$() { jerry_value_t mymodule = jerry_create_object(); iotjs_jval_set_property_string_raw(mymodule, "message", "Hello world!"); iotjs_jval_set_method(mymodule, "add", demo_method); return mymodule; } iotjs-1.0+715/tools/module_templates/shared_module_template/000077500000000000000000000000001371177304000242265ustar00rootroot00000000000000iotjs-1.0+715/tools/module_templates/shared_module_template/CMakeLists.txt000066400000000000000000000021761371177304000267740ustar00rootroot00000000000000# Copyright 2018-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. # # This is a standalone shared libray which # only requires the iotjs and jerry header file(s). # cmake_minimum_required(VERSION 2.8) set(NAME $MODULE_NAME$) set(IOTJS_INCLUDE_DIR "$IOTJS_PATH$/include") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99") add_library(${NAME} SHARED src/module_entry.c) target_include_directories(${NAME} PRIVATE ${IOTJS_INCLUDE_DIR} ${JERRY_INCLUDE_DIR}) set_target_properties(${NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" PREFIX "" SUFFIX ".node") iotjs-1.0+715/tools/module_templates/shared_module_template/README.md000066400000000000000000000003371371177304000255100ustar00rootroot00000000000000# IoT.js module: $MODULE_NAME$ ## How to build? In the source directory of the module: ```sh $ cmake -Bbuild -H. $ make -C build ``` ## How to test? In the source directory of the module: ```sh $ iotjs js/test.js ``` iotjs-1.0+715/tools/module_templates/shared_module_template/js/000077500000000000000000000000001371177304000246425ustar00rootroot00000000000000iotjs-1.0+715/tools/module_templates/shared_module_template/js/test.js000066400000000000000000000013751371177304000261650ustar00rootroot00000000000000/* Copyright 2018-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 console = require("console"); var demo_module = require("build/lib/$MODULE_NAME$"); console.log(demo_module.hello()); iotjs-1.0+715/tools/module_templates/shared_module_template/src/000077500000000000000000000000001371177304000250155ustar00rootroot00000000000000iotjs-1.0+715/tools/module_templates/shared_module_template/src/module_entry.c000066400000000000000000000024241371177304000276710ustar00rootroot00000000000000/* Copyright 2018-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 #include static napi_value hello_world(napi_env env, napi_callback_info info) { napi_value world; const char* str = "Hello world!"; size_t str_len = strlen(str); if (napi_create_string_utf8(env, str, str_len, &world) != napi_ok) return NULL; return world; } napi_value init_$MODULE_NAME$(napi_env env, napi_value exports) { napi_property_descriptor desc = { "hello", 0, hello_world, 0, 0, 0, napi_default, 0 }; if (napi_define_properties(env, exports, 1, &desc) != napi_ok) return NULL; return exports; } NAPI_MODULE($MODULE_NAME$, init_$MODULE_NAME$) iotjs-1.0+715/tools/repl.js000066400000000000000000000053761371177304000154700ustar00rootroot00000000000000/* Copyright 2019-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. */ /** * Minial REPL implementation. * * Notes: * * Currently there is no support for multi-line code input. * * No input history. */ var fs = require('fs'); var EventEmitter = require('events').EventEmitter; var utils = require('util'); function stdin() { EventEmitter.call(this); } utils.inherits(stdin, EventEmitter); stdin.prototype.start = function() { var self = this; var buffer = new Buffer(10); var read = function(buffer) { /* Read from stdin(0) */ fs.read(0, buffer, 0, buffer.length, -1, after_read); }; var after_read = function(err, bytes_read, buffer) { if (err) { throw err; }; if (bytes_read === 0) { self.emit('end'); } else { self.emit('data', buffer.slice(0, bytes_read)); if (!process._exiting) { read(buffer); } } }; read(buffer); } stdin.prototype.readline = function(callback) { var line_parts = []; this.on('data', function(data) { line_parts.push(data); /* Check if the last character is a '\n' */ var has_line_end = (data.readInt8(data.length - 1) == 0x0A); if (has_line_end) { callback(Buffer.concat(line_parts).toString()); line_parts = []; } }); }; function REPL() { this.input = new stdin(); this._prompt_msg = new Buffer('> '); }; REPL.prototype.print_prompt = function() { /* Write to stdout(1) */ fs.writeSync(1, this._prompt_msg, 0, this._prompt_msg.length); }; REPL.prototype.run_code = function(line) { var result; try { /* Doing indirect eval to force everything into the global object. */ result = eval.call(undefined, line); console.log(result); } catch (ex) { console.error(ex); } }; REPL.prototype.process_line = function(line) { this.run_code(line); this.print_prompt(); }; REPL.prototype.start = function() { /* Expose the "require" method for the global object. * This way the "eval" call can access it correctly. */ global.require = require; this.print_prompt(); this.input.start(); this.input.readline(this.process_line.bind(this)); }; var repl = new REPL(); console.log('IoT.js (%s) Minimal REPL', process.version); repl.start(); iotjs-1.0+715/tools/testrunner.py000077500000000000000000000276251371177304000167570ustar00rootroot00000000000000#!/usr/bin/env python # 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. from __future__ import print_function import argparse import json import multiprocessing import os import subprocess import sys import time try: import queue except ImportError: # Backwards compatibility import Queue as queue from collections import OrderedDict from common_py import path from common_py.system.filesystem import FileSystem as fs from common_py.system.executor import Executor from common_py.system.executor import Terminal from common_py.system.sys_platform import Platform # Defines the folder that will contain the coverage info. # The path must be consistent with the measure_coverage.sh script. JS_COVERAGE_FOLDER = fs.join(path.PROJECT_ROOT, '.coverage_output') # This code should be applied to each testfile. JS_COVERAGE_CODE = ( """ process.on('exit', function() {{ if (typeof __coverage__ == 'undefined') return; if (typeof fs == 'undefined') var fs = require('fs'); if (!fs.existsSync('{folder}')) fs.mkdirSync('{folder}'); var filename = '{folder}/{file}'; fs.writeFileSync(filename, Buffer(JSON.stringify(__coverage__))); }}) """ ) # Append coverage source to the appropriate test. def append_coverage_code(testfile, coverage): if not coverage: return with open(testfile, 'r') as file_p: content = file_p.read() with open(testfile, 'w') as file_p: file_p.write(JS_COVERAGE_CODE.format( folder=JS_COVERAGE_FOLDER, file=fs.basename(testfile))) file_p.write(content) # Remove coverage source from the appropriate test. def remove_coverage_code(testfile, coverage): if not coverage: return with open(testfile, 'r') as file_p: content = file_p.read() index = content.find('/* Copyright') with open(testfile, 'w') as file_p: file_p.write(content[index:]) class Reporter(object): @staticmethod def message(msg="", color=Terminal.empty): print("%s%s%s" % (color, msg, Terminal.empty)) @staticmethod def report_testset(testset): Reporter.message() Reporter.message("Testset: %s" % testset, Terminal.blue) @staticmethod def report_pass(test, time): Reporter.message(" PASS: %s (%ss)" % (test, time), Terminal.green) @staticmethod def report_fail(test, time): Reporter.message(" FAIL: %s (%ss)" % (test, time), Terminal.red) @staticmethod def report_timeout(test): Reporter.message(" TIMEOUT: %s" % test, Terminal.red) @staticmethod def report_skip(test, reason): skip_message = " SKIP: %s" % test if reason: skip_message += " (Reason: %s)" % reason Reporter.message(skip_message, Terminal.yellow) @staticmethod def report_configuration(testrunner): Reporter.message() Reporter.message("Test configuration:") Reporter.message(" iotjs: %s" % testrunner.iotjs) Reporter.message(" quiet: %s" % testrunner.quiet) Reporter.message(" timeout: %d sec" % testrunner.timeout) Reporter.message(" valgrind: %s" % testrunner.valgrind) Reporter.message(" skip-modules: %s" % testrunner.skip_modules) @staticmethod def report_final(results): Reporter.message() Reporter.message("Finished with all tests:", Terminal.blue) Reporter.message(" PASS: %d" % results["pass"], Terminal.green) Reporter.message(" FAIL: %d" % results["fail"], Terminal.red) Reporter.message(" TIMEOUT: %d" % results["timeout"], Terminal.red) Reporter.message(" SKIP: %d" % results["skip"], Terminal.yellow) class TestRunner(object): def __init__(self, options): self._process_pool = multiprocessing.Pool(processes=1) self.iotjs = fs.abspath(options.iotjs) self.quiet = options.quiet self.platform = options.platform self.timeout = options.timeout self.valgrind = options.valgrind self.coverage = options.coverage self.skip_modules = [] self.results = {} self._msg_queue = multiprocessing.Queue(1) if options.skip_modules: self.skip_modules = options.skip_modules.split(",") # Process the iotjs build information. iotjs_output = Executor.check_run_cmd_output(self.iotjs, [path.BUILD_INFO_PATH]) build_info = json.loads(iotjs_output) self.builtins = set(build_info["builtins"]) self.features = set(build_info["features"]) self.stability = build_info["stability"] self.debug = build_info["debug"] self.arch = build_info["arch"] if "napi" in self.builtins: self.build_napi_test_module() def build_napi_test_module(self): node_gyp = fs.join(path.PROJECT_ROOT, 'node_modules', '.bin', 'node-gyp') print('==> Build N-API test module with node-gyp\n') project_root = fs.join(path.PROJECT_ROOT, 'test', 'napi') cmd = ['--debug'] if self.debug else ['--release'] if self.platform == 'windows': node_gyp += '.cmd' cmd.append('--arch=x64' if self.arch == 'x64' else '--arch=ia32') Executor.check_run_cmd(node_gyp, ['rebuild'] + cmd, cwd=project_root) def run(self): Reporter.report_configuration(self) self.results = { "pass": 0, "fail": 0, "skip": 0, "timeout": 0 } with open(fs.join(path.TEST_ROOT, "testsets.json")) as testsets_file: testsets = json.load(testsets_file, object_pairs_hook=OrderedDict) for testset, tests in testsets.items(): self.run_testset(testset, tests) Reporter.report_final(self.results) def run_testset(self, testset, tests): Reporter.report_testset(testset) for test in tests: testfile = fs.join(path.TEST_ROOT, testset, test["name"]) timeout = test.get("timeout", self.timeout) if self.skip_test(test): Reporter.report_skip(test["name"], test.get("reason")) self.results["skip"] += 1 continue append_coverage_code(testfile, self.coverage) exitcode, output, runtime = self.run_test(testfile, timeout) expected_failure = test.get("expected-failure", False) remove_coverage_code(testfile, self.coverage) # Timeout happened. if exitcode == -1: Reporter.report_timeout(test["name"]) self.results["timeout"] += 1 continue # Show the output. if not self.quiet and output: print(output.decode("utf8"), end="") is_normal_run = (not expected_failure and exitcode == 0) is_expected_fail = (expected_failure and exitcode in [1, 2]) if is_normal_run or is_expected_fail: Reporter.report_pass(test["name"], runtime) self.results["pass"] += 1 else: Reporter.report_fail(test["name"], runtime) self.results["fail"] += 1 def run_test(self, testfile, timeout): command = [self.iotjs, testfile] if self.valgrind: valgrind_options = [ "--leak-check=full", "--error-exitcode=5", "--undef-value-errors=no" ] command = ["valgrind"] + valgrind_options + command try: process = multiprocessing.Process(target=run_subprocess, args=(self._msg_queue, command)) start = time.time() process.start() process.join(timeout) runtime = round((time.time() - start), 2) if process.is_alive(): raise multiprocessing.TimeoutError("Test still running") # At this point the queue must have data! # If not then it is also a timeout event exitcode, stdout = self._msg_queue.get_nowait() except (multiprocessing.TimeoutError, queue.Full): process.terminate() return -1, None, None return exitcode, stdout, runtime def skip_test(self, test): skip_list = set(test.get("skip", [])) # Skip by the `skip` attribute in testsets.json file. for i in ["all", self.platform, self.stability]: if i in skip_list: return True required_modules = set(test.get("required-modules", [])) required_features = set(test.get("required-features", [])) unsupported_modules = required_modules - self.builtins unsupported_features = required_features - self.features skipped_modules = required_modules.intersection(skip_list) # Skip the test if the tested module requires a module # which is not compiled into the binary if unsupported_modules: test["reason"] = "Required module(s) unsupported by iotjs build: " test["reason"] += ', '.join(sorted(unsupported_modules)) return True # Skip the test if it requires a module that is skipped by the # testrunner if skipped_modules: test["reason"] = "Required module(s) skipped by testrunner: " test["reason"] += ', '.join(sorted(skipped_modules)) return True # Skip the test if it uses features which are # unavailable in the current iotjs build if unsupported_features: test["reason"] = "Required feature(s) unsupported by iotjs build: " test["reason"] += ', '.join(sorted(unsupported_features)) return True return False def run_subprocess(parent_queue, command): process = subprocess.Popen(args=command, cwd=path.TEST_ROOT, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = process.communicate()[0] exitcode = process.returncode parent_queue.put_nowait([exitcode, stdout]) def get_args(): parser = argparse.ArgumentParser() parser.add_argument("iotjs", action="store", help="path to the iotjs binary file") parser.add_argument('--platform', default=Platform().os(), help='Specify the platform (default: %(default)s)') parser.add_argument("--quiet", action="store_true", default=False, help="show or hide the output of the tests") parser.add_argument("--skip-modules", action="store", metavar='list', help="module list to skip test of specific modules") parser.add_argument("--timeout", action="store", default=300, type=int, help="default timeout for the tests in seconds") parser.add_argument("--valgrind", action="store_true", default=False, help="check tests with Valgrind") parser.add_argument("--coverage", action="store_true", default=False, help="measure JavaScript coverage") return parser.parse_args() def main(): options = get_args() testrunner = TestRunner(options) testrunner.run() if testrunner.results["fail"]: sys.exit(1) if __name__ == "__main__": main() iotjs-1.0+715/tools/travis_script.py000077500000000000000000000224441371177304000174340ustar00rootroot00000000000000#!/usr/bin/env python # 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. import os from common_py.system.filesystem import FileSystem as fs from common_py.system.executor import Executor as ex from common_py.system.sys_platform import Platform from check_tidy import check_tidy platform = Platform() DOCKER_ROOT_PATH = fs.join('/root') # IoT.js path in travis TRAVIS_BUILD_PATH = fs.join(os.environ['TRAVIS_BUILD_DIR']) # IoT.js path in docker DOCKER_IOTJS_PATH = fs.join(DOCKER_ROOT_PATH, 'work_space/iotjs') # Node server path in docker DOCKER_NODE_SERVER_PATH = fs.join(DOCKER_ROOT_PATH, 'work_space/node_server') DOCKER_TIZENRT_PATH = fs.join(DOCKER_ROOT_PATH, 'TizenRT') DOCKER_TIZENRT_OS_PATH = fs.join(DOCKER_TIZENRT_PATH, 'os') DOCKER_TIZENRT_OS_TOOLS_PATH = fs.join(DOCKER_TIZENRT_OS_PATH, 'tools') DOCKER_NUTTX_PATH = fs.join(DOCKER_ROOT_PATH, 'nuttx') DOCKER_NUTTX_TOOLS_PATH = fs.join(DOCKER_NUTTX_PATH, 'tools') DOCKER_NUTTX_APPS_PATH = fs.join(DOCKER_ROOT_PATH, 'apps') DOCKER_NAME = 'iotjs_docker' DOCKER_TAG = 'iotjs/ubuntu:0.10' BUILDTYPES = ['debug', 'release'] TIZENRT_TAG = '2.0_Public_M2' # Common buildoptions for sanitizer jobs. BUILDOPTIONS_SANITIZER = [ '--buildtype=debug', '--clean', '--compile-flag=-fno-common', '--compile-flag=-fno-omit-frame-pointer', '--jerry-cmake-param=-DJERRY_SYSTEM_ALLOCATOR=ON', '--no-check-valgrind', '--no-snapshot', '--profile=test/profiles/host-linux.profile', '--run-test=full', '--target-arch=i686' ] def start_container(): run_docker() start_mosquitto_server() start_node_server() def run_docker(): ex.check_run_cmd('docker', ['pull', DOCKER_TAG]) ex.check_run_cmd('docker', ['run', '-dit', '--privileged', '--name', DOCKER_NAME, '-v', '%s:%s' % (TRAVIS_BUILD_PATH, DOCKER_IOTJS_PATH), '--add-host', 'test.mosquitto.org:127.0.0.1', '--add-host', 'echo.websocket.org:127.0.0.1', '--add-host', 'httpbin.org:127.0.0.1', DOCKER_TAG]) def exec_docker(cwd, cmd, env=[], is_background=False): exec_cmd = 'cd %s && ' % cwd + ' '.join(cmd) if is_background: docker_args = ['exec', '-dit'] else: docker_args = ['exec', '-it'] for e in env: docker_args.append('-e') docker_args.append(e) docker_args += [DOCKER_NAME, 'bash', '-c', exec_cmd] ex.check_run_cmd('docker', docker_args) def start_mosquitto_server(): exec_docker(DOCKER_ROOT_PATH, ['mosquitto', '-d']) def start_node_server(): exec_docker(DOCKER_NODE_SERVER_PATH, ['node', 'server.js'], [], True) def set_config_tizenrt(buildtype): exec_docker(DOCKER_ROOT_PATH, [ 'cp', fs.join(DOCKER_IOTJS_PATH, 'config/tizenrt/artik05x/configs/', buildtype, 'defconfig'), fs.join(DOCKER_TIZENRT_OS_PATH, '.config')]) def build_iotjs(buildtype, args=[], env=[]): exec_docker(DOCKER_IOTJS_PATH, [ './tools/build.py', '--clean', '--buildtype=' + buildtype] + args, env) JOBS = dict() class job(object): def __init__(self, name): self.name = name def __call__(self, fn): JOBS[self.name] = fn @job('host-linux') def job_host_linux(): start_container() for buildtype in BUILDTYPES: build_iotjs(buildtype, [ '--cmake-param=-DENABLE_MODULE_ASSERT=ON', '--run-test=full', '--profile=profiles/minimal.profile']) for buildtype in BUILDTYPES: build_iotjs(buildtype, [ '--run-test=full', '--profile=test/profiles/host-linux.profile']) @job('n-api') def job_n_api(): start_container() # N-API should work with both ES5.1 and ES2015-subset JerryScript profiles for buildtype in BUILDTYPES: build_iotjs(buildtype, [ '--run-test=full', '--n-api']) for buildtype in BUILDTYPES: build_iotjs(buildtype, [ '--run-test=full', '--n-api', '--jerry-profile=es2015-subset']) @job('mock-linux') def job_mock_linux(): start_container() for buildtype in BUILDTYPES: build_iotjs(buildtype, [ '--run-test=full', '--target-os=mock', '--profile=test/profiles/mock-linux.profile']) @job('rpi2') def job_rpi2(): start_container() for buildtype in BUILDTYPES: build_iotjs(buildtype, [ '--target-arch=arm', '--target-board=rpi2', '--profile=test/profiles/rpi2-linux.profile']) @job('stm32f4dis') def job_stm32f4dis(): start_container() # Copy the application files to apps/system/iotjs. exec_docker(DOCKER_ROOT_PATH, [ 'cp', '-r', fs.join(DOCKER_IOTJS_PATH,'config/nuttx/stm32f4dis/app/'), fs.join(DOCKER_NUTTX_APPS_PATH, 'system/iotjs/')]) exec_docker(DOCKER_ROOT_PATH, [ 'cp', '-r', fs.join(DOCKER_IOTJS_PATH, 'config/nuttx/stm32f4dis/config.travis'), fs.join(DOCKER_NUTTX_PATH, 'configs/stm32f4discovery/usbnsh/defconfig')]) for buildtype in BUILDTYPES: exec_docker(DOCKER_NUTTX_PATH, ['make', 'distclean']) exec_docker(DOCKER_NUTTX_TOOLS_PATH, ['./configure.sh', 'stm32f4discovery/usbnsh']) exec_docker(DOCKER_NUTTX_PATH, ['make', 'clean']) exec_docker(DOCKER_NUTTX_PATH, ['make', 'context']) # Build IoT.js build_iotjs(buildtype, [ '--target-arch=arm', '--target-os=nuttx', '--nuttx-home=' + DOCKER_NUTTX_PATH, '--target-board=stm32f4dis', '--jerry-heaplimit=78', '--profile=test/profiles/nuttx.profile']) # Build Nuttx if buildtype == "release": rflag = 'R=1' else: rflag = 'R=0' exec_docker(DOCKER_NUTTX_PATH, [ 'make', 'all', 'IOTJS_ROOT_DIR=' + DOCKER_IOTJS_PATH, rflag]) @job('tizen') def job_tizen(): start_container() for buildtype in BUILDTYPES: if buildtype == "debug": exec_docker(DOCKER_IOTJS_PATH, [ 'config/tizen/gbsbuild.sh', '--debug', '--clean']) else: exec_docker(DOCKER_IOTJS_PATH, ['config/tizen/gbsbuild.sh', '--clean']) @job('misc') def job_misc(): ex.check_run_cmd('tools/check_signed_off.sh', ['--travis']) ex.check_run_cmd('tools/check_tidy.py') @job('external-modules') def job_external_modules(): start_container() for buildtype in BUILDTYPES: build_iotjs(buildtype, [ '--run-test=full', '--profile=test/profiles/host-linux.profile', '--external-modules=test/external_modules/' 'mymodule1,test/external_modules/mymodule2', '--cmake-param=-DENABLE_MODULE_MYMODULE1=ON', '--cmake-param=-DENABLE_MODULE_MYMODULE2=ON']) @job('es2015') def job_es2015(): start_container() for buildtype in BUILDTYPES: build_iotjs(buildtype, [ '--run-test=full', '--jerry-profile=es2015-subset']) @job('no-snapshot') def job_no_snapshot(): start_container() for buildtype in BUILDTYPES: build_iotjs(buildtype, ['--run-test=full', '--no-snapshot', '--jerry-lto']) @job('host-darwin') def job_host_darwin(): for buildtype in BUILDTYPES: ex.check_run_cmd('./tools/build.py', [ '--run-test=full', '--buildtype=' + buildtype, '--clean', '--profile=test/profiles/host-darwin.profile']) @job('asan') def job_asan(): start_container() build_iotjs('debug', [ '--compile-flag=-fsanitize=address', '--compile-flag=-O2' ] + BUILDOPTIONS_SANITIZER, ['ASAN_OPTIONS=detect_stack_use_after_return=1:' 'check_initialization_order=true:strict_init_order=true', 'TIMEOUT=600']) @job('ubsan') def job_ubsan(): start_container() build_iotjs('debug', [ '--compile-flag=-fsanitize=undefined' ] + BUILDOPTIONS_SANITIZER, ['UBSAN_OPTIONS=print_stacktrace=1', 'TIMEOUT=600']) @job('coverity') def job_coverity(): ex.check_run_cmd('./tools/build.py', ['--clean']) if __name__ == '__main__': JOBS[os.getenv('OPTS')]() pax_global_header00006660000000000000000000000064133506605510014516gustar00rootroot0000000000000052 comment=f8f84b34db144ce54682333b360cbca3259b9536 iotjs-1.0+715/deps/http-parser/000077500000000000000000000000001335066055100162225ustar00rootroot00000000000000iotjs-1.0+715/deps/http-parser/.gitignore000066400000000000000000000003611335066055100202120ustar00rootroot00000000000000/out/ core tags *.o test test_g test_fast bench url_parser parsertrace parsertrace_g *.mk *.Makefile *.so.* *.a # Visual Studio uglies *.suo *.sln *.vcxproj *.vcxproj.filters *.vcxproj.user *.opensdf *.ncrunchsolution* *.sdf *.vsp *.psess iotjs-1.0+715/deps/http-parser/.mailmap000066400000000000000000000007401335066055100176440ustar00rootroot00000000000000# update AUTHORS with: # git log --all --reverse --format='%aN <%aE>' | perl -ne 'BEGIN{print "# Authors ordered by first contribution.\n"} print unless $h{$_}; $h{$_} = 1' > AUTHORS Ryan Dahl Salman Haq Simon Zimmermann Thomas LE ROUX LE ROUX Thomas Thomas LE ROUX Thomas LE ROUX Fedor Indutny iotjs-1.0+715/deps/http-parser/.travis.yml000066400000000000000000000002041335066055100203270ustar00rootroot00000000000000language: c compiler: - clang - gcc script: - "make" notifications: email: false irc: - "irc.freenode.net#node-ci" iotjs-1.0+715/deps/http-parser/AUTHORS000066400000000000000000000046441335066055100173020ustar00rootroot00000000000000# Authors ordered by first contribution. Ryan Dahl Jeremy Hinegardner Sergey Shepelev Joe Damato tomika Phoenix Sol Cliff Frey Ewen Cheslack-Postava Santiago Gala Tim Becker Jeff Terrace Ben Noordhuis Nathan Rajlich Mark Nottingham Aman Gupta Tim Becker Sean Cunningham Peter Griess Salman Haq Cliff Frey Jon Kolb Fouad Mardini Paul Querna Felix Geisendörfer koichik Andre Caron Ivo Raisr James McLaughlin David Gwynne Thomas LE ROUX Randy Rizun Andre Louis Caron Simon Zimmermann Erik Dubbelboer Martell Malone Bertrand Paquet BogDan Vatra Peter Faiman Corey Richardson Tóth Tamás Cam Swords Chris Dickinson Uli Köhler Charlie Somerville Patrik Stutz Fedor Indutny runner Alexis Campailla David Wragg Vinnie Falco Alex Butum Rex Feng Alex Kocharin Mark Koopman Helge Heß Alexis La Goutte George Miroshnykov Maciej MaÅ‚ecki Marc O'Morain Jeff Pinner Timothy J Fontaine Akagi201 Romain Giraud Jay Satiro Arne Steen Kjell Schubert iotjs-1.0+715/deps/http-parser/CMakeLists.txt000066400000000000000000000021231335066055100207600ustar00rootroot00000000000000cmake_minimum_required(VERSION 2.8) PROJECT(http-parser C) set(targetName httpparser) INCLUDE_DIRECTORIES(./) if("${OS}" MATCHES "NUTTX|TIZENRT") set(TARGET_INCLUDE "${NUTTX_HOME}/include") set(TARGET_INCLUDE ${TARGET_INCLUDE} "${NUTTX_HOME}/include/cxx") INCLUDE_DIRECTORIES(./ ${TARGET_INCLUDE}) endif() if("${CMAKE_BUILD_TYPE}" MATCHES "Release|MinSizeRel") # If we are building for release modify it to MinSizeRel for -Os option. set(CMAKE_BUILD_TYPE "MinSizeRel") else() # Any other case just assume debug build. set(CMAKE_BUILD_TYPE "Debug") endif() message("HTTP Parser configured with:") message(STATUS "CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE}") message(STATUS "OS ${OS}") message(STATUS "NUTTX_HOME ${NUTTX_HOME}") message(STATUS "ENABLE_MEMORY_CONSTRAINTS ${ENABLE_MEMORY_CONSTRAINTS}") if(ENABLE_MEMORY_CONSTRAINTS) set(DEFINES_HTTPPARSER ${DEFINES_HTTPPARSER} HTTPPARSER_ENABLE_MEMORY_CONSTRAINTS) endif() ADD_LIBRARY(${targetName} STATIC http_parser.c) target_compile_definitions(${targetName} PRIVATE ${DEFINES_HTTPPARSER}) iotjs-1.0+715/deps/http-parser/LICENSE-MIT000066400000000000000000000023431335066055100176600ustar00rootroot00000000000000http_parser.c is based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev. Additional changes are licensed under the same terms as NGINX and copyright Joyent, Inc. and other Node 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. iotjs-1.0+715/deps/http-parser/Makefile000066400000000000000000000110051335066055100176570ustar00rootroot00000000000000# Copyright Joyent, Inc. and other Node 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. PLATFORM ?= $(shell sh -c 'uname -s | tr "[A-Z]" "[a-z]"') ifeq (darwin,$(PLATFORM)) SONAME ?= libhttp_parser.2.5.0.dylib SOEXT ?= dylib else SONAME ?= libhttp_parser.so.2.5.0 SOEXT ?= so endif CC?=gcc AR?=ar CPPFLAGS ?= LDFLAGS ?= CPPFLAGS += -I. CPPFLAGS_DEBUG = $(CPPFLAGS) -DHTTP_PARSER_STRICT=1 CPPFLAGS_DEBUG += $(CPPFLAGS_DEBUG_EXTRA) CPPFLAGS_FAST = $(CPPFLAGS) -DHTTP_PARSER_STRICT=0 CPPFLAGS_FAST += $(CPPFLAGS_FAST_EXTRA) CPPFLAGS_BENCH = $(CPPFLAGS_FAST) CFLAGS += -Wall -Wextra -Werror CFLAGS_DEBUG = $(CFLAGS) -O0 -g $(CFLAGS_DEBUG_EXTRA) CFLAGS_FAST = $(CFLAGS) -O3 $(CFLAGS_FAST_EXTRA) CFLAGS_BENCH = $(CFLAGS_FAST) -Wno-unused-parameter CFLAGS_LIB = $(CFLAGS_FAST) -fPIC LDFLAGS_LIB = $(LDFLAGS) -shared INSTALL ?= install PREFIX ?= $(DESTDIR)/usr/local LIBDIR = $(PREFIX)/lib INCLUDEDIR = $(PREFIX)/include ifneq (darwin,$(PLATFORM)) # TODO(bnoordhuis) The native SunOS linker expects -h rather than -soname... LDFLAGS_LIB += -Wl,-soname=$(SONAME) endif test: test_g test_fast ./test_g ./test_fast test_g: http_parser_g.o test_g.o $(CC) $(CFLAGS_DEBUG) $(LDFLAGS) http_parser_g.o test_g.o -o $@ test_g.o: test.c http_parser.h Makefile $(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) -c test.c -o $@ http_parser_g.o: http_parser.c http_parser.h Makefile $(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) -c http_parser.c -o $@ test_fast: http_parser.o test.o http_parser.h $(CC) $(CFLAGS_FAST) $(LDFLAGS) http_parser.o test.o -o $@ test.o: test.c http_parser.h Makefile $(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) -c test.c -o $@ bench: http_parser.o bench.o $(CC) $(CFLAGS_BENCH) $(LDFLAGS) http_parser.o bench.o -o $@ bench.o: bench.c http_parser.h Makefile $(CC) $(CPPFLAGS_BENCH) $(CFLAGS_BENCH) -c bench.c -o $@ http_parser.o: http_parser.c http_parser.h Makefile $(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) -c http_parser.c test-run-timed: test_fast while(true) do time ./test_fast > /dev/null; done test-valgrind: test_g valgrind ./test_g libhttp_parser.o: http_parser.c http_parser.h Makefile $(CC) $(CPPFLAGS_FAST) $(CFLAGS_LIB) -c http_parser.c -o libhttp_parser.o library: libhttp_parser.o $(CC) $(LDFLAGS_LIB) -o $(SONAME) $< package: http_parser.o $(AR) rcs libhttp_parser.a http_parser.o url_parser: http_parser.o contrib/url_parser.c $(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) $^ -o $@ url_parser_g: http_parser_g.o contrib/url_parser.c $(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) $^ -o $@ parsertrace: http_parser.o contrib/parsertrace.c $(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) $^ -o parsertrace parsertrace_g: http_parser_g.o contrib/parsertrace.c $(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) $^ -o parsertrace_g tags: http_parser.c http_parser.h test.c ctags $^ install: library $(INSTALL) -D http_parser.h $(INCLUDEDIR)/http_parser.h $(INSTALL) -D $(SONAME) $(LIBDIR)/$(SONAME) ln -s $(LIBDIR)/$(SONAME) $(LIBDIR)/libhttp_parser.$(SOEXT) install-strip: library $(INSTALL) -D http_parser.h $(INCLUDEDIR)/http_parser.h $(INSTALL) -D -s $(SONAME) $(LIBDIR)/$(SONAME) ln -s $(LIBDIR)/$(SONAME) $(LIBDIR)/libhttp_parser.$(SOEXT) uninstall: rm $(INCLUDEDIR)/http_parser.h rm $(LIBDIR)/$(SONAME) rm $(LIBDIR)/libhttp_parser.so clean: rm -f *.o *.a tags test test_fast test_g \ http_parser.tar libhttp_parser.so.* \ url_parser url_parser_g parsertrace parsertrace_g contrib/url_parser.c: http_parser.h contrib/parsertrace.c: http_parser.h .PHONY: clean package test-run test-run-timed test-valgrind install install-strip uninstall iotjs-1.0+715/deps/http-parser/README.md000066400000000000000000000163311335066055100175050ustar00rootroot00000000000000HTTP Parser =========== [![Build Status](https://travis-ci.org/joyent/http-parser.png?branch=master)](https://travis-ci.org/joyent/http-parser) This is a parser for HTTP messages written in C. It parses both requests and responses. The parser is designed to be used in performance HTTP applications. It does not make any syscalls nor allocations, it does not buffer data, it can be interrupted at anytime. Depending on your architecture, it only requires about 40 bytes of data per message stream (in a web server that is per connection). Features: * No dependencies * Handles persistent streams (keep-alive). * Decodes chunked encoding. * Upgrade support * Defends against buffer overflow attacks. The parser extracts the following information from HTTP messages: * Header fields and values * Content-Length * Request method * Response status code * Transfer-Encoding * HTTP version * Request URL * Message body Usage ----- One `http_parser` object is used per TCP connection. Initialize the struct using `http_parser_init()` and set the callbacks. That might look something like this for a request parser: ```c http_parser_settings settings; settings.on_url = my_url_callback; settings.on_header_field = my_header_field_callback; /* ... */ http_parser *parser = malloc(sizeof(http_parser)); http_parser_init(parser, HTTP_REQUEST); parser->data = my_socket; ``` When data is received on the socket execute the parser and check for errors. ```c size_t len = 80*1024, nparsed; char buf[len]; ssize_t recved; recved = recv(fd, buf, len, 0); if (recved < 0) { /* Handle error. */ } /* Start up / continue the parser. * Note we pass recved==0 to signal that EOF has been received. */ nparsed = http_parser_execute(parser, &settings, buf, recved); if (parser->upgrade) { /* handle new protocol */ } else if (nparsed != recved) { /* Handle error. Usually just close the connection. */ } ``` HTTP needs to know where the end of the stream is. For example, sometimes servers send responses without Content-Length and expect the client to consume input (for the body) until EOF. To tell http_parser about EOF, give `0` as the fourth parameter to `http_parser_execute()`. Callbacks and errors can still be encountered during an EOF, so one must still be prepared to receive them. Scalar valued message information such as `status_code`, `method`, and the HTTP version are stored in the parser structure. This data is only temporally stored in `http_parser` and gets reset on each new message. If this information is needed later, copy it out of the structure during the `headers_complete` callback. The parser decodes the transfer-encoding for both requests and responses transparently. That is, a chunked encoding is decoded before being sent to the on_body callback. The Special Problem of Upgrade ------------------------------ HTTP supports upgrading the connection to a different protocol. An increasingly common example of this is the Web Socket protocol which sends a request like GET /demo HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: example.com Origin: http://example.com WebSocket-Protocol: sample followed by non-HTTP data. (See http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 for more information the Web Socket protocol.) To support this, the parser will treat this as a normal HTTP message without a body, issuing both on_headers_complete and on_message_complete callbacks. However http_parser_execute() will stop parsing at the end of the headers and return. The user is expected to check if `parser->upgrade` has been set to 1 after `http_parser_execute()` returns. Non-HTTP data begins at the buffer supplied offset by the return value of `http_parser_execute()`. Callbacks --------- During the `http_parser_execute()` call, the callbacks set in `http_parser_settings` will be executed. The parser maintains state and never looks behind, so buffering the data is not necessary. If you need to save certain data for later usage, you can do that from the callbacks. There are two types of callbacks: * notification `typedef int (*http_cb) (http_parser*);` Callbacks: on_message_begin, on_headers_complete, on_message_complete. * data `typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);` Callbacks: (requests only) on_url, (common) on_header_field, on_header_value, on_body; Callbacks must return 0 on success. Returning a non-zero value indicates error to the parser, making it exit immediately. In case you parse HTTP message in chunks (i.e. `read()` request line from socket, parse, read half headers, parse, etc) your data callbacks may be called more than once. Http-parser guarantees that data pointer is only valid for the lifetime of callback. You can also `read()` into a heap allocated buffer to avoid copying memory around if this fits your application. Reading headers may be a tricky task if you read/parse headers partially. Basically, you need to remember whether last header callback was field or value and apply the following logic: (on_header_field and on_header_value shortened to on_h_*) ------------------------ ------------ -------------------------------------------- | State (prev. callback) | Callback | Description/action | ------------------------ ------------ -------------------------------------------- | nothing (first call) | on_h_field | Allocate new buffer and copy callback data | | | | into it | ------------------------ ------------ -------------------------------------------- | value | on_h_field | New header started. | | | | Copy current name,value buffers to headers | | | | list and allocate new buffer for new name | ------------------------ ------------ -------------------------------------------- | field | on_h_field | Previous name continues. Reallocate name | | | | buffer and append callback data to it | ------------------------ ------------ -------------------------------------------- | field | on_h_value | Value for current header started. Allocate | | | | new buffer and copy callback data to it | ------------------------ ------------ -------------------------------------------- | value | on_h_value | Value continues. Reallocate value buffer | | | | and append callback data to it | ------------------------ ------------ -------------------------------------------- Parsing URLs ------------ A simplistic zero-copy URL parser is provided as `http_parser_parse_url()`. Users of this library may wish to use it to parse URLs constructed from consecutive `on_url` callbacks. See examples of reading in headers: * [partial example](http://gist.github.com/155877) in C * [from http-parser tests](http://github.com/joyent/http-parser/blob/37a0ff8/test.c#L403) in C * [from Node library](http://github.com/joyent/node/blob/842eaf4/src/http.js#L284) in Javascript iotjs-1.0+715/deps/http-parser/bench.c000066400000000000000000000065101335066055100174470ustar00rootroot00000000000000/* Copyright Fedor Indutny. 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. */ #include "http_parser.h" #include #include #include #include static const char data[] = "POST /joyent/http-parser HTTP/1.1\r\n" "Host: github.com\r\n" "DNT: 1\r\n" "Accept-Encoding: gzip, deflate, sdch\r\n" "Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4\r\n" "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/39.0.2171.65 Safari/537.36\r\n" "Accept: text/html,application/xhtml+xml,application/xml;q=0.9," "image/webp,*/*;q=0.8\r\n" "Referer: https://github.com/joyent/http-parser\r\n" "Connection: keep-alive\r\n" "Transfer-Encoding: chunked\r\n" "Cache-Control: max-age=0\r\n\r\nb\r\nhello world\r\n0\r\n\r\n"; static const size_t data_len = sizeof(data) - 1; static int on_info(http_parser* p) { return 0; } static int on_data(http_parser* p, const char *at, size_t length) { return 0; } static http_parser_settings settings = { .on_message_begin = on_info, .on_headers_complete = on_info, .on_message_complete = on_info, .on_header_field = on_data, .on_header_value = on_data, .on_url = on_data, .on_status = on_data, .on_body = on_data }; int bench(int iter_count, int silent) { struct http_parser parser; int i; int err; struct timeval start; struct timeval end; float rps; if (!silent) { err = gettimeofday(&start, NULL); assert(err == 0); } for (i = 0; i < iter_count; i++) { size_t parsed; http_parser_init(&parser, HTTP_REQUEST); parsed = http_parser_execute(&parser, &settings, data, data_len); assert(parsed == data_len); } if (!silent) { err = gettimeofday(&end, NULL); assert(err == 0); fprintf(stdout, "Benchmark result:\n"); rps = (float) (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) * 1e-6f; fprintf(stdout, "Took %f seconds to run\n", rps); rps = (float) iter_count / rps; fprintf(stdout, "%f req/sec\n", rps); fflush(stdout); } return 0; } int main(int argc, char** argv) { if (argc == 2 && strcmp(argv[1], "infinite") == 0) { for (;;) bench(5000000, 1); return 0; } else { return bench(5000000, 0); } } iotjs-1.0+715/deps/http-parser/contrib/000077500000000000000000000000001335066055100176625ustar00rootroot00000000000000iotjs-1.0+715/deps/http-parser/contrib/parsertrace.c000066400000000000000000000104001335066055100223340ustar00rootroot00000000000000/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev * * Additional changes are licensed under the same terms as NGINX and * copyright Joyent, Inc. and other Node 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. */ /* Dump what the parser finds to stdout as it happen */ #include "http_parser.h" #include #include #include int on_message_begin(http_parser* _) { (void)_; printf("\n***MESSAGE BEGIN***\n\n"); return 0; } int on_headers_complete(http_parser* _) { (void)_; printf("\n***HEADERS COMPLETE***\n\n"); return 0; } int on_message_complete(http_parser* _) { (void)_; printf("\n***MESSAGE COMPLETE***\n\n"); return 0; } int on_url(http_parser* _, const char* at, size_t length) { (void)_; printf("Url: %.*s\n", (int)length, at); return 0; } int on_header_field(http_parser* _, const char* at, size_t length) { (void)_; printf("Header field: %.*s\n", (int)length, at); return 0; } int on_header_value(http_parser* _, const char* at, size_t length) { (void)_; printf("Header value: %.*s\n", (int)length, at); return 0; } int on_body(http_parser* _, const char* at, size_t length) { (void)_; printf("Body: %.*s\n", (int)length, at); return 0; } void usage(const char* name) { fprintf(stderr, "Usage: %s $type $filename\n" " type: -x, where x is one of {r,b,q}\n" " parses file as a Response, reQuest, or Both\n", name); exit(EXIT_FAILURE); } int main(int argc, char* argv[]) { enum http_parser_type file_type; if (argc != 3) { usage(argv[0]); } char* type = argv[1]; if (type[0] != '-') { usage(argv[0]); } switch (type[1]) { /* in the case of "-", type[1] will be NUL */ case 'r': file_type = HTTP_RESPONSE; break; case 'q': file_type = HTTP_REQUEST; break; case 'b': file_type = HTTP_BOTH; break; default: usage(argv[0]); } char* filename = argv[2]; FILE* file = fopen(filename, "r"); if (file == NULL) { perror("fopen"); goto fail; } fseek(file, 0, SEEK_END); long file_length = ftell(file); if (file_length == -1) { perror("ftell"); goto fail; } fseek(file, 0, SEEK_SET); char* data = malloc(file_length); if (fread(data, 1, file_length, file) != (size_t)file_length) { fprintf(stderr, "couldn't read entire file\n"); free(data); goto fail; } http_parser_settings settings; memset(&settings, 0, sizeof(settings)); settings.on_message_begin = on_message_begin; settings.on_url = on_url; settings.on_header_field = on_header_field; settings.on_header_value = on_header_value; settings.on_headers_complete = on_headers_complete; settings.on_body = on_body; settings.on_message_complete = on_message_complete; http_parser parser; http_parser_init(&parser, file_type); size_t nparsed = http_parser_execute(&parser, &settings, data, file_length); free(data); if (nparsed != (size_t)file_length) { fprintf(stderr, "Error: %s (%s)\n", http_errno_description(HTTP_PARSER_ERRNO(&parser)), http_errno_name(HTTP_PARSER_ERRNO(&parser))); goto fail; } return EXIT_SUCCESS; fail: fclose(file); return EXIT_FAILURE; } iotjs-1.0+715/deps/http-parser/contrib/url_parser.c000066400000000000000000000021421335066055100222030ustar00rootroot00000000000000#include "http_parser.h" #include #include void dump_url (const char *url, const struct http_parser_url *u) { unsigned int i; printf("\tfield_set: 0x%x, port: %u\n", u->field_set, u->port); for (i = 0; i < UF_MAX; i++) { if ((u->field_set & (1 << i)) == 0) { printf("\tfield_data[%u]: unset\n", i); continue; } printf("\tfield_data[%u]: off: %u, len: %u, part: %.*s\n", i, u->field_data[i].off, u->field_data[i].len, u->field_data[i].len, url + u->field_data[i].off); } } int main(int argc, char ** argv) { struct http_parser_url u; int len, connect, result; if (argc != 3) { printf("Syntax : %s connect|get url\n", argv[0]); return 1; } len = strlen(argv[2]); connect = strcmp("connect", argv[1]) == 0 ? 1 : 0; printf("Parsing %s, connect %d\n", argv[2], connect); result = http_parser_parse_url(argv[2], len, connect, &u); if (result != 0) { printf("Parse error : %d\n", result); return result; } printf("Parse ok, result : \n"); dump_url(argv[2], &u); return 0; }iotjs-1.0+715/deps/http-parser/http_parser.c000066400000000000000000002117671335066055100207370ustar00rootroot00000000000000/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev * * Additional changes are licensed under the same terms as NGINX and * copyright Joyent, Inc. and other Node 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. */ #include "http_parser.h" #include #include #include #include #include #include #ifndef ULLONG_MAX # define ULLONG_MAX ((uint64_t) -1) /* 2^64-1 */ #endif #ifndef MIN # define MIN(a,b) ((a) < (b) ? (a) : (b)) #endif #ifndef ARRAY_SIZE # define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #endif #ifndef BIT_AT # define BIT_AT(a, i) \ (!!((unsigned int) (a)[(unsigned int) (i) >> 3] & \ (1 << ((unsigned int) (i) & 7)))) #endif #ifndef ELEM_AT # define ELEM_AT(a, i, v) ((unsigned int) (i) < ARRAY_SIZE(a) ? (a)[(i)] : (v)) #endif #define SET_ERRNO(e) \ do { \ parser->http_errno = (e); \ } while(0) #define CURRENT_STATE() p_state #define UPDATE_STATE(V) p_state = (enum state) (V); #define RETURN(V) \ do { \ parser->state = CURRENT_STATE(); \ return (V); \ } while (0); #define REEXECUTE() \ goto reexecute; \ #ifdef __GNUC__ # define LIKELY(X) __builtin_expect(!!(X), 1) # define UNLIKELY(X) __builtin_expect(!!(X), 0) #else # define LIKELY(X) (X) # define UNLIKELY(X) (X) #endif /* Run the notify callback FOR, returning ER if it fails */ #define CALLBACK_NOTIFY_(FOR, ER) \ do { \ assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ \ if (LIKELY(settings->on_##FOR)) { \ parser->state = CURRENT_STATE(); \ if (UNLIKELY(0 != settings->on_##FOR(parser))) { \ SET_ERRNO(HPE_CB_##FOR); \ } \ UPDATE_STATE(parser->state); \ \ /* We either errored above or got paused; get out */ \ if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \ return (ER); \ } \ } \ } while (0) /* Run the notify callback FOR and consume the current byte */ #define CALLBACK_NOTIFY(FOR) CALLBACK_NOTIFY_(FOR, p - data + 1) /* Run the notify callback FOR and don't consume the current byte */ #define CALLBACK_NOTIFY_NOADVANCE(FOR) CALLBACK_NOTIFY_(FOR, p - data) /* Run data callback FOR with LEN bytes, returning ER if it fails */ #define CALLBACK_DATA_(FOR, LEN, ER) \ do { \ assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ \ if (FOR##_mark) { \ if (LIKELY(settings->on_##FOR)) { \ parser->state = CURRENT_STATE(); \ if (UNLIKELY(0 != \ settings->on_##FOR(parser, FOR##_mark, (LEN)))) { \ SET_ERRNO(HPE_CB_##FOR); \ } \ UPDATE_STATE(parser->state); \ \ /* We either errored above or got paused; get out */ \ if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \ return (ER); \ } \ } \ FOR##_mark = NULL; \ } \ } while (0) /* Run the data callback FOR and consume the current byte */ #define CALLBACK_DATA(FOR) \ CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1) /* Run the data callback FOR and don't consume the current byte */ #define CALLBACK_DATA_NOADVANCE(FOR) \ CALLBACK_DATA_(FOR, p - FOR##_mark, p - data) /* Set the mark FOR; non-destructive if mark is already set */ #define MARK(FOR) \ do { \ if (!FOR##_mark) { \ FOR##_mark = p; \ } \ } while (0) /* Don't allow the total size of the HTTP headers (including the status * line) to exceed HTTP_MAX_HEADER_SIZE. This check is here to protect * embedders against denial-of-service attacks where the attacker feeds * us a never-ending header that the embedder keeps buffering. * * This check is arguably the responsibility of embedders but we're doing * it on the embedder's behalf because most won't bother and this way we * make the web a little safer. HTTP_MAX_HEADER_SIZE is still far bigger * than any reasonable request or response so this should never affect * day-to-day operation. */ #define COUNT_HEADER_SIZE(V) \ do { \ parser->nread += (V); \ if (UNLIKELY(parser->nread > (HTTP_MAX_HEADER_SIZE))) { \ SET_ERRNO(HPE_HEADER_OVERFLOW); \ goto error; \ } \ } while (0) #define PROXY_CONNECTION "proxy-connection" #define CONNECTION "connection" #define CONTENT_LENGTH "content-length" #define TRANSFER_ENCODING "transfer-encoding" #define UPGRADE "upgrade" #define CHUNKED "chunked" #define KEEP_ALIVE "keep-alive" #define CLOSE "close" static const char * const method_strings[] = { #define XX(num, name, string) #string, HTTP_METHOD_MAP(XX) #undef XX }; /* Tokens as defined by rfc 2616. Also lowercases them. * token = 1* * separators = "(" | ")" | "<" | ">" | "@" * | "," | ";" | ":" | "\" | <"> * | "/" | "[" | "]" | "?" | "=" * | "{" | "}" | SP | HT */ static const char tokens[256] = { /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ 0, 0, 0, 0, 0, 0, 0, 0, /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ 0, 0, 0, 0, 0, 0, 0, 0, /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ 0, 0, 0, 0, 0, 0, 0, 0, /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ 0, 0, 0, 0, 0, 0, 0, 0, /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ 0, '!', 0, '#', '$', '%', '&', '\'', /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ 0, 0, '*', '+', 0, '-', '.', 0, /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ '0', '1', '2', '3', '4', '5', '6', '7', /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ '8', '9', 0, 0, 0, 0, 0, 0, /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ 'x', 'y', 'z', 0, 0, 0, '^', '_', /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ 'x', 'y', 'z', 0, '|', 0, '~', 0 }; static const int8_t unhex[256] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; #if HTTP_PARSER_STRICT # define T(v) 0 #else # define T(v) v #endif static const uint8_t normal_url_char[32] = { /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ 0 | T(2) | 0 | 0 | T(16) | 0 | 0 | 0, /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ 0 | 2 | 4 | 0 | 16 | 32 | 64 | 128, /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, }; #undef T enum state { s_dead = 1 /* important that this is > 0 */ , s_start_req_or_res , s_res_or_resp_H , s_start_res , s_res_H , s_res_HT , s_res_HTT , s_res_HTTP , s_res_first_http_major , s_res_http_major , s_res_first_http_minor , s_res_http_minor , s_res_first_status_code , s_res_status_code , s_res_status_start , s_res_status , s_res_line_almost_done , s_start_req , s_req_method , s_req_spaces_before_url , s_req_schema , s_req_schema_slash , s_req_schema_slash_slash , s_req_server_start , s_req_server , s_req_server_with_at , s_req_path , s_req_query_string_start , s_req_query_string , s_req_fragment_start , s_req_fragment , s_req_http_start , s_req_http_H , s_req_http_HT , s_req_http_HTT , s_req_http_HTTP , s_req_first_http_major , s_req_http_major , s_req_first_http_minor , s_req_http_minor , s_req_line_almost_done , s_header_field_start , s_header_field , s_header_value_discard_ws , s_header_value_discard_ws_almost_done , s_header_value_discard_lws , s_header_value_start , s_header_value , s_header_value_lws , s_header_almost_done , s_chunk_size_start , s_chunk_size , s_chunk_parameters , s_chunk_size_almost_done , s_headers_almost_done , s_headers_done /* Important: 's_headers_done' must be the last 'header' state. All * states beyond this must be 'body' states. It is used for overflow * checking. See the PARSING_HEADER() macro. */ , s_chunk_data , s_chunk_data_almost_done , s_chunk_data_done , s_body_identity , s_body_identity_eof , s_message_done }; #define PARSING_HEADER(state) (state <= s_headers_done) enum header_states { h_general = 0 , h_C , h_CO , h_CON , h_matching_connection , h_matching_proxy_connection , h_matching_content_length , h_matching_transfer_encoding , h_matching_upgrade , h_connection , h_content_length , h_transfer_encoding , h_upgrade , h_matching_transfer_encoding_chunked , h_matching_connection_token_start , h_matching_connection_keep_alive , h_matching_connection_close , h_matching_connection_upgrade , h_matching_connection_token , h_transfer_encoding_chunked , h_connection_keep_alive , h_connection_close , h_connection_upgrade }; enum http_host_state { s_http_host_dead = 1 , s_http_userinfo_start , s_http_userinfo , s_http_host_start , s_http_host_v6_start , s_http_host , s_http_host_v6 , s_http_host_v6_end , s_http_host_port_start , s_http_host_port }; /* Macros for character classes; depends on strict-mode */ #define CR '\r' #define LF '\n' #define LOWER(c) (unsigned char)(c | 0x20) #define IS_ALPHA(c) (LOWER(c) >= 'a' && LOWER(c) <= 'z') #define IS_NUM(c) ((c) >= '0' && (c) <= '9') #define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_NUM(c)) #define IS_HEX(c) (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f')) #define IS_MARK(c) ((c) == '-' || (c) == '_' || (c) == '.' || \ (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \ (c) == ')') #define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \ (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \ (c) == '$' || (c) == ',') #define STRICT_TOKEN(c) (tokens[(unsigned char)c]) #if HTTP_PARSER_STRICT #define TOKEN(c) (tokens[(unsigned char)c]) #define IS_URL_CHAR(c) (BIT_AT(normal_url_char, (unsigned char)c)) #define IS_HOST_CHAR(c) (IS_ALPHANUM(c) || (c) == '.' || (c) == '-') #else #define TOKEN(c) ((c == ' ') ? ' ' : tokens[(unsigned char)c]) #define IS_URL_CHAR(c) \ (BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80)) #define IS_HOST_CHAR(c) \ (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_') #endif #define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res) #if HTTP_PARSER_STRICT # define STRICT_CHECK(cond) \ do { \ if (cond) { \ SET_ERRNO(HPE_STRICT); \ goto error; \ } \ } while (0) # define NEW_MESSAGE() (http_should_keep_alive(parser) ? start_state : s_dead) #else # define STRICT_CHECK(cond) # define NEW_MESSAGE() start_state #endif /* Map errno values to strings for human-readable output */ #ifdef HTTPPARSER_ENABLE_MEMORY_CONSTRAINTS #define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, "" }, #else #define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, s }, #endif static struct { const char *name; const char *description; } const http_strerror_tab[] = { HTTP_ERRNO_MAP(HTTP_STRERROR_GEN) }; #undef HTTP_STRERROR_GEN int http_message_needs_eof(const http_parser *parser); /* Our URL parser. * * This is designed to be shared by http_parser_execute() for URL validation, * hence it has a state transition + byte-for-byte interface. In addition, it * is meant to be embedded in http_parser_parse_url(), which does the dirty * work of turning state transitions URL components for its API. * * This function should only be invoked with non-space characters. It is * assumed that the caller cares about (and can detect) the transition between * URL and non-URL states by looking for these. */ static enum state parse_url_char(enum state s, const char ch) { if (ch == ' ' || ch == '\r' || ch == '\n') { return s_dead; } #if HTTP_PARSER_STRICT if (ch == '\t' || ch == '\f') { return s_dead; } #endif switch (s) { case s_req_spaces_before_url: /* Proxied requests are followed by scheme of an absolute URI (alpha). * All methods except CONNECT are followed by '/' or '*'. */ if (ch == '/' || ch == '*') { return s_req_path; } if (IS_ALPHA(ch)) { return s_req_schema; } break; case s_req_schema: if (IS_ALPHA(ch)) { return s; } if (ch == ':') { return s_req_schema_slash; } break; case s_req_schema_slash: if (ch == '/') { return s_req_schema_slash_slash; } break; case s_req_schema_slash_slash: if (ch == '/') { return s_req_server_start; } break; case s_req_server_with_at: if (ch == '@') { return s_dead; } /* FALLTHROUGH */ case s_req_server_start: case s_req_server: if (ch == '/') { return s_req_path; } if (ch == '?') { return s_req_query_string_start; } if (ch == '@') { return s_req_server_with_at; } if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') { return s_req_server; } break; case s_req_path: if (IS_URL_CHAR(ch)) { return s; } switch (ch) { case '?': return s_req_query_string_start; case '#': return s_req_fragment_start; } break; case s_req_query_string_start: case s_req_query_string: if (IS_URL_CHAR(ch)) { return s_req_query_string; } switch (ch) { case '?': /* allow extra '?' in query string */ return s_req_query_string; case '#': return s_req_fragment_start; } break; case s_req_fragment_start: if (IS_URL_CHAR(ch)) { return s_req_fragment; } switch (ch) { case '?': return s_req_fragment; case '#': return s; } break; case s_req_fragment: if (IS_URL_CHAR(ch)) { return s; } switch (ch) { case '?': case '#': return s; } break; default: break; } /* We should never fall out of the switch above unless there's an error */ return s_dead; } size_t http_parser_execute (http_parser *parser, const http_parser_settings *settings, const char *data, size_t len) { char c, ch; int8_t unhex_val; const char *p = data; const char *header_field_mark = 0; const char *header_value_mark = 0; const char *url_mark = 0; const char *body_mark = 0; const char *status_mark = 0; enum state p_state = (enum state) parser->state; /* We're in an error state. Don't bother doing anything. */ if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { return 0; } if (len == 0) { switch (CURRENT_STATE()) { case s_body_identity_eof: /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if * we got paused. */ CALLBACK_NOTIFY_NOADVANCE(message_complete); return 0; case s_dead: case s_start_req_or_res: case s_start_res: case s_start_req: return 0; default: SET_ERRNO(HPE_INVALID_EOF_STATE); return 1; } } if (CURRENT_STATE() == s_header_field) header_field_mark = data; if (CURRENT_STATE() == s_header_value) header_value_mark = data; switch (CURRENT_STATE()) { case s_req_path: case s_req_schema: case s_req_schema_slash: case s_req_schema_slash_slash: case s_req_server_start: case s_req_server: case s_req_server_with_at: case s_req_query_string_start: case s_req_query_string: case s_req_fragment_start: case s_req_fragment: url_mark = data; break; case s_res_status: status_mark = data; break; default: break; } for (p=data; p != data + len; p++) { ch = *p; if (PARSING_HEADER(CURRENT_STATE())) COUNT_HEADER_SIZE(1); reexecute: switch (CURRENT_STATE()) { case s_dead: /* this state is used after a 'Connection: close' message * the parser will error out if it reads another message */ if (LIKELY(ch == CR || ch == LF)) break; SET_ERRNO(HPE_CLOSED_CONNECTION); goto error; case s_start_req_or_res: { if (ch == CR || ch == LF) break; parser->flags = 0; parser->content_length = ULLONG_MAX; if (ch == 'H') { UPDATE_STATE(s_res_or_resp_H); CALLBACK_NOTIFY(message_begin); } else { parser->type = HTTP_REQUEST; UPDATE_STATE(s_start_req); REEXECUTE(); } break; } case s_res_or_resp_H: if (ch == 'T') { parser->type = HTTP_RESPONSE; UPDATE_STATE(s_res_HT); } else { if (UNLIKELY(ch != 'E')) { SET_ERRNO(HPE_INVALID_CONSTANT); goto error; } parser->type = HTTP_REQUEST; parser->method = HTTP_HEAD; parser->index = 2; UPDATE_STATE(s_req_method); } break; case s_start_res: { parser->flags = 0; parser->content_length = ULLONG_MAX; switch (ch) { case 'H': UPDATE_STATE(s_res_H); break; case CR: case LF: break; default: SET_ERRNO(HPE_INVALID_CONSTANT); goto error; } CALLBACK_NOTIFY(message_begin); break; } case s_res_H: STRICT_CHECK(ch != 'T'); UPDATE_STATE(s_res_HT); break; case s_res_HT: STRICT_CHECK(ch != 'T'); UPDATE_STATE(s_res_HTT); break; case s_res_HTT: STRICT_CHECK(ch != 'P'); UPDATE_STATE(s_res_HTTP); break; case s_res_HTTP: STRICT_CHECK(ch != '/'); UPDATE_STATE(s_res_first_http_major); break; case s_res_first_http_major: if (UNLIKELY(ch < '0' || ch > '9')) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_major = ch - '0'; UPDATE_STATE(s_res_http_major); break; /* major HTTP version or dot */ case s_res_http_major: { if (ch == '.') { UPDATE_STATE(s_res_first_http_minor); break; } if (!IS_NUM(ch)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_major *= 10; parser->http_major += ch - '0'; if (UNLIKELY(parser->http_major > 999)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } break; } /* first digit of minor HTTP version */ case s_res_first_http_minor: if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_minor = ch - '0'; UPDATE_STATE(s_res_http_minor); break; /* minor HTTP version or end of request line */ case s_res_http_minor: { if (ch == ' ') { UPDATE_STATE(s_res_first_status_code); break; } if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_minor *= 10; parser->http_minor += ch - '0'; if (UNLIKELY(parser->http_minor > 999)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } break; } case s_res_first_status_code: { if (!IS_NUM(ch)) { if (ch == ' ') { break; } SET_ERRNO(HPE_INVALID_STATUS); goto error; } parser->status_code = ch - '0'; UPDATE_STATE(s_res_status_code); break; } case s_res_status_code: { if (!IS_NUM(ch)) { switch (ch) { case ' ': UPDATE_STATE(s_res_status_start); break; case CR: UPDATE_STATE(s_res_line_almost_done); break; case LF: UPDATE_STATE(s_header_field_start); break; default: SET_ERRNO(HPE_INVALID_STATUS); goto error; } break; } parser->status_code *= 10; parser->status_code += ch - '0'; if (UNLIKELY(parser->status_code > 999)) { SET_ERRNO(HPE_INVALID_STATUS); goto error; } break; } case s_res_status_start: { if (ch == CR) { UPDATE_STATE(s_res_line_almost_done); break; } if (ch == LF) { UPDATE_STATE(s_header_field_start); break; } MARK(status); UPDATE_STATE(s_res_status); parser->index = 0; break; } case s_res_status: if (ch == CR) { UPDATE_STATE(s_res_line_almost_done); CALLBACK_DATA(status); break; } if (ch == LF) { UPDATE_STATE(s_header_field_start); CALLBACK_DATA(status); break; } break; case s_res_line_almost_done: STRICT_CHECK(ch != LF); UPDATE_STATE(s_header_field_start); break; case s_start_req: { if (ch == CR || ch == LF) break; parser->flags = 0; parser->content_length = ULLONG_MAX; if (UNLIKELY(!IS_ALPHA(ch))) { SET_ERRNO(HPE_INVALID_METHOD); goto error; } parser->method = (enum http_method) 0; parser->index = 1; switch (ch) { case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break; case 'D': parser->method = HTTP_DELETE; break; case 'G': parser->method = HTTP_GET; break; case 'H': parser->method = HTTP_HEAD; break; case 'L': parser->method = HTTP_LOCK; break; case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break; case 'N': parser->method = HTTP_NOTIFY; break; case 'O': parser->method = HTTP_OPTIONS; break; case 'P': parser->method = HTTP_POST; /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */ break; case 'R': parser->method = HTTP_REPORT; break; case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH */ break; case 'T': parser->method = HTTP_TRACE; break; case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE */ break; default: SET_ERRNO(HPE_INVALID_METHOD); goto error; } UPDATE_STATE(s_req_method); CALLBACK_NOTIFY(message_begin); break; } case s_req_method: { const char *matcher; if (UNLIKELY(ch == '\0')) { SET_ERRNO(HPE_INVALID_METHOD); goto error; } matcher = method_strings[parser->method]; if (ch == ' ' && matcher[parser->index] == '\0') { UPDATE_STATE(s_req_spaces_before_url); } else if (ch == matcher[parser->index]) { ; /* nada */ } else if (parser->method == HTTP_CONNECT) { if (parser->index == 1 && ch == 'H') { parser->method = HTTP_CHECKOUT; } else if (parser->index == 2 && ch == 'P') { parser->method = HTTP_COPY; } else { SET_ERRNO(HPE_INVALID_METHOD); goto error; } } else if (parser->method == HTTP_MKCOL) { if (parser->index == 1 && ch == 'O') { parser->method = HTTP_MOVE; } else if (parser->index == 1 && ch == 'E') { parser->method = HTTP_MERGE; } else if (parser->index == 1 && ch == '-') { parser->method = HTTP_MSEARCH; } else if (parser->index == 2 && ch == 'A') { parser->method = HTTP_MKACTIVITY; } else if (parser->index == 3 && ch == 'A') { parser->method = HTTP_MKCALENDAR; } else { SET_ERRNO(HPE_INVALID_METHOD); goto error; } } else if (parser->method == HTTP_SUBSCRIBE) { if (parser->index == 1 && ch == 'E') { parser->method = HTTP_SEARCH; } else { SET_ERRNO(HPE_INVALID_METHOD); goto error; } } else if (parser->index == 1 && parser->method == HTTP_POST) { if (ch == 'R') { parser->method = HTTP_PROPFIND; /* or HTTP_PROPPATCH */ } else if (ch == 'U') { parser->method = HTTP_PUT; /* or HTTP_PURGE */ } else if (ch == 'A') { parser->method = HTTP_PATCH; } else { SET_ERRNO(HPE_INVALID_METHOD); goto error; } } else if (parser->index == 2) { if (parser->method == HTTP_PUT) { if (ch == 'R') { parser->method = HTTP_PURGE; } else { SET_ERRNO(HPE_INVALID_METHOD); goto error; } } else if (parser->method == HTTP_UNLOCK) { if (ch == 'S') { parser->method = HTTP_UNSUBSCRIBE; } else { SET_ERRNO(HPE_INVALID_METHOD); goto error; } } else { SET_ERRNO(HPE_INVALID_METHOD); goto error; } } else if (parser->index == 4 && parser->method == HTTP_PROPFIND && ch == 'P') { parser->method = HTTP_PROPPATCH; } else { SET_ERRNO(HPE_INVALID_METHOD); goto error; } ++parser->index; break; } case s_req_spaces_before_url: { if (ch == ' ') break; MARK(url); if (parser->method == HTTP_CONNECT) { UPDATE_STATE(s_req_server_start); } UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); if (UNLIKELY(CURRENT_STATE() == s_dead)) { SET_ERRNO(HPE_INVALID_URL); goto error; } break; } case s_req_schema: case s_req_schema_slash: case s_req_schema_slash_slash: case s_req_server_start: { switch (ch) { /* No whitespace allowed here */ case ' ': case CR: case LF: SET_ERRNO(HPE_INVALID_URL); goto error; default: UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); if (UNLIKELY(CURRENT_STATE() == s_dead)) { SET_ERRNO(HPE_INVALID_URL); goto error; } } break; } case s_req_server: case s_req_server_with_at: case s_req_path: case s_req_query_string_start: case s_req_query_string: case s_req_fragment_start: case s_req_fragment: { switch (ch) { case ' ': UPDATE_STATE(s_req_http_start); CALLBACK_DATA(url); break; case CR: case LF: parser->http_major = 0; parser->http_minor = 9; UPDATE_STATE((ch == CR) ? s_req_line_almost_done : s_header_field_start); CALLBACK_DATA(url); break; default: UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); if (UNLIKELY(CURRENT_STATE() == s_dead)) { SET_ERRNO(HPE_INVALID_URL); goto error; } } break; } case s_req_http_start: switch (ch) { case 'H': UPDATE_STATE(s_req_http_H); break; case ' ': break; default: SET_ERRNO(HPE_INVALID_CONSTANT); goto error; } break; case s_req_http_H: STRICT_CHECK(ch != 'T'); UPDATE_STATE(s_req_http_HT); break; case s_req_http_HT: STRICT_CHECK(ch != 'T'); UPDATE_STATE(s_req_http_HTT); break; case s_req_http_HTT: STRICT_CHECK(ch != 'P'); UPDATE_STATE(s_req_http_HTTP); break; case s_req_http_HTTP: STRICT_CHECK(ch != '/'); UPDATE_STATE(s_req_first_http_major); break; /* first digit of major HTTP version */ case s_req_first_http_major: if (UNLIKELY(ch < '1' || ch > '9')) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_major = ch - '0'; UPDATE_STATE(s_req_http_major); break; /* major HTTP version or dot */ case s_req_http_major: { if (ch == '.') { UPDATE_STATE(s_req_first_http_minor); break; } if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_major *= 10; parser->http_major += ch - '0'; if (UNLIKELY(parser->http_major > 999)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } break; } /* first digit of minor HTTP version */ case s_req_first_http_minor: if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_minor = ch - '0'; UPDATE_STATE(s_req_http_minor); break; /* minor HTTP version or end of request line */ case s_req_http_minor: { if (ch == CR) { UPDATE_STATE(s_req_line_almost_done); break; } if (ch == LF) { UPDATE_STATE(s_header_field_start); break; } /* XXX allow spaces after digit? */ if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_minor *= 10; parser->http_minor += ch - '0'; if (UNLIKELY(parser->http_minor > 999)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } break; } /* end of request line */ case s_req_line_almost_done: { if (UNLIKELY(ch != LF)) { SET_ERRNO(HPE_LF_EXPECTED); goto error; } UPDATE_STATE(s_header_field_start); break; } case s_header_field_start: { if (ch == CR) { UPDATE_STATE(s_headers_almost_done); break; } if (ch == LF) { /* they might be just sending \n instead of \r\n so this would be * the second \n to denote the end of headers*/ UPDATE_STATE(s_headers_almost_done); REEXECUTE(); } c = TOKEN(ch); if (UNLIKELY(!c)) { SET_ERRNO(HPE_INVALID_HEADER_TOKEN); goto error; } MARK(header_field); parser->index = 0; UPDATE_STATE(s_header_field); switch (c) { case 'c': parser->header_state = h_C; break; case 'p': parser->header_state = h_matching_proxy_connection; break; case 't': parser->header_state = h_matching_transfer_encoding; break; case 'u': parser->header_state = h_matching_upgrade; break; default: parser->header_state = h_general; break; } break; } case s_header_field: { const char* start = p; for (; p != data + len; p++) { ch = *p; c = TOKEN(ch); if (!c) break; switch (parser->header_state) { case h_general: break; case h_C: parser->index++; parser->header_state = (c == 'o' ? h_CO : h_general); break; case h_CO: parser->index++; parser->header_state = (c == 'n' ? h_CON : h_general); break; case h_CON: parser->index++; switch (c) { case 'n': parser->header_state = h_matching_connection; break; case 't': parser->header_state = h_matching_content_length; break; default: parser->header_state = h_general; break; } break; /* connection */ case h_matching_connection: parser->index++; if (parser->index > sizeof(CONNECTION)-1 || c != CONNECTION[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(CONNECTION)-2) { parser->header_state = h_connection; } break; /* proxy-connection */ case h_matching_proxy_connection: parser->index++; if (parser->index > sizeof(PROXY_CONNECTION)-1 || c != PROXY_CONNECTION[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(PROXY_CONNECTION)-2) { parser->header_state = h_connection; } break; /* content-length */ case h_matching_content_length: parser->index++; if (parser->index > sizeof(CONTENT_LENGTH)-1 || c != CONTENT_LENGTH[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(CONTENT_LENGTH)-2) { parser->header_state = h_content_length; } break; /* transfer-encoding */ case h_matching_transfer_encoding: parser->index++; if (parser->index > sizeof(TRANSFER_ENCODING)-1 || c != TRANSFER_ENCODING[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(TRANSFER_ENCODING)-2) { parser->header_state = h_transfer_encoding; } break; /* upgrade */ case h_matching_upgrade: parser->index++; if (parser->index > sizeof(UPGRADE)-1 || c != UPGRADE[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(UPGRADE)-2) { parser->header_state = h_upgrade; } break; case h_connection: case h_content_length: case h_transfer_encoding: case h_upgrade: if (ch != ' ') parser->header_state = h_general; break; default: assert(0 && "Unknown header_state"); break; } } COUNT_HEADER_SIZE(p - start); if (p == data + len) { --p; break; } if (ch == ':') { UPDATE_STATE(s_header_value_discard_ws); CALLBACK_DATA(header_field); break; } SET_ERRNO(HPE_INVALID_HEADER_TOKEN); goto error; } case s_header_value_discard_ws: if (ch == ' ' || ch == '\t') break; if (ch == CR) { UPDATE_STATE(s_header_value_discard_ws_almost_done); break; } if (ch == LF) { UPDATE_STATE(s_header_value_discard_lws); break; } /* FALLTHROUGH */ case s_header_value_start: { MARK(header_value); UPDATE_STATE(s_header_value); parser->index = 0; c = LOWER(ch); switch (parser->header_state) { case h_upgrade: parser->flags |= F_UPGRADE; parser->header_state = h_general; break; case h_transfer_encoding: /* looking for 'Transfer-Encoding: chunked' */ if ('c' == c) { parser->header_state = h_matching_transfer_encoding_chunked; } else { parser->header_state = h_general; } break; case h_content_length: if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); goto error; } parser->content_length = ch - '0'; break; case h_connection: /* looking for 'Connection: keep-alive' */ if (c == 'k') { parser->header_state = h_matching_connection_keep_alive; /* looking for 'Connection: close' */ } else if (c == 'c') { parser->header_state = h_matching_connection_close; } else if (c == 'u') { parser->header_state = h_matching_connection_upgrade; } else { parser->header_state = h_matching_connection_token; } break; /* Multi-value `Connection` header */ case h_matching_connection_token_start: break; default: parser->header_state = h_general; break; } break; } case s_header_value: { const char* start = p; enum header_states h_state = (enum header_states) parser->header_state; for (; p != data + len; p++) { ch = *p; if (ch == CR) { UPDATE_STATE(s_header_almost_done); parser->header_state = h_state; CALLBACK_DATA(header_value); break; } if (ch == LF) { UPDATE_STATE(s_header_almost_done); COUNT_HEADER_SIZE(p - start); parser->header_state = h_state; CALLBACK_DATA_NOADVANCE(header_value); REEXECUTE(); } c = LOWER(ch); switch (h_state) { case h_general: { const char* p_cr; const char* p_lf; size_t limit = data + len - p; limit = MIN(limit, HTTP_MAX_HEADER_SIZE); p_cr = (const char*) memchr(p, CR, limit); p_lf = (const char*) memchr(p, LF, limit); if (p_cr != NULL) { if (p_lf != NULL && p_cr >= p_lf) p = p_lf; else p = p_cr; } else if (UNLIKELY(p_lf != NULL)) { p = p_lf; } else { p = data + len; } --p; break; } case h_connection: case h_transfer_encoding: assert(0 && "Shouldn't get here."); break; case h_content_length: { uint64_t t; if (ch == ' ') break; if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); parser->header_state = h_state; goto error; } t = parser->content_length; t *= 10; t += ch - '0'; /* Overflow? Test against a conservative limit for simplicity. */ if (UNLIKELY((ULLONG_MAX - 10) / 10 < parser->content_length)) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); parser->header_state = h_state; goto error; } parser->content_length = t; break; } /* Transfer-Encoding: chunked */ case h_matching_transfer_encoding_chunked: parser->index++; if (parser->index > sizeof(CHUNKED)-1 || c != CHUNKED[parser->index]) { h_state = h_general; } else if (parser->index == sizeof(CHUNKED)-2) { h_state = h_transfer_encoding_chunked; } break; case h_matching_connection_token_start: /* looking for 'Connection: keep-alive' */ if (c == 'k') { h_state = h_matching_connection_keep_alive; /* looking for 'Connection: close' */ } else if (c == 'c') { h_state = h_matching_connection_close; } else if (c == 'u') { h_state = h_matching_connection_upgrade; } else if (STRICT_TOKEN(c)) { h_state = h_matching_connection_token; } else if (c == ' ' || c == '\t') { /* Skip lws */ } else { h_state = h_general; } break; /* looking for 'Connection: keep-alive' */ case h_matching_connection_keep_alive: parser->index++; if (parser->index > sizeof(KEEP_ALIVE)-1 || c != KEEP_ALIVE[parser->index]) { h_state = h_matching_connection_token; } else if (parser->index == sizeof(KEEP_ALIVE)-2) { h_state = h_connection_keep_alive; } break; /* looking for 'Connection: close' */ case h_matching_connection_close: parser->index++; if (parser->index > sizeof(CLOSE)-1 || c != CLOSE[parser->index]) { h_state = h_matching_connection_token; } else if (parser->index == sizeof(CLOSE)-2) { h_state = h_connection_close; } break; /* looking for 'Connection: upgrade' */ case h_matching_connection_upgrade: parser->index++; if (parser->index > sizeof(UPGRADE) - 1 || c != UPGRADE[parser->index]) { h_state = h_matching_connection_token; } else if (parser->index == sizeof(UPGRADE)-2) { h_state = h_connection_upgrade; } break; case h_matching_connection_token: if (ch == ',') { h_state = h_matching_connection_token_start; parser->index = 0; } break; case h_transfer_encoding_chunked: if (ch != ' ') h_state = h_general; break; case h_connection_keep_alive: case h_connection_close: case h_connection_upgrade: if (ch == ',') { if (h_state == h_connection_keep_alive) { parser->flags |= F_CONNECTION_KEEP_ALIVE; } else if (h_state == h_connection_close) { parser->flags |= F_CONNECTION_CLOSE; } else if (h_state == h_connection_upgrade) { parser->flags |= F_CONNECTION_UPGRADE; } h_state = h_matching_connection_token_start; parser->index = 0; } else if (ch != ' ') { h_state = h_matching_connection_token; } break; default: UPDATE_STATE(s_header_value); h_state = h_general; break; } } parser->header_state = h_state; COUNT_HEADER_SIZE(p - start); if (p == data + len) --p; break; } case s_header_almost_done: { STRICT_CHECK(ch != LF); UPDATE_STATE(s_header_value_lws); break; } case s_header_value_lws: { if (ch == ' ' || ch == '\t') { UPDATE_STATE(s_header_value_start); REEXECUTE(); } /* finished the header */ switch (parser->header_state) { case h_connection_keep_alive: parser->flags |= F_CONNECTION_KEEP_ALIVE; break; case h_connection_close: parser->flags |= F_CONNECTION_CLOSE; break; case h_transfer_encoding_chunked: parser->flags |= F_CHUNKED; break; case h_connection_upgrade: parser->flags |= F_CONNECTION_UPGRADE; break; default: break; } UPDATE_STATE(s_header_field_start); REEXECUTE(); } case s_header_value_discard_ws_almost_done: { STRICT_CHECK(ch != LF); UPDATE_STATE(s_header_value_discard_lws); break; } case s_header_value_discard_lws: { if (ch == ' ' || ch == '\t') { UPDATE_STATE(s_header_value_discard_ws); break; } else { switch (parser->header_state) { case h_connection_keep_alive: parser->flags |= F_CONNECTION_KEEP_ALIVE; break; case h_connection_close: parser->flags |= F_CONNECTION_CLOSE; break; case h_connection_upgrade: parser->flags |= F_CONNECTION_UPGRADE; break; case h_transfer_encoding_chunked: parser->flags |= F_CHUNKED; break; default: break; } /* header value was empty */ MARK(header_value); UPDATE_STATE(s_header_field_start); CALLBACK_DATA_NOADVANCE(header_value); REEXECUTE(); } } case s_headers_almost_done: { STRICT_CHECK(ch != LF); if (parser->flags & F_TRAILING) { /* End of a chunked request */ UPDATE_STATE(s_message_done); CALLBACK_NOTIFY_NOADVANCE(chunk_complete); REEXECUTE(); } UPDATE_STATE(s_headers_done); /* Set this here so that on_headers_complete() callbacks can see it */ parser->upgrade = ((parser->flags & (F_UPGRADE | F_CONNECTION_UPGRADE)) == (F_UPGRADE | F_CONNECTION_UPGRADE) || parser->method == HTTP_CONNECT); /* Here we call the headers_complete callback. This is somewhat * different than other callbacks because if the user returns 1, we * will interpret that as saying that this message has no body. This * is needed for the annoying case of recieving a response to a HEAD * request. * * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so * we have to simulate it by handling a change in errno below. */ if (settings->on_headers_complete) { switch (settings->on_headers_complete(parser)) { case 0: break; case 1: parser->flags |= F_SKIPBODY; break; default: SET_ERRNO(HPE_CB_headers_complete); RETURN(p - data); /* Error */ } } if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { RETURN(p - data); } REEXECUTE(); } case s_headers_done: { STRICT_CHECK(ch != LF); parser->nread = 0; int hasBody = parser->flags & F_CHUNKED || (parser->content_length > 0 && parser->content_length != ULLONG_MAX); if (parser->upgrade && (parser->method == HTTP_CONNECT || (parser->flags & F_SKIPBODY) || !hasBody)) { /* Exit, the rest of the message is in a different protocol. */ UPDATE_STATE(NEW_MESSAGE()); CALLBACK_NOTIFY(message_complete); RETURN((p - data) + 1); } if (parser->flags & F_SKIPBODY) { UPDATE_STATE(NEW_MESSAGE()); CALLBACK_NOTIFY(message_complete); } else if (parser->flags & F_CHUNKED) { /* chunked encoding - ignore Content-Length header */ UPDATE_STATE(s_chunk_size_start); } else { if (parser->content_length == 0) { /* Content-Length header given but zero: Content-Length: 0\r\n */ UPDATE_STATE(NEW_MESSAGE()); CALLBACK_NOTIFY(message_complete); } else if (parser->content_length != ULLONG_MAX) { /* Content-Length header given and non-zero */ UPDATE_STATE(s_body_identity); } else { if (!http_message_needs_eof(parser)) { /* Assume content-length 0 - read the next */ UPDATE_STATE(NEW_MESSAGE()); CALLBACK_NOTIFY(message_complete); } else { /* Read body until EOF */ UPDATE_STATE(s_body_identity_eof); } } } break; } case s_body_identity: { uint64_t to_read = MIN(parser->content_length, (uint64_t) ((data + len) - p)); assert(parser->content_length != 0 && parser->content_length != ULLONG_MAX); /* The difference between advancing content_length and p is because * the latter will automaticaly advance on the next loop iteration. * Further, if content_length ends up at 0, we want to see the last * byte again for our message complete callback. */ MARK(body); parser->content_length -= to_read; p += to_read - 1; if (parser->content_length == 0) { UPDATE_STATE(s_message_done); /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte. * * The alternative to doing this is to wait for the next byte to * trigger the data callback, just as in every other case. The * problem with this is that this makes it difficult for the test * harness to distinguish between complete-on-EOF and * complete-on-length. It's not clear that this distinction is * important for applications, but let's keep it for now. */ CALLBACK_DATA_(body, p - body_mark + 1, p - data); REEXECUTE(); } break; } /* read until EOF */ case s_body_identity_eof: MARK(body); p = data + len - 1; break; case s_message_done: UPDATE_STATE(NEW_MESSAGE()); CALLBACK_NOTIFY(message_complete); if (parser->upgrade) { /* Exit, the rest of the message is in a different protocol. */ RETURN((p - data) + 1); } break; case s_chunk_size_start: { assert(parser->nread == 1); assert(parser->flags & F_CHUNKED); unhex_val = unhex[(unsigned char)ch]; if (UNLIKELY(unhex_val == -1)) { SET_ERRNO(HPE_INVALID_CHUNK_SIZE); goto error; } parser->content_length = unhex_val; UPDATE_STATE(s_chunk_size); break; } case s_chunk_size: { uint64_t t; assert(parser->flags & F_CHUNKED); if (ch == CR) { UPDATE_STATE(s_chunk_size_almost_done); break; } unhex_val = unhex[(unsigned char)ch]; if (unhex_val == -1) { if (ch == ';' || ch == ' ') { UPDATE_STATE(s_chunk_parameters); break; } SET_ERRNO(HPE_INVALID_CHUNK_SIZE); goto error; } t = parser->content_length; t *= 16; t += unhex_val; /* Overflow? Test against a conservative limit for simplicity. */ if (UNLIKELY((ULLONG_MAX - 16) / 16 < parser->content_length)) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); goto error; } parser->content_length = t; break; } case s_chunk_parameters: { assert(parser->flags & F_CHUNKED); /* just ignore this shit. TODO check for overflow */ if (ch == CR) { UPDATE_STATE(s_chunk_size_almost_done); break; } break; } case s_chunk_size_almost_done: { assert(parser->flags & F_CHUNKED); STRICT_CHECK(ch != LF); parser->nread = 0; if (parser->content_length == 0) { parser->flags |= F_TRAILING; UPDATE_STATE(s_header_field_start); } else { UPDATE_STATE(s_chunk_data); } CALLBACK_NOTIFY(chunk_header); break; } case s_chunk_data: { uint64_t to_read = MIN(parser->content_length, (uint64_t) ((data + len) - p)); assert(parser->flags & F_CHUNKED); assert(parser->content_length != 0 && parser->content_length != ULLONG_MAX); /* See the explanation in s_body_identity for why the content * length and data pointers are managed this way. */ MARK(body); parser->content_length -= to_read; p += to_read - 1; if (parser->content_length == 0) { UPDATE_STATE(s_chunk_data_almost_done); } break; } case s_chunk_data_almost_done: assert(parser->flags & F_CHUNKED); assert(parser->content_length == 0); STRICT_CHECK(ch != CR); UPDATE_STATE(s_chunk_data_done); CALLBACK_DATA(body); break; case s_chunk_data_done: assert(parser->flags & F_CHUNKED); STRICT_CHECK(ch != LF); parser->nread = 0; UPDATE_STATE(s_chunk_size_start); CALLBACK_NOTIFY(chunk_complete); break; default: assert(0 && "unhandled state"); SET_ERRNO(HPE_INVALID_INTERNAL_STATE); goto error; } } /* Run callbacks for any marks that we have leftover after we ran our of * bytes. There should be at most one of these set, so it's OK to invoke * them in series (unset marks will not result in callbacks). * * We use the NOADVANCE() variety of callbacks here because 'p' has already * overflowed 'data' and this allows us to correct for the off-by-one that * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p' * value that's in-bounds). */ assert(((header_field_mark ? 1 : 0) + (header_value_mark ? 1 : 0) + (url_mark ? 1 : 0) + (body_mark ? 1 : 0) + (status_mark ? 1 : 0)) <= 1); CALLBACK_DATA_NOADVANCE(header_field); CALLBACK_DATA_NOADVANCE(header_value); CALLBACK_DATA_NOADVANCE(url); CALLBACK_DATA_NOADVANCE(body); CALLBACK_DATA_NOADVANCE(status); RETURN(len); error: if (HTTP_PARSER_ERRNO(parser) == HPE_OK) { SET_ERRNO(HPE_UNKNOWN); } RETURN(p - data); } /* Does the parser need to see an EOF to find the end of the message? */ int http_message_needs_eof (const http_parser *parser) { if (parser->type == HTTP_REQUEST) { return 0; } /* See RFC 2616 section 4.4 */ if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */ parser->status_code == 204 || /* No Content */ parser->status_code == 304 || /* Not Modified */ parser->flags & F_SKIPBODY) { /* response to a HEAD request */ return 0; } if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) { return 0; } return 1; } int http_should_keep_alive (const http_parser *parser) { if (parser->http_major > 0 && parser->http_minor > 0) { /* HTTP/1.1 */ if (parser->flags & F_CONNECTION_CLOSE) { return 0; } } else { /* HTTP/1.0 or earlier */ if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) { return 0; } } return !http_message_needs_eof(parser); } const char * http_method_str (enum http_method m) { return ELEM_AT(method_strings, m, ""); } void http_parser_init (http_parser *parser, enum http_parser_type t) { void *data = parser->data; /* preserve application data */ memset(parser, 0, sizeof(*parser)); parser->data = data; parser->type = t; parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res)); parser->http_errno = HPE_OK; } void http_parser_settings_init(http_parser_settings *settings) { memset(settings, 0, sizeof(*settings)); } const char * http_errno_name(enum http_errno err) { assert(((size_t) err) < (sizeof(http_strerror_tab) / sizeof(http_strerror_tab[0]))); return http_strerror_tab[err].name; } #ifndef HTTPPARSER_ENABLE_MEMORY_CONSTRAINTS const char * http_errno_description(enum http_errno err) { assert(((size_t) err) < (sizeof(http_strerror_tab) / sizeof(http_strerror_tab[0]))); return http_strerror_tab[err].description; } static enum http_host_state http_parse_host_char(enum http_host_state s, const char ch) { switch(s) { case s_http_userinfo: case s_http_userinfo_start: if (ch == '@') { return s_http_host_start; } if (IS_USERINFO_CHAR(ch)) { return s_http_userinfo; } break; case s_http_host_start: if (ch == '[') { return s_http_host_v6_start; } if (IS_HOST_CHAR(ch)) { return s_http_host; } break; case s_http_host: if (IS_HOST_CHAR(ch)) { return s_http_host; } /* FALLTHROUGH */ case s_http_host_v6_end: if (ch == ':') { return s_http_host_port_start; } break; case s_http_host_v6: if (ch == ']') { return s_http_host_v6_end; } /* FALLTHROUGH */ case s_http_host_v6_start: if (IS_HEX(ch) || ch == ':' || ch == '.') { return s_http_host_v6; } break; case s_http_host_port: case s_http_host_port_start: if (IS_NUM(ch)) { return s_http_host_port; } break; default: break; } return s_http_host_dead; } static int http_parse_host(const char * buf, struct http_parser_url *u, int found_at) { assert(u->field_set & (1 << UF_HOST)); enum http_host_state s; const char *p; size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len; u->field_data[UF_HOST].len = 0; s = found_at ? s_http_userinfo_start : s_http_host_start; for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) { enum http_host_state new_s = http_parse_host_char(s, *p); if (new_s == s_http_host_dead) { return 1; } switch(new_s) { case s_http_host: if (s != s_http_host) { u->field_data[UF_HOST].off = p - buf; } u->field_data[UF_HOST].len++; break; case s_http_host_v6: if (s != s_http_host_v6) { u->field_data[UF_HOST].off = p - buf; } u->field_data[UF_HOST].len++; break; case s_http_host_port: if (s != s_http_host_port) { u->field_data[UF_PORT].off = p - buf; u->field_data[UF_PORT].len = 0; u->field_set |= (1 << UF_PORT); } u->field_data[UF_PORT].len++; break; case s_http_userinfo: if (s != s_http_userinfo) { u->field_data[UF_USERINFO].off = p - buf ; u->field_data[UF_USERINFO].len = 0; u->field_set |= (1 << UF_USERINFO); } u->field_data[UF_USERINFO].len++; break; default: break; } s = new_s; } /* Make sure we don't end somewhere unexpected */ switch (s) { case s_http_host_start: case s_http_host_v6_start: case s_http_host_v6: case s_http_host_port_start: case s_http_userinfo: case s_http_userinfo_start: return 1; default: break; } return 0; } int http_parser_parse_url(const char *buf, size_t buflen, int is_connect, struct http_parser_url *u) { enum state s; const char *p; enum http_parser_url_fields uf, old_uf; int found_at = 0; u->port = u->field_set = 0; s = is_connect ? s_req_server_start : s_req_spaces_before_url; old_uf = UF_MAX; for (p = buf; p < buf + buflen; p++) { s = parse_url_char(s, *p); /* Figure out the next field that we're operating on */ switch (s) { case s_dead: return 1; /* Skip delimeters */ case s_req_schema_slash: case s_req_schema_slash_slash: case s_req_server_start: case s_req_query_string_start: case s_req_fragment_start: continue; case s_req_schema: uf = UF_SCHEMA; break; case s_req_server_with_at: found_at = 1; /* FALLTROUGH */ case s_req_server: uf = UF_HOST; break; case s_req_path: uf = UF_PATH; break; case s_req_query_string: uf = UF_QUERY; break; case s_req_fragment: uf = UF_FRAGMENT; break; default: assert(!"Unexpected state"); return 1; } /* Nothing's changed; soldier on */ if (uf == old_uf) { u->field_data[uf].len++; continue; } u->field_data[uf].off = p - buf; u->field_data[uf].len = 1; u->field_set |= (1 << uf); old_uf = uf; } /* host must be present if there is a schema */ /* parsing http:///toto will fail */ if ((u->field_set & (1 << UF_SCHEMA)) && (u->field_set & (1 << UF_HOST)) == 0) { return 1; } if (u->field_set & (1 << UF_HOST)) { if (http_parse_host(buf, u, found_at) != 0) { return 1; } } /* CONNECT requests can only contain "hostname:port" */ if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) { return 1; } if (u->field_set & (1 << UF_PORT)) { /* Don't bother with endp; we've already validated the string */ unsigned long v = strtoul(buf + u->field_data[UF_PORT].off, NULL, 10); /* Ports have a max value of 2^16 */ if (v > 0xffff) { return 1; } u->port = (uint16_t) v; } return 0; } #endif void http_parser_pause(http_parser *parser, int paused) { /* Users should only be pausing/unpausing a parser that is not in an error * state. In non-debug builds, there's not much that we can do about this * other than ignore it. */ if (HTTP_PARSER_ERRNO(parser) == HPE_OK || HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) { SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK); } else { assert(0 && "Attempting to pause parser in error state"); } } #ifndef HTTPPARSER_ENABLE_MEMORY_CONSTRAINTS int http_body_is_final(const struct http_parser *parser) { return parser->state == s_message_done; } unsigned long http_parser_version(void) { return HTTP_PARSER_VERSION_MAJOR * 0x10000 | HTTP_PARSER_VERSION_MINOR * 0x00100 | HTTP_PARSER_VERSION_PATCH * 0x00001; } #endif iotjs-1.0+715/deps/http-parser/http_parser.gyp000066400000000000000000000054471335066055100213100ustar00rootroot00000000000000# This file is used with the GYP meta build system. # http://code.google.com/p/gyp/ # To build try this: # svn co http://gyp.googlecode.com/svn/trunk gyp # ./gyp/gyp -f make --depth=`pwd` http_parser.gyp # ./out/Debug/test { 'target_defaults': { 'default_configuration': 'Debug', 'configurations': { # TODO: hoist these out and put them somewhere common, because # RuntimeLibrary MUST MATCH across the entire project 'Debug': { 'defines': [ 'DEBUG', '_DEBUG' ], 'cflags': [ '-Wall', '-Wextra', '-O0', '-g', '-ftrapv' ], 'msvs_settings': { 'VCCLCompilerTool': { 'RuntimeLibrary': 1, # static debug }, }, }, 'Release': { 'defines': [ 'NDEBUG' ], 'cflags': [ '-Wall', '-Wextra', '-O3' ], 'msvs_settings': { 'VCCLCompilerTool': { 'RuntimeLibrary': 0, # static release }, }, } }, 'msvs_settings': { 'VCCLCompilerTool': { }, 'VCLibrarianTool': { }, 'VCLinkerTool': { 'GenerateDebugInformation': 'true', }, }, 'conditions': [ ['OS == "win"', { 'defines': [ 'WIN32' ], }] ], }, 'targets': [ { 'target_name': 'http_parser', 'type': 'static_library', 'include_dirs': [ '.' ], 'direct_dependent_settings': { 'defines': [ 'HTTP_PARSER_STRICT=0' ], 'include_dirs': [ '.' ], }, 'defines': [ 'HTTP_PARSER_STRICT=0' ], 'sources': [ './http_parser.c', ], 'conditions': [ ['OS=="win"', { 'msvs_settings': { 'VCCLCompilerTool': { # Compile as C++. http_parser.c is actually C99, but C++ is # close enough in this case. 'CompileAs': 2, }, }, }] ], }, { 'target_name': 'http_parser_strict', 'type': 'static_library', 'include_dirs': [ '.' ], 'direct_dependent_settings': { 'defines': [ 'HTTP_PARSER_STRICT=1' ], 'include_dirs': [ '.' ], }, 'defines': [ 'HTTP_PARSER_STRICT=1' ], 'sources': [ './http_parser.c', ], 'conditions': [ ['OS=="win"', { 'msvs_settings': { 'VCCLCompilerTool': { # Compile as C++. http_parser.c is actually C99, but C++ is # close enough in this case. 'CompileAs': 2, }, }, }] ], }, { 'target_name': 'test-nonstrict', 'type': 'executable', 'dependencies': [ 'http_parser' ], 'sources': [ 'test.c' ] }, { 'target_name': 'test-strict', 'type': 'executable', 'dependencies': [ 'http_parser_strict' ], 'sources': [ 'test.c' ] } ] } iotjs-1.0+715/deps/http-parser/http_parser.h000066400000000000000000000315331335066055100207330ustar00rootroot00000000000000/* Copyright Joyent, Inc. and other Node 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. */ #ifndef http_parser_h #define http_parser_h #ifdef __cplusplus extern "C" { #endif /* Also update SONAME in the Makefile whenever you change these. */ #define HTTP_PARSER_VERSION_MAJOR 2 #define HTTP_PARSER_VERSION_MINOR 5 #define HTTP_PARSER_VERSION_PATCH 0 #include #if defined(_WIN32) && !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER<1600) #include #include typedef __int8 int8_t; typedef unsigned __int8 uint8_t; typedef __int16 int16_t; typedef unsigned __int16 uint16_t; typedef __int32 int32_t; typedef unsigned __int32 uint32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #else #include #endif /* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run * faster */ #ifndef HTTP_PARSER_STRICT # define HTTP_PARSER_STRICT 1 #endif /* Maximium header size allowed. If the macro is not defined * before including this header then the default is used. To * change the maximum header size, define the macro in the build * environment (e.g. -DHTTP_MAX_HEADER_SIZE=). To remove * the effective limit on the size of the header, define the macro * to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff) */ #ifndef HTTP_MAX_HEADER_SIZE # define HTTP_MAX_HEADER_SIZE (80*1024) #endif typedef struct http_parser http_parser; typedef struct http_parser_settings http_parser_settings; /* Callbacks should return non-zero to indicate an error. The parser will * then halt execution. * * The one exception is on_headers_complete. In a HTTP_RESPONSE parser * returning '1' from on_headers_complete will tell the parser that it * should not expect a body. This is used when receiving a response to a * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding: * chunked' headers that indicate the presence of a body. * * http_data_cb does not return data chunks. It will be called arbitrarily * many times for each string. E.G. you might get 10 callbacks for "on_url" * each providing just a few characters more data. */ typedef int (*http_data_cb) (http_parser*, const char *at, size_t length); typedef int (*http_cb) (http_parser*); /* Request Methods */ #define HTTP_METHOD_MAP(XX) \ XX(0, DELETE, DELETE) \ XX(1, GET, GET) \ XX(2, HEAD, HEAD) \ XX(3, POST, POST) \ XX(4, PUT, PUT) \ /* pathological */ \ XX(5, CONNECT, CONNECT) \ XX(6, OPTIONS, OPTIONS) \ XX(7, TRACE, TRACE) \ /* webdav */ \ XX(8, COPY, COPY) \ XX(9, LOCK, LOCK) \ XX(10, MKCOL, MKCOL) \ XX(11, MOVE, MOVE) \ XX(12, PROPFIND, PROPFIND) \ XX(13, PROPPATCH, PROPPATCH) \ XX(14, SEARCH, SEARCH) \ XX(15, UNLOCK, UNLOCK) \ /* subversion */ \ XX(16, REPORT, REPORT) \ XX(17, MKACTIVITY, MKACTIVITY) \ XX(18, CHECKOUT, CHECKOUT) \ XX(19, MERGE, MERGE) \ /* upnp */ \ XX(20, MSEARCH, M-SEARCH) \ XX(21, NOTIFY, NOTIFY) \ XX(22, SUBSCRIBE, SUBSCRIBE) \ XX(23, UNSUBSCRIBE, UNSUBSCRIBE) \ /* RFC-5789 */ \ XX(24, PATCH, PATCH) \ XX(25, PURGE, PURGE) \ /* CalDAV */ \ XX(26, MKCALENDAR, MKCALENDAR) \ enum http_method { #define XX(num, name, string) HTTP_##name = num, HTTP_METHOD_MAP(XX) #undef XX }; enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH }; /* Flag values for http_parser.flags field */ enum flags { F_CHUNKED = 1 << 0 , F_CONNECTION_KEEP_ALIVE = 1 << 1 , F_CONNECTION_CLOSE = 1 << 2 , F_CONNECTION_UPGRADE = 1 << 3 , F_TRAILING = 1 << 4 , F_UPGRADE = 1 << 5 , F_SKIPBODY = 1 << 6 }; /* Map for errno-related constants * * The provided argument should be a macro that takes 2 arguments. */ #define HTTP_ERRNO_MAP(XX) \ /* No error */ \ XX(OK, "success") \ \ /* Callback-related errors */ \ XX(CB_message_begin, "the on_message_begin callback failed") \ XX(CB_url, "the on_url callback failed") \ XX(CB_header_field, "the on_header_field callback failed") \ XX(CB_header_value, "the on_header_value callback failed") \ XX(CB_headers_complete, "the on_headers_complete callback failed") \ XX(CB_body, "the on_body callback failed") \ XX(CB_message_complete, "the on_message_complete callback failed") \ XX(CB_status, "the on_status callback failed") \ XX(CB_chunk_header, "the on_chunk_header callback failed") \ XX(CB_chunk_complete, "the on_chunk_complete callback failed") \ \ /* Parsing-related errors */ \ XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \ XX(HEADER_OVERFLOW, \ "too many header bytes seen; overflow detected") \ XX(CLOSED_CONNECTION, \ "data received after completed connection: close message") \ XX(INVALID_VERSION, "invalid HTTP version") \ XX(INVALID_STATUS, "invalid HTTP status code") \ XX(INVALID_METHOD, "invalid HTTP method") \ XX(INVALID_URL, "invalid URL") \ XX(INVALID_HOST, "invalid host") \ XX(INVALID_PORT, "invalid port") \ XX(INVALID_PATH, "invalid path") \ XX(INVALID_QUERY_STRING, "invalid query string") \ XX(INVALID_FRAGMENT, "invalid fragment") \ XX(LF_EXPECTED, "LF character expected") \ XX(INVALID_HEADER_TOKEN, "invalid character in header") \ XX(INVALID_CONTENT_LENGTH, \ "invalid character in content-length header") \ XX(INVALID_CHUNK_SIZE, \ "invalid character in chunk size header") \ XX(INVALID_CONSTANT, "invalid constant string") \ XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\ XX(STRICT, "strict mode assertion failed") \ XX(PAUSED, "parser is paused") \ XX(UNKNOWN, "an unknown error occurred") /* Define HPE_* values for each errno value above */ #define HTTP_ERRNO_GEN(n, s) HPE_##n, enum http_errno { HTTP_ERRNO_MAP(HTTP_ERRNO_GEN) }; #undef HTTP_ERRNO_GEN /* Get an http_errno value from an http_parser */ #define HTTP_PARSER_ERRNO(p) ((enum http_errno) (p)->http_errno) struct http_parser { /** PRIVATE **/ unsigned int type : 2; /* enum http_parser_type */ unsigned int flags : 7; /* F_* values from 'flags' enum; semi-public */ unsigned int state : 7; /* enum state from http_parser.c */ unsigned int header_state : 8; /* enum header_state from http_parser.c */ unsigned int index : 8; /* index into current matcher */ uint32_t nread; /* # bytes read in various scenarios */ uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */ /** READ-ONLY **/ unsigned short http_major; unsigned short http_minor; unsigned int status_code : 16; /* responses only */ unsigned int method : 8; /* requests only */ unsigned int http_errno : 7; /* 1 = Upgrade header was present and the parser has exited because of that. * 0 = No upgrade header present. * Should be checked when http_parser_execute() returns in addition to * error checking. */ unsigned int upgrade : 1; /** PUBLIC **/ void *data; /* A pointer to get hook to the "connection" or "socket" object */ }; struct http_parser_settings { http_cb on_message_begin; http_data_cb on_url; http_data_cb on_status; http_data_cb on_header_field; http_data_cb on_header_value; http_cb on_headers_complete; http_data_cb on_body; http_cb on_message_complete; /* When on_chunk_header is called, the current chunk length is stored * in parser->content_length. */ http_cb on_chunk_header; http_cb on_chunk_complete; }; enum http_parser_url_fields { UF_SCHEMA = 0 , UF_HOST = 1 , UF_PORT = 2 , UF_PATH = 3 , UF_QUERY = 4 , UF_FRAGMENT = 5 , UF_USERINFO = 6 , UF_MAX = 7 }; /* Result structure for http_parser_parse_url(). * * Callers should index into field_data[] with UF_* values iff field_set * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and * because we probably have padding left over), we convert any port to * a uint16_t. */ struct http_parser_url { uint16_t field_set; /* Bitmask of (1 << UF_*) values */ uint16_t port; /* Converted UF_PORT string */ struct { uint16_t off; /* Offset into buffer in which field starts */ uint16_t len; /* Length of run in buffer */ } field_data[UF_MAX]; }; #ifndef HTTPPARSER_ENABLE_MEMORY_CONSTRAINTS /* Returns the library version. Bits 16-23 contain the major version number, * bits 8-15 the minor version number and bits 0-7 the patch level. * Usage example: * * unsigned long version = http_parser_version(); * unsigned major = (version >> 16) & 255; * unsigned minor = (version >> 8) & 255; * unsigned patch = version & 255; * printf("http_parser v%u.%u.%u\n", major, minor, patch); */ unsigned long http_parser_version(void); #endif void http_parser_init(http_parser *parser, enum http_parser_type type); /* Initialize http_parser_settings members to 0 */ void http_parser_settings_init(http_parser_settings *settings); /* Executes the parser. Returns number of parsed bytes. Sets * `parser->http_errno` on error. */ size_t http_parser_execute(http_parser *parser, const http_parser_settings *settings, const char *data, size_t len); /* If http_should_keep_alive() in the on_headers_complete or * on_message_complete callback returns 0, then this should be * the last message on the connection. * If you are the server, respond with the "Connection: close" header. * If you are the client, close the connection. */ int http_should_keep_alive(const http_parser *parser); /* Returns a string version of the HTTP method. */ const char *http_method_str(enum http_method m); /* Return a string name of the given error */ const char *http_errno_name(enum http_errno err); #ifndef HTTPPARSER_ENABLE_MEMORY_CONSTRAINTS /* Return a string description of the given error */ const char *http_errno_description(enum http_errno err); /* Parse a URL; return nonzero on failure */ int http_parser_parse_url(const char *buf, size_t buflen, int is_connect, struct http_parser_url *u); #endif /* Pause or un-pause the parser; a nonzero value pauses */ void http_parser_pause(http_parser *parser, int paused); #ifndef HTTPPARSER_ENABLE_MEMORY_CONSTRAINTS /* Checks if this is the final chunk of the body. */ int http_body_is_final(const http_parser *parser); #endif #ifdef __cplusplus } #endif #endif iotjs-1.0+715/deps/http-parser/test.c000066400000000000000000003111671335066055100173560ustar00rootroot00000000000000/* Copyright Joyent, Inc. and other Node 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. */ #include "http_parser.h" #include #include #include #include /* rand */ #include #include #if defined(__APPLE__) # undef strlcat # undef strlncpy # undef strlcpy #endif /* defined(__APPLE__) */ #undef TRUE #define TRUE 1 #undef FALSE #define FALSE 0 #define MAX_HEADERS 13 #define MAX_ELEMENT_SIZE 2048 #define MAX_CHUNKS 16 #define MIN(a,b) ((a) < (b) ? (a) : (b)) static http_parser *parser; struct message { const char *name; // for debugging purposes const char *raw; enum http_parser_type type; enum http_method method; int status_code; char response_status[MAX_ELEMENT_SIZE]; char request_path[MAX_ELEMENT_SIZE]; char request_url[MAX_ELEMENT_SIZE]; char fragment[MAX_ELEMENT_SIZE]; char query_string[MAX_ELEMENT_SIZE]; char body[MAX_ELEMENT_SIZE]; size_t body_size; const char *host; const char *userinfo; uint16_t port; int num_headers; enum { NONE=0, FIELD, VALUE } last_header_element; char headers [MAX_HEADERS][2][MAX_ELEMENT_SIZE]; int should_keep_alive; int num_chunks; int num_chunks_complete; int chunk_lengths[MAX_CHUNKS]; const char *upgrade; // upgraded body unsigned short http_major; unsigned short http_minor; int message_begin_cb_called; int headers_complete_cb_called; int message_complete_cb_called; int message_complete_on_eof; int body_is_final; }; static int currently_parsing_eof; static struct message messages[5]; static int num_messages; static http_parser_settings *current_pause_parser; /* * R E Q U E S T S * */ const struct message requests[] = #define CURL_GET 0 { {.name= "curl get" ,.type= HTTP_REQUEST ,.raw= "GET /test HTTP/1.1\r\n" "User-Agent: curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1\r\n" "Host: 0.0.0.0=5000\r\n" "Accept: */*\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/test" ,.request_url= "/test" ,.num_headers= 3 ,.headers= { { "User-Agent", "curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1" } , { "Host", "0.0.0.0=5000" } , { "Accept", "*/*" } } ,.body= "" } #define FIREFOX_GET 1 , {.name= "firefox get" ,.type= HTTP_REQUEST ,.raw= "GET /favicon.ico HTTP/1.1\r\n" "Host: 0.0.0.0=5000\r\n" "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0\r\n" "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" "Accept-Language: en-us,en;q=0.5\r\n" "Accept-Encoding: gzip,deflate\r\n" "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" "Keep-Alive: 300\r\n" "Connection: keep-alive\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/favicon.ico" ,.request_url= "/favicon.ico" ,.num_headers= 8 ,.headers= { { "Host", "0.0.0.0=5000" } , { "User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0" } , { "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } , { "Accept-Language", "en-us,en;q=0.5" } , { "Accept-Encoding", "gzip,deflate" } , { "Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7" } , { "Keep-Alive", "300" } , { "Connection", "keep-alive" } } ,.body= "" } #define DUMBFUCK 2 , {.name= "dumbfuck" ,.type= HTTP_REQUEST ,.raw= "GET /dumbfuck HTTP/1.1\r\n" "aaaaaaaaaaaaa:++++++++++\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/dumbfuck" ,.request_url= "/dumbfuck" ,.num_headers= 1 ,.headers= { { "aaaaaaaaaaaaa", "++++++++++" } } ,.body= "" } #define FRAGMENT_IN_URI 3 , {.name= "fragment in url" ,.type= HTTP_REQUEST ,.raw= "GET /forums/1/topics/2375?page=1#posts-17408 HTTP/1.1\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "page=1" ,.fragment= "posts-17408" ,.request_path= "/forums/1/topics/2375" /* XXX request url does include fragment? */ ,.request_url= "/forums/1/topics/2375?page=1#posts-17408" ,.num_headers= 0 ,.body= "" } #define GET_NO_HEADERS_NO_BODY 4 , {.name= "get no headers no body" ,.type= HTTP_REQUEST ,.raw= "GET /get_no_headers_no_body/world HTTP/1.1\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE /* would need Connection: close */ ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/get_no_headers_no_body/world" ,.request_url= "/get_no_headers_no_body/world" ,.num_headers= 0 ,.body= "" } #define GET_ONE_HEADER_NO_BODY 5 , {.name= "get one header no body" ,.type= HTTP_REQUEST ,.raw= "GET /get_one_header_no_body HTTP/1.1\r\n" "Accept: */*\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE /* would need Connection: close */ ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/get_one_header_no_body" ,.request_url= "/get_one_header_no_body" ,.num_headers= 1 ,.headers= { { "Accept" , "*/*" } } ,.body= "" } #define GET_FUNKY_CONTENT_LENGTH 6 , {.name= "get funky content length body hello" ,.type= HTTP_REQUEST ,.raw= "GET /get_funky_content_length_body_hello HTTP/1.0\r\n" "conTENT-Length: 5\r\n" "\r\n" "HELLO" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 0 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/get_funky_content_length_body_hello" ,.request_url= "/get_funky_content_length_body_hello" ,.num_headers= 1 ,.headers= { { "conTENT-Length" , "5" } } ,.body= "HELLO" } #define POST_IDENTITY_BODY_WORLD 7 , {.name= "post identity body world" ,.type= HTTP_REQUEST ,.raw= "POST /post_identity_body_world?q=search#hey HTTP/1.1\r\n" "Accept: */*\r\n" "Transfer-Encoding: identity\r\n" "Content-Length: 5\r\n" "\r\n" "World" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_POST ,.query_string= "q=search" ,.fragment= "hey" ,.request_path= "/post_identity_body_world" ,.request_url= "/post_identity_body_world?q=search#hey" ,.num_headers= 3 ,.headers= { { "Accept", "*/*" } , { "Transfer-Encoding", "identity" } , { "Content-Length", "5" } } ,.body= "World" } #define POST_CHUNKED_ALL_YOUR_BASE 8 , {.name= "post - chunked body: all your base are belong to us" ,.type= HTTP_REQUEST ,.raw= "POST /post_chunked_all_your_base HTTP/1.1\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "1e\r\nall your base are belong to us\r\n" "0\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_POST ,.query_string= "" ,.fragment= "" ,.request_path= "/post_chunked_all_your_base" ,.request_url= "/post_chunked_all_your_base" ,.num_headers= 1 ,.headers= { { "Transfer-Encoding" , "chunked" } } ,.body= "all your base are belong to us" ,.num_chunks_complete= 2 ,.chunk_lengths= { 0x1e } } #define TWO_CHUNKS_MULT_ZERO_END 9 , {.name= "two chunks ; triple zero ending" ,.type= HTTP_REQUEST ,.raw= "POST /two_chunks_mult_zero_end HTTP/1.1\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "5\r\nhello\r\n" "6\r\n world\r\n" "000\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_POST ,.query_string= "" ,.fragment= "" ,.request_path= "/two_chunks_mult_zero_end" ,.request_url= "/two_chunks_mult_zero_end" ,.num_headers= 1 ,.headers= { { "Transfer-Encoding", "chunked" } } ,.body= "hello world" ,.num_chunks_complete= 3 ,.chunk_lengths= { 5, 6 } } #define CHUNKED_W_TRAILING_HEADERS 10 , {.name= "chunked with trailing headers. blech." ,.type= HTTP_REQUEST ,.raw= "POST /chunked_w_trailing_headers HTTP/1.1\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "5\r\nhello\r\n" "6\r\n world\r\n" "0\r\n" "Vary: *\r\n" "Content-Type: text/plain\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_POST ,.query_string= "" ,.fragment= "" ,.request_path= "/chunked_w_trailing_headers" ,.request_url= "/chunked_w_trailing_headers" ,.num_headers= 3 ,.headers= { { "Transfer-Encoding", "chunked" } , { "Vary", "*" } , { "Content-Type", "text/plain" } } ,.body= "hello world" ,.num_chunks_complete= 3 ,.chunk_lengths= { 5, 6 } } #define CHUNKED_W_BULLSHIT_AFTER_LENGTH 11 , {.name= "with bullshit after the length" ,.type= HTTP_REQUEST ,.raw= "POST /chunked_w_bullshit_after_length HTTP/1.1\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "5; ihatew3;whatthefuck=aretheseparametersfor\r\nhello\r\n" "6; blahblah; blah\r\n world\r\n" "0\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_POST ,.query_string= "" ,.fragment= "" ,.request_path= "/chunked_w_bullshit_after_length" ,.request_url= "/chunked_w_bullshit_after_length" ,.num_headers= 1 ,.headers= { { "Transfer-Encoding", "chunked" } } ,.body= "hello world" ,.num_chunks_complete= 3 ,.chunk_lengths= { 5, 6 } } #define WITH_QUOTES 12 , {.name= "with quotes" ,.type= HTTP_REQUEST ,.raw= "GET /with_\"stupid\"_quotes?foo=\"bar\" HTTP/1.1\r\n\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "foo=\"bar\"" ,.fragment= "" ,.request_path= "/with_\"stupid\"_quotes" ,.request_url= "/with_\"stupid\"_quotes?foo=\"bar\"" ,.num_headers= 0 ,.headers= { } ,.body= "" } #define APACHEBENCH_GET 13 /* The server receiving this request SHOULD NOT wait for EOF * to know that content-length == 0. * How to represent this in a unit test? message_complete_on_eof * Compare with NO_CONTENT_LENGTH_RESPONSE. */ , {.name = "apachebench get" ,.type= HTTP_REQUEST ,.raw= "GET /test HTTP/1.0\r\n" "Host: 0.0.0.0:5000\r\n" "User-Agent: ApacheBench/2.3\r\n" "Accept: */*\r\n\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 0 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/test" ,.request_url= "/test" ,.num_headers= 3 ,.headers= { { "Host", "0.0.0.0:5000" } , { "User-Agent", "ApacheBench/2.3" } , { "Accept", "*/*" } } ,.body= "" } #define QUERY_URL_WITH_QUESTION_MARK_GET 14 /* Some clients include '?' characters in query strings. */ , {.name = "query url with question mark" ,.type= HTTP_REQUEST ,.raw= "GET /test.cgi?foo=bar?baz HTTP/1.1\r\n\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "foo=bar?baz" ,.fragment= "" ,.request_path= "/test.cgi" ,.request_url= "/test.cgi?foo=bar?baz" ,.num_headers= 0 ,.headers= {} ,.body= "" } #define PREFIX_NEWLINE_GET 15 /* Some clients, especially after a POST in a keep-alive connection, * will send an extra CRLF before the next request */ , {.name = "newline prefix get" ,.type= HTTP_REQUEST ,.raw= "\r\nGET /test HTTP/1.1\r\n\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/test" ,.request_url= "/test" ,.num_headers= 0 ,.headers= { } ,.body= "" } #define UPGRADE_REQUEST 16 , {.name = "upgrade request" ,.type= HTTP_REQUEST ,.raw= "GET /demo HTTP/1.1\r\n" "Host: example.com\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Key2: 12998 5 Y3 1 .P00\r\n" "Sec-WebSocket-Protocol: sample\r\n" "Upgrade: WebSocket\r\n" "Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5\r\n" "Origin: http://example.com\r\n" "\r\n" "Hot diggity dogg" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/demo" ,.request_url= "/demo" ,.num_headers= 7 ,.upgrade="Hot diggity dogg" ,.headers= { { "Host", "example.com" } , { "Connection", "Upgrade" } , { "Sec-WebSocket-Key2", "12998 5 Y3 1 .P00" } , { "Sec-WebSocket-Protocol", "sample" } , { "Upgrade", "WebSocket" } , { "Sec-WebSocket-Key1", "4 @1 46546xW%0l 1 5" } , { "Origin", "http://example.com" } } ,.body= "" } #define CONNECT_REQUEST 17 , {.name = "connect request" ,.type= HTTP_REQUEST ,.raw= "CONNECT 0-home0.netscape.com:443 HTTP/1.0\r\n" "User-agent: Mozilla/1.1N\r\n" "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" "\r\n" "some data\r\n" "and yet even more data" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 0 ,.method= HTTP_CONNECT ,.query_string= "" ,.fragment= "" ,.request_path= "" ,.request_url= "0-home0.netscape.com:443" ,.num_headers= 2 ,.upgrade="some data\r\nand yet even more data" ,.headers= { { "User-agent", "Mozilla/1.1N" } , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } } ,.body= "" } #define REPORT_REQ 18 , {.name= "report request" ,.type= HTTP_REQUEST ,.raw= "REPORT /test HTTP/1.1\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_REPORT ,.query_string= "" ,.fragment= "" ,.request_path= "/test" ,.request_url= "/test" ,.num_headers= 0 ,.headers= {} ,.body= "" } #define NO_HTTP_VERSION 19 , {.name= "request with no http version" ,.type= HTTP_REQUEST ,.raw= "GET /\r\n" "\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 0 ,.http_minor= 9 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/" ,.request_url= "/" ,.num_headers= 0 ,.headers= {} ,.body= "" } #define MSEARCH_REQ 20 , {.name= "m-search request" ,.type= HTTP_REQUEST ,.raw= "M-SEARCH * HTTP/1.1\r\n" "HOST: 239.255.255.250:1900\r\n" "MAN: \"ssdp:discover\"\r\n" "ST: \"ssdp:all\"\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_MSEARCH ,.query_string= "" ,.fragment= "" ,.request_path= "*" ,.request_url= "*" ,.num_headers= 3 ,.headers= { { "HOST", "239.255.255.250:1900" } , { "MAN", "\"ssdp:discover\"" } , { "ST", "\"ssdp:all\"" } } ,.body= "" } #define LINE_FOLDING_IN_HEADER 21 , {.name= "line folding in header value" ,.type= HTTP_REQUEST ,.raw= "GET / HTTP/1.1\r\n" "Line1: abc\r\n" "\tdef\r\n" " ghi\r\n" "\t\tjkl\r\n" " mno \r\n" "\t \tqrs\r\n" "Line2: \t line2\t\r\n" "Line3:\r\n" " line3\r\n" "Line4: \r\n" " \r\n" "Connection:\r\n" " close\r\n" "\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/" ,.request_url= "/" ,.num_headers= 5 ,.headers= { { "Line1", "abc\tdef ghi\t\tjkl mno \t \tqrs" } , { "Line2", "line2\t" } , { "Line3", "line3" } , { "Line4", "" } , { "Connection", "close" }, } ,.body= "" } #define QUERY_TERMINATED_HOST 22 , {.name= "host terminated by a query string" ,.type= HTTP_REQUEST ,.raw= "GET http://hypnotoad.org?hail=all HTTP/1.1\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "hail=all" ,.fragment= "" ,.request_path= "" ,.request_url= "http://hypnotoad.org?hail=all" ,.host= "hypnotoad.org" ,.num_headers= 0 ,.headers= { } ,.body= "" } #define QUERY_TERMINATED_HOSTPORT 23 , {.name= "host:port terminated by a query string" ,.type= HTTP_REQUEST ,.raw= "GET http://hypnotoad.org:1234?hail=all HTTP/1.1\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "hail=all" ,.fragment= "" ,.request_path= "" ,.request_url= "http://hypnotoad.org:1234?hail=all" ,.host= "hypnotoad.org" ,.port= 1234 ,.num_headers= 0 ,.headers= { } ,.body= "" } #define SPACE_TERMINATED_HOSTPORT 24 , {.name= "host:port terminated by a space" ,.type= HTTP_REQUEST ,.raw= "GET http://hypnotoad.org:1234 HTTP/1.1\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "" ,.request_url= "http://hypnotoad.org:1234" ,.host= "hypnotoad.org" ,.port= 1234 ,.num_headers= 0 ,.headers= { } ,.body= "" } #define PATCH_REQ 25 , {.name = "PATCH request" ,.type= HTTP_REQUEST ,.raw= "PATCH /file.txt HTTP/1.1\r\n" "Host: www.example.com\r\n" "Content-Type: application/example\r\n" "If-Match: \"e0023aa4e\"\r\n" "Content-Length: 10\r\n" "\r\n" "cccccccccc" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_PATCH ,.query_string= "" ,.fragment= "" ,.request_path= "/file.txt" ,.request_url= "/file.txt" ,.num_headers= 4 ,.headers= { { "Host", "www.example.com" } , { "Content-Type", "application/example" } , { "If-Match", "\"e0023aa4e\"" } , { "Content-Length", "10" } } ,.body= "cccccccccc" } #define CONNECT_CAPS_REQUEST 26 , {.name = "connect caps request" ,.type= HTTP_REQUEST ,.raw= "CONNECT HOME0.NETSCAPE.COM:443 HTTP/1.0\r\n" "User-agent: Mozilla/1.1N\r\n" "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" "\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 0 ,.method= HTTP_CONNECT ,.query_string= "" ,.fragment= "" ,.request_path= "" ,.request_url= "HOME0.NETSCAPE.COM:443" ,.num_headers= 2 ,.upgrade="" ,.headers= { { "User-agent", "Mozilla/1.1N" } , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } } ,.body= "" } #if !HTTP_PARSER_STRICT #define UTF8_PATH_REQ 27 , {.name= "utf-8 path request" ,.type= HTTP_REQUEST ,.raw= "GET /δ¶/δt/pope?q=1#narf HTTP/1.1\r\n" "Host: github.com\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "q=1" ,.fragment= "narf" ,.request_path= "/δ¶/δt/pope" ,.request_url= "/δ¶/δt/pope?q=1#narf" ,.num_headers= 1 ,.headers= { {"Host", "github.com" } } ,.body= "" } #define HOSTNAME_UNDERSCORE 28 , {.name = "hostname underscore" ,.type= HTTP_REQUEST ,.raw= "CONNECT home_0.netscape.com:443 HTTP/1.0\r\n" "User-agent: Mozilla/1.1N\r\n" "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" "\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 0 ,.method= HTTP_CONNECT ,.query_string= "" ,.fragment= "" ,.request_path= "" ,.request_url= "home_0.netscape.com:443" ,.num_headers= 2 ,.upgrade="" ,.headers= { { "User-agent", "Mozilla/1.1N" } , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } } ,.body= "" } #endif /* !HTTP_PARSER_STRICT */ /* see https://github.com/ry/http-parser/issues/47 */ #define EAT_TRAILING_CRLF_NO_CONNECTION_CLOSE 29 , {.name = "eat CRLF between requests, no \"Connection: close\" header" ,.raw= "POST / HTTP/1.1\r\n" "Host: www.example.com\r\n" "Content-Type: application/x-www-form-urlencoded\r\n" "Content-Length: 4\r\n" "\r\n" "q=42\r\n" /* note the trailing CRLF */ ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_POST ,.query_string= "" ,.fragment= "" ,.request_path= "/" ,.request_url= "/" ,.num_headers= 3 ,.upgrade= 0 ,.headers= { { "Host", "www.example.com" } , { "Content-Type", "application/x-www-form-urlencoded" } , { "Content-Length", "4" } } ,.body= "q=42" } /* see https://github.com/ry/http-parser/issues/47 */ #define EAT_TRAILING_CRLF_WITH_CONNECTION_CLOSE 30 , {.name = "eat CRLF between requests even if \"Connection: close\" is set" ,.raw= "POST / HTTP/1.1\r\n" "Host: www.example.com\r\n" "Content-Type: application/x-www-form-urlencoded\r\n" "Content-Length: 4\r\n" "Connection: close\r\n" "\r\n" "q=42\r\n" /* note the trailing CRLF */ ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE /* input buffer isn't empty when on_message_complete is called */ ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_POST ,.query_string= "" ,.fragment= "" ,.request_path= "/" ,.request_url= "/" ,.num_headers= 4 ,.upgrade= 0 ,.headers= { { "Host", "www.example.com" } , { "Content-Type", "application/x-www-form-urlencoded" } , { "Content-Length", "4" } , { "Connection", "close" } } ,.body= "q=42" } #define PURGE_REQ 31 , {.name = "PURGE request" ,.type= HTTP_REQUEST ,.raw= "PURGE /file.txt HTTP/1.1\r\n" "Host: www.example.com\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_PURGE ,.query_string= "" ,.fragment= "" ,.request_path= "/file.txt" ,.request_url= "/file.txt" ,.num_headers= 1 ,.headers= { { "Host", "www.example.com" } } ,.body= "" } #define SEARCH_REQ 32 , {.name = "SEARCH request" ,.type= HTTP_REQUEST ,.raw= "SEARCH / HTTP/1.1\r\n" "Host: www.example.com\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_SEARCH ,.query_string= "" ,.fragment= "" ,.request_path= "/" ,.request_url= "/" ,.num_headers= 1 ,.headers= { { "Host", "www.example.com" } } ,.body= "" } #define PROXY_WITH_BASIC_AUTH 33 , {.name= "host:port and basic_auth" ,.type= HTTP_REQUEST ,.raw= "GET http://a%12:b!&*$@hypnotoad.org:1234/toto HTTP/1.1\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.fragment= "" ,.request_path= "/toto" ,.request_url= "http://a%12:b!&*$@hypnotoad.org:1234/toto" ,.host= "hypnotoad.org" ,.userinfo= "a%12:b!&*$" ,.port= 1234 ,.num_headers= 0 ,.headers= { } ,.body= "" } #define LINE_FOLDING_IN_HEADER_WITH_LF 34 , {.name= "line folding in header value" ,.type= HTTP_REQUEST ,.raw= "GET / HTTP/1.1\n" "Line1: abc\n" "\tdef\n" " ghi\n" "\t\tjkl\n" " mno \n" "\t \tqrs\n" "Line2: \t line2\t\n" "Line3:\n" " line3\n" "Line4: \n" " \n" "Connection:\n" " close\n" "\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/" ,.request_url= "/" ,.num_headers= 5 ,.headers= { { "Line1", "abc\tdef ghi\t\tjkl mno \t \tqrs" } , { "Line2", "line2\t" } , { "Line3", "line3" } , { "Line4", "" } , { "Connection", "close" }, } ,.body= "" } #define CONNECTION_MULTI 35 , {.name = "multiple connection header values with folding" ,.type= HTTP_REQUEST ,.raw= "GET /demo HTTP/1.1\r\n" "Host: example.com\r\n" "Connection: Something,\r\n" " Upgrade, ,Keep-Alive\r\n" "Sec-WebSocket-Key2: 12998 5 Y3 1 .P00\r\n" "Sec-WebSocket-Protocol: sample\r\n" "Upgrade: WebSocket\r\n" "Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5\r\n" "Origin: http://example.com\r\n" "\r\n" "Hot diggity dogg" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/demo" ,.request_url= "/demo" ,.num_headers= 7 ,.upgrade="Hot diggity dogg" ,.headers= { { "Host", "example.com" } , { "Connection", "Something, Upgrade, ,Keep-Alive" } , { "Sec-WebSocket-Key2", "12998 5 Y3 1 .P00" } , { "Sec-WebSocket-Protocol", "sample" } , { "Upgrade", "WebSocket" } , { "Sec-WebSocket-Key1", "4 @1 46546xW%0l 1 5" } , { "Origin", "http://example.com" } } ,.body= "" } #define CONNECTION_MULTI_LWS 36 , {.name = "multiple connection header values with folding and lws" ,.type= HTTP_REQUEST ,.raw= "GET /demo HTTP/1.1\r\n" "Connection: keep-alive, upgrade\r\n" "Upgrade: WebSocket\r\n" "\r\n" "Hot diggity dogg" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/demo" ,.request_url= "/demo" ,.num_headers= 2 ,.upgrade="Hot diggity dogg" ,.headers= { { "Connection", "keep-alive, upgrade" } , { "Upgrade", "WebSocket" } } ,.body= "" } #define CONNECTION_MULTI_LWS_CRLF 37 , {.name = "multiple connection header values with folding and lws" ,.type= HTTP_REQUEST ,.raw= "GET /demo HTTP/1.1\r\n" "Connection: keep-alive, \r\n upgrade\r\n" "Upgrade: WebSocket\r\n" "\r\n" "Hot diggity dogg" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" ,.request_path= "/demo" ,.request_url= "/demo" ,.num_headers= 2 ,.upgrade="Hot diggity dogg" ,.headers= { { "Connection", "keep-alive, upgrade" } , { "Upgrade", "WebSocket" } } ,.body= "" } #define UPGRADE_POST_REQUEST 38 , {.name = "upgrade post request" ,.type= HTTP_REQUEST ,.raw= "POST /demo HTTP/1.1\r\n" "Host: example.com\r\n" "Connection: Upgrade\r\n" "Upgrade: HTTP/2.0\r\n" "Content-Length: 15\r\n" "\r\n" "sweet post body" "Hot diggity dogg" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.method= HTTP_POST ,.request_path= "/demo" ,.request_url= "/demo" ,.num_headers= 4 ,.upgrade="Hot diggity dogg" ,.headers= { { "Host", "example.com" } , { "Connection", "Upgrade" } , { "Upgrade", "HTTP/2.0" } , { "Content-Length", "15" } } ,.body= "sweet post body" } #define CONNECT_WITH_BODY_REQUEST 39 , {.name = "connect with body request" ,.type= HTTP_REQUEST ,.raw= "CONNECT foo.bar.com:443 HTTP/1.0\r\n" "User-agent: Mozilla/1.1N\r\n" "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" "Content-Length: 10\r\n" "\r\n" "blarfcicle" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 0 ,.method= HTTP_CONNECT ,.request_url= "foo.bar.com:443" ,.num_headers= 3 ,.upgrade="blarfcicle" ,.headers= { { "User-agent", "Mozilla/1.1N" } , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } , { "Content-Length", "10" } } ,.body= "" } , {.name= NULL } /* sentinel */ }; /* * R E S P O N S E S * */ const struct message responses[] = #define GOOGLE_301 0 { {.name= "google 301" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 301 Moved Permanently\r\n" "Location: http://www.google.com/\r\n" "Content-Type: text/html; charset=UTF-8\r\n" "Date: Sun, 26 Apr 2009 11:11:49 GMT\r\n" "Expires: Tue, 26 May 2009 11:11:49 GMT\r\n" "X-$PrototypeBI-Version: 1.6.0.3\r\n" /* $ char in header field */ "Cache-Control: public, max-age=2592000\r\n" "Server: gws\r\n" "Content-Length: 219 \r\n" "\r\n" "\n" "301 Moved\n" "

301 Moved

\n" "The document has moved\n" "here.\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 301 ,.response_status= "Moved Permanently" ,.num_headers= 8 ,.headers= { { "Location", "http://www.google.com/" } , { "Content-Type", "text/html; charset=UTF-8" } , { "Date", "Sun, 26 Apr 2009 11:11:49 GMT" } , { "Expires", "Tue, 26 May 2009 11:11:49 GMT" } , { "X-$PrototypeBI-Version", "1.6.0.3" } , { "Cache-Control", "public, max-age=2592000" } , { "Server", "gws" } , { "Content-Length", "219 " } } ,.body= "\n" "301 Moved\n" "

301 Moved

\n" "The document has moved\n" "here.\r\n" "\r\n" } #define NO_CONTENT_LENGTH_RESPONSE 1 /* The client should wait for the server's EOF. That is, when content-length * is not specified, and "Connection: close", the end of body is specified * by the EOF. * Compare with APACHEBENCH_GET */ , {.name= "no content-length response" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 OK\r\n" "Date: Tue, 04 Aug 2009 07:59:32 GMT\r\n" "Server: Apache\r\n" "X-Powered-By: Servlet/2.5 JSP/2.1\r\n" "Content-Type: text/xml; charset=utf-8\r\n" "Connection: close\r\n" "\r\n" "\n" "\n" " \n" " \n" " SOAP-ENV:Client\n" " Client Error\n" " \n" " \n" "" ,.should_keep_alive= FALSE ,.message_complete_on_eof= TRUE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 5 ,.headers= { { "Date", "Tue, 04 Aug 2009 07:59:32 GMT" } , { "Server", "Apache" } , { "X-Powered-By", "Servlet/2.5 JSP/2.1" } , { "Content-Type", "text/xml; charset=utf-8" } , { "Connection", "close" } } ,.body= "\n" "\n" " \n" " \n" " SOAP-ENV:Client\n" " Client Error\n" " \n" " \n" "" } #define NO_HEADERS_NO_BODY_404 2 , {.name= "404 no headers no body" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 404 Not Found\r\n\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= TRUE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 404 ,.response_status= "Not Found" ,.num_headers= 0 ,.headers= {} ,.body_size= 0 ,.body= "" } #define NO_REASON_PHRASE 3 , {.name= "301 no response phrase" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 301\r\n\r\n" ,.should_keep_alive = FALSE ,.message_complete_on_eof= TRUE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 301 ,.response_status= "" ,.num_headers= 0 ,.headers= {} ,.body= "" } #define TRAILING_SPACE_ON_CHUNKED_BODY 4 , {.name="200 trailing space on chunked body" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "25 \r\n" "This is the data in the first chunk\r\n" "\r\n" "1C\r\n" "and this is the second one\r\n" "\r\n" "0 \r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 2 ,.headers= { {"Content-Type", "text/plain" } , {"Transfer-Encoding", "chunked" } } ,.body_size = 37+28 ,.body = "This is the data in the first chunk\r\n" "and this is the second one\r\n" ,.num_chunks_complete= 3 ,.chunk_lengths= { 0x25, 0x1c } } #define NO_CARRIAGE_RET 5 , {.name="no carriage ret" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 OK\n" "Content-Type: text/html; charset=utf-8\n" "Connection: close\n" "\n" "these headers are from http://news.ycombinator.com/" ,.should_keep_alive= FALSE ,.message_complete_on_eof= TRUE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 2 ,.headers= { {"Content-Type", "text/html; charset=utf-8" } , {"Connection", "close" } } ,.body= "these headers are from http://news.ycombinator.com/" } #define PROXY_CONNECTION 6 , {.name="proxy connection" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n" "Content-Length: 11\r\n" "Proxy-Connection: close\r\n" "Date: Thu, 31 Dec 2009 20:55:48 +0000\r\n" "\r\n" "hello world" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 4 ,.headers= { {"Content-Type", "text/html; charset=UTF-8" } , {"Content-Length", "11" } , {"Proxy-Connection", "close" } , {"Date", "Thu, 31 Dec 2009 20:55:48 +0000"} } ,.body= "hello world" } #define UNDERSTORE_HEADER_KEY 7 // shown by // curl -o /dev/null -v "http://ad.doubleclick.net/pfadx/DARTSHELLCONFIGXML;dcmt=text/xml;" , {.name="underscore header key" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 OK\r\n" "Server: DCLK-AdSvr\r\n" "Content-Type: text/xml\r\n" "Content-Length: 0\r\n" "DCLK_imp: v7;x;114750856;0-0;0;17820020;0/0;21603567/21621457/1;;~okv=;dcmt=text/xml;;~cs=o\r\n\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 4 ,.headers= { {"Server", "DCLK-AdSvr" } , {"Content-Type", "text/xml" } , {"Content-Length", "0" } , {"DCLK_imp", "v7;x;114750856;0-0;0;17820020;0/0;21603567/21621457/1;;~okv=;dcmt=text/xml;;~cs=o" } } ,.body= "" } #define BONJOUR_MADAME_FR 8 /* The client should not merge two headers fields when the first one doesn't * have a value. */ , {.name= "bonjourmadame.fr" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.0 301 Moved Permanently\r\n" "Date: Thu, 03 Jun 2010 09:56:32 GMT\r\n" "Server: Apache/2.2.3 (Red Hat)\r\n" "Cache-Control: public\r\n" "Pragma: \r\n" "Location: http://www.bonjourmadame.fr/\r\n" "Vary: Accept-Encoding\r\n" "Content-Length: 0\r\n" "Content-Type: text/html; charset=UTF-8\r\n" "Connection: keep-alive\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 0 ,.status_code= 301 ,.response_status= "Moved Permanently" ,.num_headers= 9 ,.headers= { { "Date", "Thu, 03 Jun 2010 09:56:32 GMT" } , { "Server", "Apache/2.2.3 (Red Hat)" } , { "Cache-Control", "public" } , { "Pragma", "" } , { "Location", "http://www.bonjourmadame.fr/" } , { "Vary", "Accept-Encoding" } , { "Content-Length", "0" } , { "Content-Type", "text/html; charset=UTF-8" } , { "Connection", "keep-alive" } } ,.body= "" } #define RES_FIELD_UNDERSCORE 9 /* Should handle spaces in header fields */ , {.name= "field underscore" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 OK\r\n" "Date: Tue, 28 Sep 2010 01:14:13 GMT\r\n" "Server: Apache\r\n" "Cache-Control: no-cache, must-revalidate\r\n" "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n" ".et-Cookie: PlaxoCS=1274804622353690521; path=/; domain=.plaxo.com\r\n" "Vary: Accept-Encoding\r\n" "_eep-Alive: timeout=45\r\n" /* semantic value ignored */ "_onnection: Keep-Alive\r\n" /* semantic value ignored */ "Transfer-Encoding: chunked\r\n" "Content-Type: text/html\r\n" "Connection: close\r\n" "\r\n" "0\r\n\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 11 ,.headers= { { "Date", "Tue, 28 Sep 2010 01:14:13 GMT" } , { "Server", "Apache" } , { "Cache-Control", "no-cache, must-revalidate" } , { "Expires", "Mon, 26 Jul 1997 05:00:00 GMT" } , { ".et-Cookie", "PlaxoCS=1274804622353690521; path=/; domain=.plaxo.com" } , { "Vary", "Accept-Encoding" } , { "_eep-Alive", "timeout=45" } , { "_onnection", "Keep-Alive" } , { "Transfer-Encoding", "chunked" } , { "Content-Type", "text/html" } , { "Connection", "close" } } ,.body= "" ,.num_chunks_complete= 1 ,.chunk_lengths= {} } #define NON_ASCII_IN_STATUS_LINE 10 /* Should handle non-ASCII in status line */ , {.name= "non-ASCII in status line" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 500 Oriëntatieprobleem\r\n" "Date: Fri, 5 Nov 2010 23:07:12 GMT+2\r\n" "Content-Length: 0\r\n" "Connection: close\r\n" "\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 500 ,.response_status= "Oriëntatieprobleem" ,.num_headers= 3 ,.headers= { { "Date", "Fri, 5 Nov 2010 23:07:12 GMT+2" } , { "Content-Length", "0" } , { "Connection", "close" } } ,.body= "" } #define HTTP_VERSION_0_9 11 /* Should handle HTTP/0.9 */ , {.name= "http version 0.9" ,.type= HTTP_RESPONSE ,.raw= "HTTP/0.9 200 OK\r\n" "\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= TRUE ,.http_major= 0 ,.http_minor= 9 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 0 ,.headers= {} ,.body= "" } #define NO_CONTENT_LENGTH_NO_TRANSFER_ENCODING_RESPONSE 12 /* The client should wait for the server's EOF. That is, when neither * content-length nor transfer-encoding is specified, the end of body * is specified by the EOF. */ , {.name= "neither content-length nor transfer-encoding response" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "\r\n" "hello world" ,.should_keep_alive= FALSE ,.message_complete_on_eof= TRUE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 1 ,.headers= { { "Content-Type", "text/plain" } } ,.body= "hello world" } #define NO_BODY_HTTP10_KA_200 13 , {.name= "HTTP/1.0 with keep-alive and EOF-terminated 200 status" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.0 200 OK\r\n" "Connection: keep-alive\r\n" "\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= TRUE ,.http_major= 1 ,.http_minor= 0 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 1 ,.headers= { { "Connection", "keep-alive" } } ,.body_size= 0 ,.body= "" } #define NO_BODY_HTTP10_KA_204 14 , {.name= "HTTP/1.0 with keep-alive and a 204 status" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.0 204 No content\r\n" "Connection: keep-alive\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 0 ,.status_code= 204 ,.response_status= "No content" ,.num_headers= 1 ,.headers= { { "Connection", "keep-alive" } } ,.body_size= 0 ,.body= "" } #define NO_BODY_HTTP11_KA_200 15 , {.name= "HTTP/1.1 with an EOF-terminated 200 status" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 OK\r\n" "\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= TRUE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 0 ,.headers={} ,.body_size= 0 ,.body= "" } #define NO_BODY_HTTP11_KA_204 16 , {.name= "HTTP/1.1 with a 204 status" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 204 No content\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 204 ,.response_status= "No content" ,.num_headers= 0 ,.headers={} ,.body_size= 0 ,.body= "" } #define NO_BODY_HTTP11_NOKA_204 17 , {.name= "HTTP/1.1 with a 204 status and keep-alive disabled" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 204 No content\r\n" "Connection: close\r\n" "\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 204 ,.response_status= "No content" ,.num_headers= 1 ,.headers= { { "Connection", "close" } } ,.body_size= 0 ,.body= "" } #define NO_BODY_HTTP11_KA_CHUNKED_200 18 , {.name= "HTTP/1.1 with chunked endocing and a 200 response" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 OK\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "0\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 1 ,.headers= { { "Transfer-Encoding", "chunked" } } ,.body_size= 0 ,.body= "" ,.num_chunks_complete= 1 } #if !HTTP_PARSER_STRICT #define SPACE_IN_FIELD_RES 19 /* Should handle spaces in header fields */ , {.name= "field space" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 OK\r\n" "Server: Microsoft-IIS/6.0\r\n" "X-Powered-By: ASP.NET\r\n" "en-US Content-Type: text/xml\r\n" /* this is the problem */ "Content-Type: text/xml\r\n" "Content-Length: 16\r\n" "Date: Fri, 23 Jul 2010 18:45:38 GMT\r\n" "Connection: keep-alive\r\n" "\r\n" "hello" /* fake body */ ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 7 ,.headers= { { "Server", "Microsoft-IIS/6.0" } , { "X-Powered-By", "ASP.NET" } , { "en-US Content-Type", "text/xml" } , { "Content-Type", "text/xml" } , { "Content-Length", "16" } , { "Date", "Fri, 23 Jul 2010 18:45:38 GMT" } , { "Connection", "keep-alive" } } ,.body= "hello" } #endif /* !HTTP_PARSER_STRICT */ #define AMAZON_COM 20 , {.name= "amazon.com" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 301 MovedPermanently\r\n" "Date: Wed, 15 May 2013 17:06:33 GMT\r\n" "Server: Server\r\n" "x-amz-id-1: 0GPHKXSJQ826RK7GZEB2\r\n" "p3p: policyref=\"http://www.amazon.com/w3c/p3p.xml\",CP=\"CAO DSP LAW CUR ADM IVAo IVDo CONo OTPo OUR DELi PUBi OTRi BUS PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA HEA PRE LOC GOV OTC \"\r\n" "x-amz-id-2: STN69VZxIFSz9YJLbz1GDbxpbjG6Qjmmq5E3DxRhOUw+Et0p4hr7c/Q8qNcx4oAD\r\n" "Location: http://www.amazon.com/Dan-Brown/e/B000AP9DSU/ref=s9_pop_gw_al1?_encoding=UTF8&refinementId=618073011&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-2&pf_rd_r=0SHYY5BZXN3KR20BNFAY&pf_rd_t=101&pf_rd_p=1263340922&pf_rd_i=507846\r\n" "Vary: Accept-Encoding,User-Agent\r\n" "Content-Type: text/html; charset=ISO-8859-1\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "1\r\n" "\n\r\n" "0\r\n" "\r\n" ,.should_keep_alive= TRUE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 301 ,.response_status= "MovedPermanently" ,.num_headers= 9 ,.headers= { { "Date", "Wed, 15 May 2013 17:06:33 GMT" } , { "Server", "Server" } , { "x-amz-id-1", "0GPHKXSJQ826RK7GZEB2" } , { "p3p", "policyref=\"http://www.amazon.com/w3c/p3p.xml\",CP=\"CAO DSP LAW CUR ADM IVAo IVDo CONo OTPo OUR DELi PUBi OTRi BUS PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA HEA PRE LOC GOV OTC \"" } , { "x-amz-id-2", "STN69VZxIFSz9YJLbz1GDbxpbjG6Qjmmq5E3DxRhOUw+Et0p4hr7c/Q8qNcx4oAD" } , { "Location", "http://www.amazon.com/Dan-Brown/e/B000AP9DSU/ref=s9_pop_gw_al1?_encoding=UTF8&refinementId=618073011&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-2&pf_rd_r=0SHYY5BZXN3KR20BNFAY&pf_rd_t=101&pf_rd_p=1263340922&pf_rd_i=507846" } , { "Vary", "Accept-Encoding,User-Agent" } , { "Content-Type", "text/html; charset=ISO-8859-1" } , { "Transfer-Encoding", "chunked" } } ,.body= "\n" ,.num_chunks_complete= 2 ,.chunk_lengths= { 1 } } #define EMPTY_REASON_PHRASE_AFTER_SPACE 20 , {.name= "empty reason phrase after space" ,.type= HTTP_RESPONSE ,.raw= "HTTP/1.1 200 \r\n" "\r\n" ,.should_keep_alive= FALSE ,.message_complete_on_eof= TRUE ,.http_major= 1 ,.http_minor= 1 ,.status_code= 200 ,.response_status= "" ,.num_headers= 0 ,.headers= {} ,.body= "" } , {.name= NULL } /* sentinel */ }; /* strnlen() is a POSIX.2008 addition. Can't rely on it being available so * define it ourselves. */ size_t strnlen(const char *s, size_t maxlen) { const char *p; p = memchr(s, '\0', maxlen); if (p == NULL) return maxlen; return p - s; } size_t strlncat(char *dst, size_t len, const char *src, size_t n) { size_t slen; size_t dlen; size_t rlen; size_t ncpy; slen = strnlen(src, n); dlen = strnlen(dst, len); if (dlen < len) { rlen = len - dlen; ncpy = slen < rlen ? slen : (rlen - 1); memcpy(dst + dlen, src, ncpy); dst[dlen + ncpy] = '\0'; } assert(len > slen + dlen); return slen + dlen; } size_t strlcat(char *dst, const char *src, size_t len) { return strlncat(dst, len, src, (size_t) -1); } size_t strlncpy(char *dst, size_t len, const char *src, size_t n) { size_t slen; size_t ncpy; slen = strnlen(src, n); if (len > 0) { ncpy = slen < len ? slen : (len - 1); memcpy(dst, src, ncpy); dst[ncpy] = '\0'; } assert(len > slen); return slen; } size_t strlcpy(char *dst, const char *src, size_t len) { return strlncpy(dst, len, src, (size_t) -1); } int request_url_cb (http_parser *p, const char *buf, size_t len) { assert(p == parser); strlncat(messages[num_messages].request_url, sizeof(messages[num_messages].request_url), buf, len); return 0; } int header_field_cb (http_parser *p, const char *buf, size_t len) { assert(p == parser); struct message *m = &messages[num_messages]; if (m->last_header_element != FIELD) m->num_headers++; strlncat(m->headers[m->num_headers-1][0], sizeof(m->headers[m->num_headers-1][0]), buf, len); m->last_header_element = FIELD; return 0; } int header_value_cb (http_parser *p, const char *buf, size_t len) { assert(p == parser); struct message *m = &messages[num_messages]; strlncat(m->headers[m->num_headers-1][1], sizeof(m->headers[m->num_headers-1][1]), buf, len); m->last_header_element = VALUE; return 0; } void check_body_is_final (const http_parser *p) { if (messages[num_messages].body_is_final) { fprintf(stderr, "\n\n *** Error http_body_is_final() should return 1 " "on last on_body callback call " "but it doesn't! ***\n\n"); assert(0); abort(); } messages[num_messages].body_is_final = http_body_is_final(p); } int body_cb (http_parser *p, const char *buf, size_t len) { assert(p == parser); strlncat(messages[num_messages].body, sizeof(messages[num_messages].body), buf, len); messages[num_messages].body_size += len; check_body_is_final(p); // printf("body_cb: '%s'\n", requests[num_messages].body); return 0; } int count_body_cb (http_parser *p, const char *buf, size_t len) { assert(p == parser); assert(buf); messages[num_messages].body_size += len; check_body_is_final(p); return 0; } int message_begin_cb (http_parser *p) { assert(p == parser); messages[num_messages].message_begin_cb_called = TRUE; return 0; } int headers_complete_cb (http_parser *p) { assert(p == parser); messages[num_messages].method = parser->method; messages[num_messages].status_code = parser->status_code; messages[num_messages].http_major = parser->http_major; messages[num_messages].http_minor = parser->http_minor; messages[num_messages].headers_complete_cb_called = TRUE; messages[num_messages].should_keep_alive = http_should_keep_alive(parser); return 0; } int message_complete_cb (http_parser *p) { assert(p == parser); if (messages[num_messages].should_keep_alive != http_should_keep_alive(parser)) { fprintf(stderr, "\n\n *** Error http_should_keep_alive() should have same " "value in both on_message_complete and on_headers_complete " "but it doesn't! ***\n\n"); assert(0); abort(); } if (messages[num_messages].body_size && http_body_is_final(p) && !messages[num_messages].body_is_final) { fprintf(stderr, "\n\n *** Error http_body_is_final() should return 1 " "on last on_body callback call " "but it doesn't! ***\n\n"); assert(0); abort(); } messages[num_messages].message_complete_cb_called = TRUE; messages[num_messages].message_complete_on_eof = currently_parsing_eof; num_messages++; return 0; } int response_status_cb (http_parser *p, const char *buf, size_t len) { assert(p == parser); strlncat(messages[num_messages].response_status, sizeof(messages[num_messages].response_status), buf, len); return 0; } int chunk_header_cb (http_parser *p) { assert(p == parser); int chunk_idx = messages[num_messages].num_chunks; messages[num_messages].num_chunks++; if (chunk_idx < MAX_CHUNKS) { messages[num_messages].chunk_lengths[chunk_idx] = p->content_length; } return 0; } int chunk_complete_cb (http_parser *p) { assert(p == parser); /* Here we want to verify that each chunk_header_cb is matched by a * chunk_complete_cb, so not only should the total number of calls to * both callbacks be the same, but they also should be interleaved * properly */ assert(messages[num_messages].num_chunks == messages[num_messages].num_chunks_complete + 1); messages[num_messages].num_chunks_complete++; return 0; } /* These dontcall_* callbacks exist so that we can verify that when we're * paused, no additional callbacks are invoked */ int dontcall_message_begin_cb (http_parser *p) { if (p) { } // gcc fprintf(stderr, "\n\n*** on_message_begin() called on paused parser ***\n\n"); abort(); } int dontcall_header_field_cb (http_parser *p, const char *buf, size_t len) { if (p || buf || len) { } // gcc fprintf(stderr, "\n\n*** on_header_field() called on paused parser ***\n\n"); abort(); } int dontcall_header_value_cb (http_parser *p, const char *buf, size_t len) { if (p || buf || len) { } // gcc fprintf(stderr, "\n\n*** on_header_value() called on paused parser ***\n\n"); abort(); } int dontcall_request_url_cb (http_parser *p, const char *buf, size_t len) { if (p || buf || len) { } // gcc fprintf(stderr, "\n\n*** on_request_url() called on paused parser ***\n\n"); abort(); } int dontcall_body_cb (http_parser *p, const char *buf, size_t len) { if (p || buf || len) { } // gcc fprintf(stderr, "\n\n*** on_body_cb() called on paused parser ***\n\n"); abort(); } int dontcall_headers_complete_cb (http_parser *p) { if (p) { } // gcc fprintf(stderr, "\n\n*** on_headers_complete() called on paused " "parser ***\n\n"); abort(); } int dontcall_message_complete_cb (http_parser *p) { if (p) { } // gcc fprintf(stderr, "\n\n*** on_message_complete() called on paused " "parser ***\n\n"); abort(); } int dontcall_response_status_cb (http_parser *p, const char *buf, size_t len) { if (p || buf || len) { } // gcc fprintf(stderr, "\n\n*** on_status() called on paused parser ***\n\n"); abort(); } int dontcall_chunk_header_cb (http_parser *p) { if (p) { } // gcc fprintf(stderr, "\n\n*** on_chunk_header() called on paused parser ***\n\n"); exit(1); } int dontcall_chunk_complete_cb (http_parser *p) { if (p) { } // gcc fprintf(stderr, "\n\n*** on_chunk_complete() " "called on paused parser ***\n\n"); exit(1); } static http_parser_settings settings_dontcall = {.on_message_begin = dontcall_message_begin_cb ,.on_header_field = dontcall_header_field_cb ,.on_header_value = dontcall_header_value_cb ,.on_url = dontcall_request_url_cb ,.on_status = dontcall_response_status_cb ,.on_body = dontcall_body_cb ,.on_headers_complete = dontcall_headers_complete_cb ,.on_message_complete = dontcall_message_complete_cb ,.on_chunk_header = dontcall_chunk_header_cb ,.on_chunk_complete = dontcall_chunk_complete_cb }; /* These pause_* callbacks always pause the parser and just invoke the regular * callback that tracks content. Before returning, we overwrite the parser * settings to point to the _dontcall variety so that we can verify that * the pause actually did, you know, pause. */ int pause_message_begin_cb (http_parser *p) { http_parser_pause(p, 1); *current_pause_parser = settings_dontcall; return message_begin_cb(p); } int pause_header_field_cb (http_parser *p, const char *buf, size_t len) { http_parser_pause(p, 1); *current_pause_parser = settings_dontcall; return header_field_cb(p, buf, len); } int pause_header_value_cb (http_parser *p, const char *buf, size_t len) { http_parser_pause(p, 1); *current_pause_parser = settings_dontcall; return header_value_cb(p, buf, len); } int pause_request_url_cb (http_parser *p, const char *buf, size_t len) { http_parser_pause(p, 1); *current_pause_parser = settings_dontcall; return request_url_cb(p, buf, len); } int pause_body_cb (http_parser *p, const char *buf, size_t len) { http_parser_pause(p, 1); *current_pause_parser = settings_dontcall; return body_cb(p, buf, len); } int pause_headers_complete_cb (http_parser *p) { http_parser_pause(p, 1); *current_pause_parser = settings_dontcall; return headers_complete_cb(p); } int pause_message_complete_cb (http_parser *p) { http_parser_pause(p, 1); *current_pause_parser = settings_dontcall; return message_complete_cb(p); } int pause_response_status_cb (http_parser *p, const char *buf, size_t len) { http_parser_pause(p, 1); *current_pause_parser = settings_dontcall; return response_status_cb(p, buf, len); } int pause_chunk_header_cb (http_parser *p) { http_parser_pause(p, 1); *current_pause_parser = settings_dontcall; return chunk_header_cb(p); } int pause_chunk_complete_cb (http_parser *p) { http_parser_pause(p, 1); *current_pause_parser = settings_dontcall; return chunk_complete_cb(p); } static http_parser_settings settings_pause = {.on_message_begin = pause_message_begin_cb ,.on_header_field = pause_header_field_cb ,.on_header_value = pause_header_value_cb ,.on_url = pause_request_url_cb ,.on_status = pause_response_status_cb ,.on_body = pause_body_cb ,.on_headers_complete = pause_headers_complete_cb ,.on_message_complete = pause_message_complete_cb ,.on_chunk_header = pause_chunk_header_cb ,.on_chunk_complete = pause_chunk_complete_cb }; static http_parser_settings settings = {.on_message_begin = message_begin_cb ,.on_header_field = header_field_cb ,.on_header_value = header_value_cb ,.on_url = request_url_cb ,.on_status = response_status_cb ,.on_body = body_cb ,.on_headers_complete = headers_complete_cb ,.on_message_complete = message_complete_cb ,.on_chunk_header = chunk_header_cb ,.on_chunk_complete = chunk_complete_cb }; static http_parser_settings settings_count_body = {.on_message_begin = message_begin_cb ,.on_header_field = header_field_cb ,.on_header_value = header_value_cb ,.on_url = request_url_cb ,.on_status = response_status_cb ,.on_body = count_body_cb ,.on_headers_complete = headers_complete_cb ,.on_message_complete = message_complete_cb ,.on_chunk_header = chunk_header_cb ,.on_chunk_complete = chunk_complete_cb }; static http_parser_settings settings_null = {.on_message_begin = 0 ,.on_header_field = 0 ,.on_header_value = 0 ,.on_url = 0 ,.on_status = 0 ,.on_body = 0 ,.on_headers_complete = 0 ,.on_message_complete = 0 ,.on_chunk_header = 0 ,.on_chunk_complete = 0 }; void parser_init (enum http_parser_type type) { num_messages = 0; assert(parser == NULL); parser = malloc(sizeof(http_parser)); http_parser_init(parser, type); memset(&messages, 0, sizeof messages); } void parser_free () { assert(parser); free(parser); parser = NULL; } size_t parse (const char *buf, size_t len) { size_t nparsed; currently_parsing_eof = (len == 0); nparsed = http_parser_execute(parser, &settings, buf, len); return nparsed; } size_t parse_count_body (const char *buf, size_t len) { size_t nparsed; currently_parsing_eof = (len == 0); nparsed = http_parser_execute(parser, &settings_count_body, buf, len); return nparsed; } size_t parse_pause (const char *buf, size_t len) { size_t nparsed; http_parser_settings s = settings_pause; currently_parsing_eof = (len == 0); current_pause_parser = &s; nparsed = http_parser_execute(parser, current_pause_parser, buf, len); return nparsed; } static inline int check_str_eq (const struct message *m, const char *prop, const char *expected, const char *found) { if ((expected == NULL) != (found == NULL)) { printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name); printf("expected %s\n", (expected == NULL) ? "NULL" : expected); printf(" found %s\n", (found == NULL) ? "NULL" : found); return 0; } if (expected != NULL && 0 != strcmp(expected, found)) { printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name); printf("expected '%s'\n", expected); printf(" found '%s'\n", found); return 0; } return 1; } static inline int check_num_eq (const struct message *m, const char *prop, int expected, int found) { if (expected != found) { printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name); printf("expected %d\n", expected); printf(" found %d\n", found); return 0; } return 1; } #define MESSAGE_CHECK_STR_EQ(expected, found, prop) \ if (!check_str_eq(expected, #prop, expected->prop, found->prop)) return 0 #define MESSAGE_CHECK_NUM_EQ(expected, found, prop) \ if (!check_num_eq(expected, #prop, expected->prop, found->prop)) return 0 #define MESSAGE_CHECK_URL_EQ(u, expected, found, prop, fn) \ do { \ char ubuf[256]; \ \ if ((u)->field_set & (1 << (fn))) { \ memcpy(ubuf, (found)->request_url + (u)->field_data[(fn)].off, \ (u)->field_data[(fn)].len); \ ubuf[(u)->field_data[(fn)].len] = '\0'; \ } else { \ ubuf[0] = '\0'; \ } \ \ check_str_eq(expected, #prop, expected->prop, ubuf); \ } while(0) int message_eq (int index, const struct message *expected) { int i; struct message *m = &messages[index]; MESSAGE_CHECK_NUM_EQ(expected, m, http_major); MESSAGE_CHECK_NUM_EQ(expected, m, http_minor); if (expected->type == HTTP_REQUEST) { MESSAGE_CHECK_NUM_EQ(expected, m, method); } else { MESSAGE_CHECK_NUM_EQ(expected, m, status_code); MESSAGE_CHECK_STR_EQ(expected, m, response_status); } MESSAGE_CHECK_NUM_EQ(expected, m, should_keep_alive); MESSAGE_CHECK_NUM_EQ(expected, m, message_complete_on_eof); assert(m->message_begin_cb_called); assert(m->headers_complete_cb_called); assert(m->message_complete_cb_called); MESSAGE_CHECK_STR_EQ(expected, m, request_url); /* Check URL components; we can't do this w/ CONNECT since it doesn't * send us a well-formed URL. */ if (*m->request_url && m->method != HTTP_CONNECT) { struct http_parser_url u; if (http_parser_parse_url(m->request_url, strlen(m->request_url), 0, &u)) { fprintf(stderr, "\n\n*** failed to parse URL %s ***\n\n", m->request_url); abort(); } if (expected->host) { MESSAGE_CHECK_URL_EQ(&u, expected, m, host, UF_HOST); } if (expected->userinfo) { MESSAGE_CHECK_URL_EQ(&u, expected, m, userinfo, UF_USERINFO); } m->port = (u.field_set & (1 << UF_PORT)) ? u.port : 0; MESSAGE_CHECK_URL_EQ(&u, expected, m, query_string, UF_QUERY); MESSAGE_CHECK_URL_EQ(&u, expected, m, fragment, UF_FRAGMENT); MESSAGE_CHECK_URL_EQ(&u, expected, m, request_path, UF_PATH); MESSAGE_CHECK_NUM_EQ(expected, m, port); } if (expected->body_size) { MESSAGE_CHECK_NUM_EQ(expected, m, body_size); } else { MESSAGE_CHECK_STR_EQ(expected, m, body); } assert(m->num_chunks == m->num_chunks_complete); MESSAGE_CHECK_NUM_EQ(expected, m, num_chunks_complete); for (i = 0; i < m->num_chunks && i < MAX_CHUNKS; i++) { MESSAGE_CHECK_NUM_EQ(expected, m, chunk_lengths[i]); } MESSAGE_CHECK_NUM_EQ(expected, m, num_headers); int r; for (i = 0; i < m->num_headers; i++) { r = check_str_eq(expected, "header field", expected->headers[i][0], m->headers[i][0]); if (!r) return 0; r = check_str_eq(expected, "header value", expected->headers[i][1], m->headers[i][1]); if (!r) return 0; } MESSAGE_CHECK_STR_EQ(expected, m, upgrade); return 1; } /* Given a sequence of varargs messages, return the number of them that the * parser should successfully parse, taking into account that upgraded * messages prevent all subsequent messages from being parsed. */ size_t count_parsed_messages(const size_t nmsgs, ...) { size_t i; va_list ap; va_start(ap, nmsgs); for (i = 0; i < nmsgs; i++) { struct message *m = va_arg(ap, struct message *); if (m->upgrade) { va_end(ap); return i + 1; } } va_end(ap); return nmsgs; } /* Given a sequence of bytes and the number of these that we were able to * parse, verify that upgrade bodies are correct. */ void upgrade_message_fix(char *body, const size_t nread, const size_t nmsgs, ...) { va_list ap; size_t i; size_t off = 0; va_start(ap, nmsgs); for (i = 0; i < nmsgs; i++) { struct message *m = va_arg(ap, struct message *); off += strlen(m->raw); if (m->upgrade) { off -= strlen(m->upgrade); /* Check the portion of the response after its specified upgrade */ if (!check_str_eq(m, "upgrade", body + off, body + nread)) { abort(); } /* Fix up the response so that message_eq() will verify the beginning * of the upgrade */ *(body + nread + strlen(m->upgrade)) = '\0'; messages[num_messages -1 ].upgrade = body + nread; va_end(ap); return; } } va_end(ap); printf("\n\n*** Error: expected a message with upgrade ***\n"); abort(); } static void print_error (const char *raw, size_t error_location) { fprintf(stderr, "\n*** %s ***\n\n", http_errno_description(HTTP_PARSER_ERRNO(parser))); int this_line = 0, char_len = 0; size_t i, j, len = strlen(raw), error_location_line = 0; for (i = 0; i < len; i++) { if (i == error_location) this_line = 1; switch (raw[i]) { case '\r': char_len = 2; fprintf(stderr, "\\r"); break; case '\n': fprintf(stderr, "\\n\n"); if (this_line) goto print; error_location_line = 0; continue; default: char_len = 1; fputc(raw[i], stderr); break; } if (!this_line) error_location_line += char_len; } fprintf(stderr, "[eof]\n"); print: for (j = 0; j < error_location_line; j++) { fputc(' ', stderr); } fprintf(stderr, "^\n\nerror location: %u\n", (unsigned int)error_location); } void test_preserve_data (void) { char my_data[] = "application-specific data"; http_parser parser; parser.data = my_data; http_parser_init(&parser, HTTP_REQUEST); if (parser.data != my_data) { printf("\n*** parser.data not preserved accross http_parser_init ***\n\n"); abort(); } } struct url_test { const char *name; const char *url; int is_connect; struct http_parser_url u; int rv; }; const struct url_test url_tests[] = { {.name="proxy request" ,.url="http://hostname/" ,.is_connect=0 ,.u= {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PATH) ,.port=0 ,.field_data= {{ 0, 4 } /* UF_SCHEMA */ ,{ 7, 8 } /* UF_HOST */ ,{ 0, 0 } /* UF_PORT */ ,{ 15, 1 } /* UF_PATH */ ,{ 0, 0 } /* UF_QUERY */ ,{ 0, 0 } /* UF_FRAGMENT */ ,{ 0, 0 } /* UF_USERINFO */ } } ,.rv=0 } , {.name="proxy request with port" ,.url="http://hostname:444/" ,.is_connect=0 ,.u= {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PORT) | (1 << UF_PATH) ,.port=444 ,.field_data= {{ 0, 4 } /* UF_SCHEMA */ ,{ 7, 8 } /* UF_HOST */ ,{ 16, 3 } /* UF_PORT */ ,{ 19, 1 } /* UF_PATH */ ,{ 0, 0 } /* UF_QUERY */ ,{ 0, 0 } /* UF_FRAGMENT */ ,{ 0, 0 } /* UF_USERINFO */ } } ,.rv=0 } , {.name="CONNECT request" ,.url="hostname:443" ,.is_connect=1 ,.u= {.field_set=(1 << UF_HOST) | (1 << UF_PORT) ,.port=443 ,.field_data= {{ 0, 0 } /* UF_SCHEMA */ ,{ 0, 8 } /* UF_HOST */ ,{ 9, 3 } /* UF_PORT */ ,{ 0, 0 } /* UF_PATH */ ,{ 0, 0 } /* UF_QUERY */ ,{ 0, 0 } /* UF_FRAGMENT */ ,{ 0, 0 } /* UF_USERINFO */ } } ,.rv=0 } , {.name="CONNECT request but not connect" ,.url="hostname:443" ,.is_connect=0 ,.rv=1 } , {.name="proxy ipv6 request" ,.url="http://[1:2::3:4]/" ,.is_connect=0 ,.u= {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PATH) ,.port=0 ,.field_data= {{ 0, 4 } /* UF_SCHEMA */ ,{ 8, 8 } /* UF_HOST */ ,{ 0, 0 } /* UF_PORT */ ,{ 17, 1 } /* UF_PATH */ ,{ 0, 0 } /* UF_QUERY */ ,{ 0, 0 } /* UF_FRAGMENT */ ,{ 0, 0 } /* UF_USERINFO */ } } ,.rv=0 } , {.name="proxy ipv6 request with port" ,.url="http://[1:2::3:4]:67/" ,.is_connect=0 ,.u= {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PORT) | (1 << UF_PATH) ,.port=67 ,.field_data= {{ 0, 4 } /* UF_SCHEMA */ ,{ 8, 8 } /* UF_HOST */ ,{ 18, 2 } /* UF_PORT */ ,{ 20, 1 } /* UF_PATH */ ,{ 0, 0 } /* UF_QUERY */ ,{ 0, 0 } /* UF_FRAGMENT */ ,{ 0, 0 } /* UF_USERINFO */ } } ,.rv=0 } , {.name="CONNECT ipv6 address" ,.url="[1:2::3:4]:443" ,.is_connect=1 ,.u= {.field_set=(1 << UF_HOST) | (1 << UF_PORT) ,.port=443 ,.field_data= {{ 0, 0 } /* UF_SCHEMA */ ,{ 1, 8 } /* UF_HOST */ ,{ 11, 3 } /* UF_PORT */ ,{ 0, 0 } /* UF_PATH */ ,{ 0, 0 } /* UF_QUERY */ ,{ 0, 0 } /* UF_FRAGMENT */ ,{ 0, 0 } /* UF_USERINFO */ } } ,.rv=0 } , {.name="ipv4 in ipv6 address" ,.url="http://[2001:0000:0000:0000:0000:0000:1.9.1.1]/" ,.is_connect=0 ,.u= {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PATH) ,.port=0 ,.field_data= {{ 0, 4 } /* UF_SCHEMA */ ,{ 8, 37 } /* UF_HOST */ ,{ 0, 0 } /* UF_PORT */ ,{ 46, 1 } /* UF_PATH */ ,{ 0, 0 } /* UF_QUERY */ ,{ 0, 0 } /* UF_FRAGMENT */ ,{ 0, 0 } /* UF_USERINFO */ } } ,.rv=0 } , {.name="extra ? in query string" ,.url="http://a.tbcdn.cn/p/fp/2010c/??fp-header-min.css,fp-base-min.css," "fp-channel-min.css,fp-product-min.css,fp-mall-min.css,fp-category-min.css," "fp-sub-min.css,fp-gdp4p-min.css,fp-css3-min.css,fp-misc-min.css?t=20101022.css" ,.is_connect=0 ,.u= {.field_set=(1<field_set, u->port); for (i = 0; i < UF_MAX; i++) { if ((u->field_set & (1 << i)) == 0) { printf("\tfield_data[%u]: unset\n", i); continue; } printf("\tfield_data[%u]: off: %u len: %u part: \"%.*s\n\"", i, u->field_data[i].off, u->field_data[i].len, u->field_data[i].len, url + u->field_data[i].off); } } void test_parse_url (void) { struct http_parser_url u; const struct url_test *test; unsigned int i; int rv; for (i = 0; i < (sizeof(url_tests) / sizeof(url_tests[0])); i++) { test = &url_tests[i]; memset(&u, 0, sizeof(u)); rv = http_parser_parse_url(test->url, strlen(test->url), test->is_connect, &u); if (test->rv == 0) { if (rv != 0) { printf("\n*** http_parser_parse_url(\"%s\") \"%s\" test failed, " "unexpected rv %d ***\n\n", test->url, test->name, rv); abort(); } if (memcmp(&u, &test->u, sizeof(u)) != 0) { printf("\n*** http_parser_parse_url(\"%s\") \"%s\" failed ***\n", test->url, test->name); printf("target http_parser_url:\n"); dump_url(test->url, &test->u); printf("result http_parser_url:\n"); dump_url(test->url, &u); abort(); } } else { /* test->rv != 0 */ if (rv == 0) { printf("\n*** http_parser_parse_url(\"%s\") \"%s\" test failed, " "unexpected rv %d ***\n\n", test->url, test->name, rv); abort(); } } } } void test_method_str (void) { assert(0 == strcmp("GET", http_method_str(HTTP_GET))); assert(0 == strcmp("", http_method_str(1337))); } void test_message (const struct message *message) { size_t raw_len = strlen(message->raw); size_t msg1len; for (msg1len = 0; msg1len < raw_len; msg1len++) { parser_init(message->type); size_t read; const char *msg1 = message->raw; const char *msg2 = msg1 + msg1len; size_t msg2len = raw_len - msg1len; if (msg1len) { read = parse(msg1, msg1len); if (message->upgrade && parser->upgrade && num_messages > 0) { messages[num_messages - 1].upgrade = msg1 + read; goto test; } if (read != msg1len) { print_error(msg1, read); abort(); } } read = parse(msg2, msg2len); if (message->upgrade && parser->upgrade) { messages[num_messages - 1].upgrade = msg2 + read; goto test; } if (read != msg2len) { print_error(msg2, read); abort(); } read = parse(NULL, 0); if (read != 0) { print_error(message->raw, read); abort(); } test: if (num_messages != 1) { printf("\n*** num_messages != 1 after testing '%s' ***\n\n", message->name); abort(); } if(!message_eq(0, message)) abort(); parser_free(); } } void test_message_count_body (const struct message *message) { parser_init(message->type); size_t read; size_t l = strlen(message->raw); size_t i, toread; size_t chunk = 4024; for (i = 0; i < l; i+= chunk) { toread = MIN(l-i, chunk); read = parse_count_body(message->raw + i, toread); if (read != toread) { print_error(message->raw, read); abort(); } } read = parse_count_body(NULL, 0); if (read != 0) { print_error(message->raw, read); abort(); } if (num_messages != 1) { printf("\n*** num_messages != 1 after testing '%s' ***\n\n", message->name); abort(); } if(!message_eq(0, message)) abort(); parser_free(); } void test_simple (const char *buf, enum http_errno err_expected) { parser_init(HTTP_REQUEST); enum http_errno err; parse(buf, strlen(buf)); err = HTTP_PARSER_ERRNO(parser); parse(NULL, 0); parser_free(); /* In strict mode, allow us to pass with an unexpected HPE_STRICT as * long as the caller isn't expecting success. */ #if HTTP_PARSER_STRICT if (err_expected != err && err_expected != HPE_OK && err != HPE_STRICT) { #else if (err_expected != err) { #endif fprintf(stderr, "\n*** test_simple expected %s, but saw %s ***\n\n%s\n", http_errno_name(err_expected), http_errno_name(err), buf); abort(); } } void test_header_overflow_error (int req) { http_parser parser; http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); size_t parsed; const char *buf; buf = req ? "GET / HTTP/1.1\r\n" : "HTTP/1.0 200 OK\r\n"; parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf)); assert(parsed == strlen(buf)); buf = "header-key: header-value\r\n"; size_t buflen = strlen(buf); int i; for (i = 0; i < 10000; i++) { parsed = http_parser_execute(&parser, &settings_null, buf, buflen); if (parsed != buflen) { //fprintf(stderr, "error found on iter %d\n", i); assert(HTTP_PARSER_ERRNO(&parser) == HPE_HEADER_OVERFLOW); return; } } fprintf(stderr, "\n*** Error expected but none in header overflow test ***\n"); abort(); } void test_header_nread_value () { http_parser parser; http_parser_init(&parser, HTTP_REQUEST); size_t parsed; const char *buf; buf = "GET / HTTP/1.1\r\nheader: value\nhdr: value\r\n"; parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf)); assert(parsed == strlen(buf)); assert(parser.nread == strlen(buf)); } static void test_content_length_overflow (const char *buf, size_t buflen, int expect_ok) { http_parser parser; http_parser_init(&parser, HTTP_RESPONSE); http_parser_execute(&parser, &settings_null, buf, buflen); if (expect_ok) assert(HTTP_PARSER_ERRNO(&parser) == HPE_OK); else assert(HTTP_PARSER_ERRNO(&parser) == HPE_INVALID_CONTENT_LENGTH); } void test_header_content_length_overflow_error (void) { #define X(size) \ "HTTP/1.1 200 OK\r\n" \ "Content-Length: " #size "\r\n" \ "\r\n" const char a[] = X(1844674407370955160); /* 2^64 / 10 - 1 */ const char b[] = X(18446744073709551615); /* 2^64-1 */ const char c[] = X(18446744073709551616); /* 2^64 */ #undef X test_content_length_overflow(a, sizeof(a) - 1, 1); /* expect ok */ test_content_length_overflow(b, sizeof(b) - 1, 0); /* expect failure */ test_content_length_overflow(c, sizeof(c) - 1, 0); /* expect failure */ } void test_chunk_content_length_overflow_error (void) { #define X(size) \ "HTTP/1.1 200 OK\r\n" \ "Transfer-Encoding: chunked\r\n" \ "\r\n" \ #size "\r\n" \ "..." const char a[] = X(FFFFFFFFFFFFFFE); /* 2^64 / 16 - 1 */ const char b[] = X(FFFFFFFFFFFFFFFF); /* 2^64-1 */ const char c[] = X(10000000000000000); /* 2^64 */ #undef X test_content_length_overflow(a, sizeof(a) - 1, 1); /* expect ok */ test_content_length_overflow(b, sizeof(b) - 1, 0); /* expect failure */ test_content_length_overflow(c, sizeof(c) - 1, 0); /* expect failure */ } void test_no_overflow_long_body (int req, size_t length) { http_parser parser; http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); size_t parsed; size_t i; char buf1[3000]; size_t buf1len = sprintf(buf1, "%s\r\nConnection: Keep-Alive\r\nContent-Length: %lu\r\n\r\n", req ? "POST / HTTP/1.0" : "HTTP/1.0 200 OK", (unsigned long)length); parsed = http_parser_execute(&parser, &settings_null, buf1, buf1len); if (parsed != buf1len) goto err; for (i = 0; i < length; i++) { char foo = 'a'; parsed = http_parser_execute(&parser, &settings_null, &foo, 1); if (parsed != 1) goto err; } parsed = http_parser_execute(&parser, &settings_null, buf1, buf1len); if (parsed != buf1len) goto err; return; err: fprintf(stderr, "\n*** error in test_no_overflow_long_body %s of length %lu ***\n", req ? "REQUEST" : "RESPONSE", (unsigned long)length); abort(); } void test_multiple3 (const struct message *r1, const struct message *r2, const struct message *r3) { int message_count = count_parsed_messages(3, r1, r2, r3); char total[ strlen(r1->raw) + strlen(r2->raw) + strlen(r3->raw) + 1 ]; total[0] = '\0'; strcat(total, r1->raw); strcat(total, r2->raw); strcat(total, r3->raw); parser_init(r1->type); size_t read; read = parse(total, strlen(total)); if (parser->upgrade) { upgrade_message_fix(total, read, 3, r1, r2, r3); goto test; } if (read != strlen(total)) { print_error(total, read); abort(); } read = parse(NULL, 0); if (read != 0) { print_error(total, read); abort(); } test: if (message_count != num_messages) { fprintf(stderr, "\n\n*** Parser didn't see 3 messages only %d *** \n", num_messages); abort(); } if (!message_eq(0, r1)) abort(); if (message_count > 1 && !message_eq(1, r2)) abort(); if (message_count > 2 && !message_eq(2, r3)) abort(); parser_free(); } /* SCAN through every possible breaking to make sure the * parser can handle getting the content in any chunks that * might come from the socket */ void test_scan (const struct message *r1, const struct message *r2, const struct message *r3) { char total[80*1024] = "\0"; char buf1[80*1024] = "\0"; char buf2[80*1024] = "\0"; char buf3[80*1024] = "\0"; strcat(total, r1->raw); strcat(total, r2->raw); strcat(total, r3->raw); size_t read; int total_len = strlen(total); int total_ops = 2 * (total_len - 1) * (total_len - 2) / 2; int ops = 0 ; size_t buf1_len, buf2_len, buf3_len; int message_count = count_parsed_messages(3, r1, r2, r3); int i,j,type_both; for (type_both = 0; type_both < 2; type_both ++ ) { for (j = 2; j < total_len; j ++ ) { for (i = 1; i < j; i ++ ) { if (ops % 1000 == 0) { printf("\b\b\b\b%3.0f%%", 100 * (float)ops /(float)total_ops); fflush(stdout); } ops += 1; parser_init(type_both ? HTTP_BOTH : r1->type); buf1_len = i; strlncpy(buf1, sizeof(buf1), total, buf1_len); buf1[buf1_len] = 0; buf2_len = j - i; strlncpy(buf2, sizeof(buf1), total+i, buf2_len); buf2[buf2_len] = 0; buf3_len = total_len - j; strlncpy(buf3, sizeof(buf1), total+j, buf3_len); buf3[buf3_len] = 0; read = parse(buf1, buf1_len); if (parser->upgrade) goto test; if (read != buf1_len) { print_error(buf1, read); goto error; } read += parse(buf2, buf2_len); if (parser->upgrade) goto test; if (read != buf1_len + buf2_len) { print_error(buf2, read); goto error; } read += parse(buf3, buf3_len); if (parser->upgrade) goto test; if (read != buf1_len + buf2_len + buf3_len) { print_error(buf3, read); goto error; } parse(NULL, 0); test: if (parser->upgrade) { upgrade_message_fix(total, read, 3, r1, r2, r3); } if (message_count != num_messages) { fprintf(stderr, "\n\nParser didn't see %d messages only %d\n", message_count, num_messages); goto error; } if (!message_eq(0, r1)) { fprintf(stderr, "\n\nError matching messages[0] in test_scan.\n"); goto error; } if (message_count > 1 && !message_eq(1, r2)) { fprintf(stderr, "\n\nError matching messages[1] in test_scan.\n"); goto error; } if (message_count > 2 && !message_eq(2, r3)) { fprintf(stderr, "\n\nError matching messages[2] in test_scan.\n"); goto error; } parser_free(); } } } puts("\b\b\b\b100%"); return; error: fprintf(stderr, "i=%d j=%d\n", i, j); fprintf(stderr, "buf1 (%u) %s\n\n", (unsigned int)buf1_len, buf1); fprintf(stderr, "buf2 (%u) %s\n\n", (unsigned int)buf2_len , buf2); fprintf(stderr, "buf3 (%u) %s\n", (unsigned int)buf3_len, buf3); abort(); } // user required to free the result // string terminated by \0 char * create_large_chunked_message (int body_size_in_kb, const char* headers) { int i; size_t wrote = 0; size_t headers_len = strlen(headers); size_t bufsize = headers_len + (5+1024+2)*body_size_in_kb + 6; char * buf = malloc(bufsize); memcpy(buf, headers, headers_len); wrote += headers_len; for (i = 0; i < body_size_in_kb; i++) { // write 1kb chunk into the body. memcpy(buf + wrote, "400\r\n", 5); wrote += 5; memset(buf + wrote, 'C', 1024); wrote += 1024; strcpy(buf + wrote, "\r\n"); wrote += 2; } memcpy(buf + wrote, "0\r\n\r\n", 6); wrote += 6; assert(wrote == bufsize); return buf; } /* Verify that we can pause parsing at any of the bytes in the * message and still get the result that we're expecting. */ void test_message_pause (const struct message *msg) { char *buf = (char*) msg->raw; size_t buflen = strlen(msg->raw); size_t nread; parser_init(msg->type); do { nread = parse_pause(buf, buflen); // We can only set the upgrade buffer once we've gotten our message // completion callback. if (messages[0].message_complete_cb_called && msg->upgrade && parser->upgrade) { messages[0].upgrade = buf + nread; goto test; } if (nread < buflen) { // Not much do to if we failed a strict-mode check if (HTTP_PARSER_ERRNO(parser) == HPE_STRICT) { parser_free(); return; } assert (HTTP_PARSER_ERRNO(parser) == HPE_PAUSED); } buf += nread; buflen -= nread; http_parser_pause(parser, 0); } while (buflen > 0); nread = parse_pause(NULL, 0); assert (nread == 0); test: if (num_messages != 1) { printf("\n*** num_messages != 1 after testing '%s' ***\n\n", msg->name); abort(); } if(!message_eq(0, msg)) abort(); parser_free(); } int main (void) { parser = NULL; int i, j, k; int request_count; int response_count; unsigned long version; unsigned major; unsigned minor; unsigned patch; version = http_parser_version(); major = (version >> 16) & 255; minor = (version >> 8) & 255; patch = version & 255; printf("http_parser v%u.%u.%u (0x%06lx)\n", major, minor, patch, version); printf("sizeof(http_parser) = %u\n", (unsigned int)sizeof(http_parser)); for (request_count = 0; requests[request_count].name; request_count++); for (response_count = 0; responses[response_count].name; response_count++); //// API test_preserve_data(); test_parse_url(); test_method_str(); //// NREAD test_header_nread_value(); //// OVERFLOW CONDITIONS test_header_overflow_error(HTTP_REQUEST); test_no_overflow_long_body(HTTP_REQUEST, 1000); test_no_overflow_long_body(HTTP_REQUEST, 100000); test_header_overflow_error(HTTP_RESPONSE); test_no_overflow_long_body(HTTP_RESPONSE, 1000); test_no_overflow_long_body(HTTP_RESPONSE, 100000); test_header_content_length_overflow_error(); test_chunk_content_length_overflow_error(); //// RESPONSES for (i = 0; i < response_count; i++) { test_message(&responses[i]); } for (i = 0; i < response_count; i++) { test_message_pause(&responses[i]); } for (i = 0; i < response_count; i++) { if (!responses[i].should_keep_alive) continue; for (j = 0; j < response_count; j++) { if (!responses[j].should_keep_alive) continue; for (k = 0; k < response_count; k++) { test_multiple3(&responses[i], &responses[j], &responses[k]); } } } test_message_count_body(&responses[NO_HEADERS_NO_BODY_404]); test_message_count_body(&responses[TRAILING_SPACE_ON_CHUNKED_BODY]); // test very large chunked response { char * msg = create_large_chunked_message(31337, "HTTP/1.0 200 OK\r\n" "Transfer-Encoding: chunked\r\n" "Content-Type: text/plain\r\n" "\r\n"); struct message large_chunked = {.name= "large chunked" ,.type= HTTP_RESPONSE ,.raw= msg ,.should_keep_alive= FALSE ,.message_complete_on_eof= FALSE ,.http_major= 1 ,.http_minor= 0 ,.status_code= 200 ,.response_status= "OK" ,.num_headers= 2 ,.headers= { { "Transfer-Encoding", "chunked" } , { "Content-Type", "text/plain" } } ,.body_size= 31337*1024 ,.num_chunks_complete= 31338 }; for (i = 0; i < MAX_CHUNKS; i++) { large_chunked.chunk_lengths[i] = 1024; } test_message_count_body(&large_chunked); free(msg); } printf("response scan 1/2 "); test_scan( &responses[TRAILING_SPACE_ON_CHUNKED_BODY] , &responses[NO_BODY_HTTP10_KA_204] , &responses[NO_REASON_PHRASE] ); printf("response scan 2/2 "); test_scan( &responses[BONJOUR_MADAME_FR] , &responses[UNDERSTORE_HEADER_KEY] , &responses[NO_CARRIAGE_RET] ); puts("responses okay"); /// REQUESTS test_simple("GET / HTP/1.1\r\n\r\n", HPE_INVALID_VERSION); // Well-formed but incomplete test_simple("GET / HTTP/1.1\r\n" "Content-Type: text/plain\r\n" "Content-Length: 6\r\n" "\r\n" "fooba", HPE_OK); static const char *all_methods[] = { "DELETE", "GET", "HEAD", "POST", "PUT", //"CONNECT", //CONNECT can't be tested like other methods, it's a tunnel "OPTIONS", "TRACE", "COPY", "LOCK", "MKCOL", "MOVE", "PROPFIND", "PROPPATCH", "UNLOCK", "REPORT", "MKACTIVITY", "CHECKOUT", "MERGE", "M-SEARCH", "NOTIFY", "SUBSCRIBE", "UNSUBSCRIBE", "PATCH", 0 }; const char **this_method; for (this_method = all_methods; *this_method; this_method++) { char buf[200]; sprintf(buf, "%s / HTTP/1.1\r\n\r\n", *this_method); test_simple(buf, HPE_OK); } static const char *bad_methods[] = { "ASDF", "C******", "COLA", "GEM", "GETA", "M****", "MKCOLA", "PROPPATCHA", "PUN", "PX", "SA", "hello world", 0 }; for (this_method = bad_methods; *this_method; this_method++) { char buf[200]; sprintf(buf, "%s / HTTP/1.1\r\n\r\n", *this_method); test_simple(buf, HPE_INVALID_METHOD); } // illegal header field name line folding test_simple("GET / HTTP/1.1\r\n" "name\r\n" " : value\r\n" "\r\n", HPE_INVALID_HEADER_TOKEN); const char *dumbfuck2 = "GET / HTTP/1.1\r\n" "X-SSL-Bullshit: -----BEGIN CERTIFICATE-----\r\n" "\tMIIFbTCCBFWgAwIBAgICH4cwDQYJKoZIhvcNAQEFBQAwcDELMAkGA1UEBhMCVUsx\r\n" "\tETAPBgNVBAoTCGVTY2llbmNlMRIwEAYDVQQLEwlBdXRob3JpdHkxCzAJBgNVBAMT\r\n" "\tAkNBMS0wKwYJKoZIhvcNAQkBFh5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMu\r\n" "\tdWswHhcNMDYwNzI3MTQxMzI4WhcNMDcwNzI3MTQxMzI4WjBbMQswCQYDVQQGEwJV\r\n" "\tSzERMA8GA1UEChMIZVNjaWVuY2UxEzARBgNVBAsTCk1hbmNoZXN0ZXIxCzAJBgNV\r\n" "\tBAcTmrsogriqMWLAk1DMRcwFQYDVQQDEw5taWNoYWVsIHBhcmQYJKoZIhvcNAQEB\r\n" "\tBQADggEPADCCAQoCggEBANPEQBgl1IaKdSS1TbhF3hEXSl72G9J+WC/1R64fAcEF\r\n" "\tW51rEyFYiIeZGx/BVzwXbeBoNUK41OK65sxGuflMo5gLflbwJtHBRIEKAfVVp3YR\r\n" "\tgW7cMA/s/XKgL1GEC7rQw8lIZT8RApukCGqOVHSi/F1SiFlPDxuDfmdiNzL31+sL\r\n" "\t0iwHDdNkGjy5pyBSB8Y79dsSJtCW/iaLB0/n8Sj7HgvvZJ7x0fr+RQjYOUUfrePP\r\n" "\tu2MSpFyf+9BbC/aXgaZuiCvSR+8Snv3xApQY+fULK/xY8h8Ua51iXoQ5jrgu2SqR\r\n" "\twgA7BUi3G8LFzMBl8FRCDYGUDy7M6QaHXx1ZWIPWNKsCAwEAAaOCAiQwggIgMAwG\r\n" "\tA1UdEwEB/wQCMAAwEQYJYIZIAYb4QgHTTPAQDAgWgMA4GA1UdDwEB/wQEAwID6DAs\r\n" "\tBglghkgBhvhCAQ0EHxYdVUsgZS1TY2llbmNlIFVzZXIgQ2VydGlmaWNhdGUwHQYD\r\n" "\tVR0OBBYEFDTt/sf9PeMaZDHkUIldrDYMNTBZMIGaBgNVHSMEgZIwgY+AFAI4qxGj\r\n" "\tloCLDdMVKwiljjDastqooXSkcjBwMQswCQYDVQQGEwJVSzERMA8GA1UEChMIZVNj\r\n" "\taWVuY2UxEjAQBgNVBAsTCUF1dGhvcml0eTELMAkGA1UEAxMCQ0ExLTArBgkqhkiG\r\n" "\t9w0BCQEWHmNhLW9wZXJhdG9yQGdyaWQtc3VwcG9ydC5hYy51a4IBADApBgNVHRIE\r\n" "\tIjAggR5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMudWswGQYDVR0gBBIwEDAO\r\n" "\tBgwrBgEEAdkvAQEBAQYwPQYJYIZIAYb4QgEEBDAWLmh0dHA6Ly9jYS5ncmlkLXN1\r\n" "\tcHBvcnQuYWMudmT4sopwqlBWsvcHViL2NybC9jYWNybC5jcmwwPQYJYIZIAYb4QgEDBDAWLmh0\r\n" "\tdHA6Ly9jYS5ncmlkLXN1cHBvcnQuYWMudWsvcHViL2NybC9jYWNybC5jcmwwPwYD\r\n" "\tVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NhLmdyaWQt5hYy51ay9wdWIv\r\n" "\tY3JsL2NhY3JsLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAS/U4iiooBENGW/Hwmmd3\r\n" "\tXCy6Zrt08YjKCzGNjorT98g8uGsqYjSxv/hmi0qlnlHs+k/3Iobc3LjS5AMYr5L8\r\n" "\tUO7OSkgFFlLHQyC9JzPfmLCAugvzEbyv4Olnsr8hbxF1MbKZoQxUZtMVu29wjfXk\r\n" "\thTeApBv7eaKCWpSp7MCbvgzm74izKhu3vlDk9w6qVrxePfGgpKPqfHiOoGhFnbTK\r\n" "\twTC6o2xq5y0qZ03JonF7OJspEd3I5zKY3E+ov7/ZhW6DqT8UFvsAdjvQbXyhV8Eu\r\n" "\tYhixw1aKEPzNjNowuIseVogKOLXxWI5vAi5HgXdS0/ES5gDGsABo4fqovUKlgop3\r\n" "\tRA==\r\n" "\t-----END CERTIFICATE-----\r\n" "\r\n"; test_simple(dumbfuck2, HPE_OK); const char *corrupted_connection = "GET / HTTP/1.1\r\n" "Host: www.example.com\r\n" "Connection\r\033\065\325eep-Alive\r\n" "Accept-Encoding: gzip\r\n" "\r\n"; test_simple(corrupted_connection, HPE_INVALID_HEADER_TOKEN); const char *corrupted_header_name = "GET / HTTP/1.1\r\n" "Host: www.example.com\r\n" "X-Some-Header\r\033\065\325eep-Alive\r\n" "Accept-Encoding: gzip\r\n" "\r\n"; test_simple(corrupted_header_name, HPE_INVALID_HEADER_TOKEN); #if 0 // NOTE(Wed Nov 18 11:57:27 CET 2009) this seems okay. we just read body // until EOF. // // no content-length // error if there is a body without content length const char *bad_get_no_headers_no_body = "GET /bad_get_no_headers_no_body/world HTTP/1.1\r\n" "Accept: */*\r\n" "\r\n" "HELLO"; test_simple(bad_get_no_headers_no_body, 0); #endif /* TODO sending junk and large headers gets rejected */ /* check to make sure our predefined requests are okay */ for (i = 0; requests[i].name; i++) { test_message(&requests[i]); } for (i = 0; i < request_count; i++) { test_message_pause(&requests[i]); } for (i = 0; i < request_count; i++) { if (!requests[i].should_keep_alive) continue; for (j = 0; j < request_count; j++) { if (!requests[j].should_keep_alive) continue; for (k = 0; k < request_count; k++) { test_multiple3(&requests[i], &requests[j], &requests[k]); } } } printf("request scan 1/4 "); test_scan( &requests[GET_NO_HEADERS_NO_BODY] , &requests[GET_ONE_HEADER_NO_BODY] , &requests[GET_NO_HEADERS_NO_BODY] ); printf("request scan 2/4 "); test_scan( &requests[POST_CHUNKED_ALL_YOUR_BASE] , &requests[POST_IDENTITY_BODY_WORLD] , &requests[GET_FUNKY_CONTENT_LENGTH] ); printf("request scan 3/4 "); test_scan( &requests[TWO_CHUNKS_MULT_ZERO_END] , &requests[CHUNKED_W_TRAILING_HEADERS] , &requests[CHUNKED_W_BULLSHIT_AFTER_LENGTH] ); printf("request scan 4/4 "); test_scan( &requests[QUERY_URL_WITH_QUESTION_MARK_GET] , &requests[PREFIX_NEWLINE_GET ] , &requests[CONNECT_REQUEST] ); puts("requests okay"); return 0; } pax_global_header00006660000000000000000000000064137101204570014512gustar00rootroot0000000000000052 comment=56e328be416c32d31988644a57e18aeb959e6be2 iotjs-1.0+715/deps/jerry/000077500000000000000000000000001371012045700151005ustar00rootroot00000000000000iotjs-1.0+715/deps/jerry/.github/000077500000000000000000000000001371012045700164405ustar00rootroot00000000000000iotjs-1.0+715/deps/jerry/.github/ISSUE_TEMPLATE/000077500000000000000000000000001371012045700206235ustar00rootroot00000000000000iotjs-1.0+715/deps/jerry/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000052611371012045700233210ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve --- First of all, when reporting a bug, give the issue a descriptive title. In the body of the issue, optionally give a free-form text description of the bug. Give the context necessary for others to understand the problem. Then, provide information necessary to reproduce the bug. Omit sections that are irrelevant for the bug report, but note that information like git revision, build platform, build command, and test case are required in almost all cases. ###### JerryScript revision Identify the git hash(es) or tag(s) where the issue was observed. ###### Build platform Name the build platform. E.g., copy the output of `echo "$(lsb_release -ds) ($(uname -mrs))"` (on Linux), `echo "$(sw_vers -productName) $(sw_vers -productVersion) ($(uname -mrs))"` (on macOS), or `python -c "import platform; print(platform.platform())"` (should work everywhere). ###### Build steps Describe how to build JerryScript. Give all the necessary details of the build (e.g., environment variables, command(s), profile, command line options, etc.). E.g.: ```sh tools/build.py --clean --debug ``` Or: ```sh mkdir build && cmake -H. -Bbuild && make -C build ``` Even if the bug was originally observed when JerryScript was integrated into a larger project, try to reproduce it with as few external code as possible, preferably by building the `jerry` command line tool. ###### Build log Copy the build log if the reported issue is a build problem. Do a verbose build if necessary. Try and trim the log to relevant parts. ###### Test case Give the JavaScript input that should be passed to the engine to trigger the bug. Try and post a reduced test case that is minimally necessary to reproduce the issue. As a rule of thumb, use Markdown's fenced code block syntax for the test case. Attach the file (renamed to .txt) if the test case contains 'problematic' bytes that cannot be copied in the bug report directly. ###### Execution platform Unnecessary if the same as the build platform. ###### Execution steps List the steps that trigger the bug. E.g., if a bug is snapshot-specific: ```sh build/bin/jerry-snapshot generate -o testcase.js.snapshot testcase.js build/bin/jerry --exec-snapshot testcase.js.snapshot ``` Unnecessary if trivial (i.e., `build/bin/jerry testcase.js`). ###### Output Copy relevant output from the standard output and/or error channels. ###### Backtrace In case of a crash (assertion failure, etc.), try to copy the backtrace from a debugger at the point of failure. ###### Expected behavior Describe what should happen instead of current behavior. Unnecessary if trivial (e.g., in case of a crash, the trivial expected behavior is not to crash). iotjs-1.0+715/deps/jerry/.github/pull_request_template.md000066400000000000000000000014461371012045700234060ustar00rootroot00000000000000**PLEASE REMOVE THIS TEMPLATE BEFORE SUBMITTING** Before submitting a PR, please, make sure that: - Changes are in a separate branch, not in master. - The branch contains only one commit on top of master (if not, squash them into one commit). - The commit has a descriptive commit message with a concise title (first line). - The commit message contains `fixes #XXXX` or `closes #XXXX` to auto-close the issue(s) that the PR fixes (if any). - Tests for the changes have been added (for bug fixes / features). - Documentation has been added / updated (if applicable). - All new and existing tests passed locally (if not, fix them first and amend the commit). IMPORTANT: Please review the CONTRIBUTING.md file for detailed contributing guidelines. **PLEASE REMOVE THIS TEMPLATE BEFORE SUBMITTING** iotjs-1.0+715/deps/jerry/.github/workflows/000077500000000000000000000000001371012045700204755ustar00rootroot00000000000000iotjs-1.0+715/deps/jerry/.github/workflows/gh-actions.yml000066400000000000000000000070221371012045700232550ustar00rootroot00000000000000name: JerryScript CI on: push: branches: [ master ] pull_request: branches: [ master ] env: RUNNER: tools/run-tests.py jobs: Checks: runs-on: ubuntu-18.04 steps: - uses: actions/checkout@v1 - name: Initializtaion run: sudo apt-get install doxygen vera++ cppcheck pylint pylint python-serial -q - name: Signed-off run: $RUNNER --check-signed-off=gh-actions - name: Doxygen run: $RUNNER --check-doxygen - name: Vera++ run: $RUNNER --check-vera - name: License run: $RUNNER --check-license - name: Magic strings run: $RUNNER --check-magic-strings - name: Pylint run: $RUNNER --check-pylint - name: Cppcheck run: $RUNNER --check-cppcheck Linux_x86-64_Build_Correctness_Debugger_Tests: runs-on: ubuntu-18.04 steps: - uses: actions/checkout@v1 - name: Correctness - jerry-tests run: $RUNNER --jerry-tests -q - name: Debugger Tests run: $RUNNER --jerry-debugger -q Linux_x86_cpointer-32bit_Build_Correctness_Tests: runs-on: ubuntu-18.04 env: BUILD_OPTIONS: --buildoptions=--compile-flag=-m32,--cpointer-32bit=on -q steps: - uses: actions/checkout@v1 - name: Initializtaion run: sudo apt-get install gcc-multilib - name: Correctness - jerry-tests run: $RUNNER --jerry-tests $BUILD_OPTIONS -q OSX_x86-64_Build_Correctness_Unit_Tests: runs-on: macos-10.15 steps: - uses: actions/checkout@v1 - name: Correctness - jerry-tests run: $RUNNER --jerry-tests -q - name: Unit Tests run: $RUNNER --unittests -q Conformance_Tests_ES5_1: runs-on: ubuntu-18.04 steps: - uses: actions/checkout@v1 - name: Test262 - ES5.1 run: $RUNNER --test262 Conformance_Tests_ES2015: runs-on: ubuntu-18.04 steps: - uses: actions/checkout@v1 - name: Test262 - ES2015 run: $RUNNER --test262-es2015 update Unit_Tests: runs-on: ubuntu-18.04 steps: - uses: actions/checkout@v1 - name: Unit Tests run: $RUNNER --unittests -q ASAN_Tests: runs-on: ubuntu-18.04 env: ASAN_OPTIONS: detect_stack_use_after_return=1:check_initialization_order=true:strict_init_order=true SKIP_LIST: --skip-list=parser-oom.js,parser-oom2.js,stack-limit.js,regression-test-issue-2190.js,regression-test-issue-2258-2963.js,regression-test-issue-2448.js,regression-test-issue-2905.js,regression-test-issue-3785.js BUILD_OPTIONS: --buildoptions=--stack-limit=0,--compile-flag=-fsanitize=address,--compile-flag=-m32,--compile-flag=-fno-omit-frame-pointer,--compile-flag=-fno-common,--compile-flag=-O2,--debug,--system-allocator=on,--linker-flag=-fuse-ld=gold steps: - uses: actions/checkout@v1 - name: Initializtaion run: sudo apt-get install gcc-multilib - name: ASAN - jerry-tests run: $RUNNER --jerry-tests $SKIP_LIST $BUILD_OPTIONS -q UBSAN_Tests: runs-on: ubuntu-18.04 env: UBSAN_OPTIONS: print_stacktrace=1 SKIP_LIST: --skip-list=parser-oom.js,parser-oom2.js BUILD_OPTIONS: --buildoptions=--compile-flag=-fsanitize=undefined,--compile-flag=-m32,--compile-flag=-fno-omit-frame-pointer,--compile-flag=-fno-common,--debug,--system-allocator=on,--linker-flag=-fuse-ld=gold steps: - uses: actions/checkout@v1 - name: Initializtaion run: sudo apt-get install gcc-multilib - name: UBSAN - jerry-tests run: $RUNNER --jerry-tests $SKIP_LIST $BUILD_OPTIONS -q iotjs-1.0+715/deps/jerry/.gitignore000066400000000000000000000006351371012045700170740ustar00rootroot00000000000000# Produced files .mbedignore build/* # IDE related files nbproject *.sublime-project *.sublime-workspace .idea # Random Trash *.swp *.swo *~ core vgcore.* *.orig *.directory *.patch .tags* cscope.* __pycache__ *.pyc .DS_Store # ctags and ID database tags ID # targets jerry-targetjs.h .output targets/esp8266/output.map targets/esp8266/libs # Generated documentation docs/doxygen # Tests tests/test262/ .vs iotjs-1.0+715/deps/jerry/.travis.yml000066400000000000000000000121451371012045700172140ustar00rootroot00000000000000language: c # Default environment: Ubuntu Bionic 18.04. os: linux dist: bionic # Default job task: run tests as defined in the $OPT environment variable. # Jobs can redefine the 'script' stage in the matrix below. script: tools/run-tests.py $OPTS # All the job definitions in the matrix. matrix: include: - name: "Linux/ARM Build & Correctness Tests" env: - OPTS="--quiet --jerry-tests --toolchain=cmake/toolchain_linux_armv7l.cmake --buildoptions=--linker-flag=-static" - RUNTIME=qemu-arm-static - TIMEOUT=300 addons: apt: packages: [gcc-arm-linux-gnueabihf, libc6-dev-armhf-cross, qemu-user-static] - name: "Linux/AArch64 Native Build & Correctness Tests" arch: arm64 env: - OPTS="--quiet --jerry-tests --buildoptions=--linker-flag=-static" - TIMEOUT=300 - name: "Coverity Scan & SonarQube" env: # Declaration of the encrypted COVERITY_SCAN_TOKEN, created via the # "travis encrypt" command using the project repo's public key. - secure: "V7BdXv3FCVkFGEfKfWto6I+Sytou1zTCGyn49xurkBfKNsG/3vbkXfsbK1m6lCZxmY7W/1odpfjixpAPZgy2L4FgPZK6/UyVvC8pIFjDOubcEniN48haleSvm/ZFPLDifxDL2+VVFtK1oRYPtDBzzSoUCcfwovgk+Wy+tSBnhnyRLqO/WaI6PqFof7ECYMTRlJVjioZARVP4YmkBruIPmGDdR/3EvwowlxfuiFoPheix61ug4x3tpTBW2qWgvFjDyCZXFz4pJrBQPTAIbyKMxHcBykJjl9eR+dWAOsvE1Uw48tFOJxjKDfUttVQUPsyKFllmcCVS0fDYB5pzZOmRUPxJmox1jt8J1FY85Ri1PGY0THBPM2H7to4Yf2418Y3539epbN8p+79dwaM7e2OiJ2owukbWI7PoNqIz5DV5zxpIKsOQfeWuNLJOgsBePEIU7lz133Si/2d5W/7If46B1d+hZRBJfSYksgDqDU6G/voZkPf0K5bKe2O2BxiIW1DYk4yQ1ecZAkqGjZ8jG3zYGMG3mSF4VyuU4UGFG1Pg8fw7Ap5zuHxSVY1H9dtu4T6JQG3aj/x1omlzfw48DjgkwxVhf7Xvl3yfR7pzydYheLX3MZYtcVo7rWnglZFZoUjWDK1StbmzsvPftvwWtoDTWlzo4xeSXhahSJvJyc4U8Wc=" addons: coverity_scan: project: name: "jerryscript-project/jerryscript" description: "Ultra-lightweight JavaScript engine for the Internet of Things." notification_email: rsipka.uszeged@partner.samsung.com build_command: "tools/build.py --clean" branch_pattern: master sonarcloud: organization: "jerryscript-project" # Coverity Scan has already built the project by the time 'script' stage is reached. script: tools/check-sonarqube.sh cache: directories: - '${HOME}/.sonar/cache' - name: "Mbed OS 5/K64F Build Test" addons: apt: sources: - sourceline: ppa:team-gcc-arm-embedded/ppa packages: [gcc-arm-embedded] language: python # NOTE: only way to ensure python>=2.7.10 on Trusty image python: 3.6 install: make -f ./targets/mbedos5/Makefile.travis install script: make -f ./targets/mbedos5/Makefile.travis script - name: "Zephyr/Arduino 101 Build Test" language: python # NOTE: only way to ensure python>=2.7.10 on Trusty image python: 3.6 install: make -f ./targets/zephyr/Makefile.travis install-noapt script: make -f ./targets/zephyr/Makefile.travis script addons: apt: packages: [gperf, dfu-util, device-tree-compiler] - name: "NuttX/STM32F4 Build Test" install: make -f targets/nuttx-stm32f4/Makefile.travis install-noapt script: make -f targets/nuttx-stm32f4/Makefile.travis script addons: apt: packages: [gcc-arm-none-eabi, libnewlib-arm-none-eabi, gperf] - name: "RIOT/STM32F4 Build Test" install: make -f ./targets/riot-stm32f4/Makefile.travis install-noapt script: make -f ./targets/riot-stm32f4/Makefile.travis script compiler: clang-3.9 addons: apt: sources: - sourceline: ppa:team-gcc-arm-embedded/ppa packages: [clang-3.9, gcc-arm-embedded, gcc-multilib] - name: "ESP8266 Build Test" install: make -f ./targets/esp8266/Makefile.travis install-noapt script: make -f ./targets/esp8266/Makefile.travis script addons: apt: packages: [wget] fast_finish: true # The channel name "chat.freenode.net#jerryscript" # is encrypted against Samsung/jerryscript # to prevent IRC spam of forks. # # travis encrypt -r "Samsung/jerryscript" "chat.freenode.net#jerryscript" notifications: irc: channels: - secure: "4kML4uZywOPaT3r/bHCvZCeQWooyzZumESmKuHG2Y8/B29WtMBobsoRQZRfOmlUP5kshfjh0Itp5WFpdACiBCoorHch/8z3VT7fIbKF4UnxrAvNiFArqxXC0OWGIu93e7uyyXJCsQ/JiOXU7bD31Mh8LbnfS1z3wBAMXi+AwcaGiVVH4VTL6O8sR3ij5WmsqpECWhyWTgTP3MiLquZ+09Lv9mp5GGciEemq4p8VnaQt2BdyEBmUJJ1EAyMCJlKNObQudegOzYsY3CVON9C87dCuHf7DYstsxb8AzwRAKn8LHiaWhYaWLfvHqoXmc4w1ZgN0HZ5Qyx8KMkZkXKUiHxuCSoXDxNAHWTGQBsTDid5drZeqOFucOHEKJzkqaWSUKUF3pY/hq/h2kjAn230DlBNkJt+ikSxwy6Mm8GG8LnH5gRMl37zHDHrtyRsKR8GIst9B1B95LAOLA5t8U/ucGKXqLsohS8glXaM4jjh69it3GeHj6NhB8NbC/LsmRrhjKzV+VnjPI6gZvN+5tDiuxMbsMal+0DdWVNCst/aO3Jz0iaA5ahyo2ZwBb2efw3CekRLMKmHtnjqB0SWWXT3/t2+5zNoM6gBjo4RPOg7k5eTOXcfk8okWtQ5d3n8UtvZ5rSiDl3rssHwp1yHuuC8rGGov74DLvyDlpM6p/dmtu2o8=" on_success: always on_failure: always use_notice: true template: - "%{repository_name} (%{branch}@%{commit}): %{author} - %{commit_subject} [%{result}]" - "Commit: %{compare_url}" - "Build: %{build_url}" iotjs-1.0+715/deps/jerry/CMakeLists.txt000066400000000000000000000213001371012045700176340ustar00rootroot00000000000000# Copyright JS Foundation and other contributors, http://js.foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. cmake_minimum_required (VERSION 2.8.12) project (Jerry C) # Determining platform set(PLATFORM "${CMAKE_SYSTEM_NAME}") string(TOUPPER "${PLATFORM}" PLATFORM) # Determining compiler if(CMAKE_C_COMPILER_ID MATCHES "GNU") set(USING_GCC 1) endif() if(CMAKE_C_COMPILER_ID MATCHES "Clang") set(USING_CLANG 1) endif() if(CMAKE_C_COMPILER_ID MATCHES "TI") set(USING_TI 1) endif() if(CMAKE_C_COMPILER_ID MATCHES "MSVC") set(USING_MSVC 1) endif() # Determining build type if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "MinSizeRel") endif() # Optional components set(JERRY_CMDLINE ON CACHE BOOL "Build jerry command line tool?") set(JERRY_CMDLINE_TEST OFF CACHE BOOL "Build jerry test command line tool?") set(JERRY_CMDLINE_SNAPSHOT OFF CACHE BOOL "Build jerry snapshot command line tool?") set(JERRY_LIBFUZZER OFF CACHE BOOL "Build jerry with libfuzzer support?") set(JERRY_PORT_DEFAULT ON CACHE BOOL "Build default jerry port implementation?") set(JERRY_EXT ON CACHE BOOL "Build jerry-ext?") set(JERRY_LIBM ON CACHE BOOL "Build and use jerry-libm?") set(UNITTESTS OFF CACHE BOOL "Build unit tests?") set(DOCTESTS OFF CACHE BOOL "Build doc tests?") # Optional build settings set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build shared libraries?") set(ENABLE_LTO ON CACHE BOOL "Enable LTO build?") set(ENABLE_STRIP ON CACHE BOOL "Enable stripping all symbols from release binary?") # Option overrides if(NOT USING_CLANG) set(JERRY_LIBFUZZER OFF) set(JERRY_LIBFUZZER_MESSAGE " (FORCED BY COMPILER)") endif() if(JERRY_CMDLINE OR JERRY_CMDLINE_TEST OR JERRY_CMDLINE_SNAPSHOT OR JERRY_LIBFUZZER OR UNITTESTS OR DOCTESTS) set(JERRY_PORT_DEFAULT ON) set(JERRY_PORT_DEFAULT_MESSAGE " (FORCED BY CMDLINE OR LIBFUZZER OR TESTS)") endif() if(JERRY_CMDLINE OR DOCTESTS) set(JERRY_EXT ON) set(JERRY_EXT_MESSAGE " (FORCED BY CMDLINE OR TESTS)") endif() if("${PLATFORM}" STREQUAL "DARWIN") set(JERRY_LIBM OFF) set(ENABLE_LTO OFF) set(ENABLE_STRIP OFF) set(JERRY_LIBM_MESSAGE " (FORCED BY PLATFORM)") set(ENABLE_LTO_MESSAGE " (FORCED BY PLATFORM)") set(ENABLE_STRIP_MESSAGE " (FORCED BY PLATFORM)") endif() if(USING_TI) set(ENABLE_STRIP OFF) set(ENABLE_STRIP_MESSAGE " (FORCED BY COMPILER)") endif() if(USING_MSVC) set(JERRY_LIBM OFF) set(ENABLE_STRIP OFF) set(JERRY_LIBM_MESSAGE " (FORCED BY COMPILER)") set(ENABLE_STRIP_MESSAGE " (FORCED BY COMPILER)") endif() if(CYGWIN OR MINGW OR MSYS) set(ENABLE_LTO OFF) set(ENABLE_LTO_MESSAGE " (FORCED BY PLATFORM)") endif() # Status messages message(STATUS "CMAKE_BUILD_TYPE " ${CMAKE_BUILD_TYPE}) message(STATUS "CMAKE_C_COMPILER_ID " ${CMAKE_C_COMPILER_ID}) message(STATUS "CMAKE_SYSTEM_NAME " ${CMAKE_SYSTEM_NAME}) message(STATUS "CMAKE_SYSTEM_PROCESSOR " ${CMAKE_SYSTEM_PROCESSOR}) message(STATUS "BUILD_SHARED_LIBS " ${BUILD_SHARED_LIBS}) message(STATUS "ENABLE_LTO " ${ENABLE_LTO} ${ENABLE_LTO_MESSAGE}) message(STATUS "ENABLE_STRIP " ${ENABLE_STRIP} ${ENABLE_STRIP_MESSAGE}) message(STATUS "JERRY_CMDLINE " ${JERRY_CMDLINE} ${JERRY_CMDLINE_MESSAGE}) message(STATUS "JERRY_CMDLINE_TEST " ${JERRY_CMDLINE_TEST} ${JERRY_CMDLINE_TEST_MESSAGE}) message(STATUS "JERRY_CMDLINE_SNAPSHOT " ${JERRY_CMDLINE_SNAPSHOT} ${JERRY_CMDLINE_SNAPSHOT_MESSAGE}) message(STATUS "JERRY_LIBFUZZER " ${JERRY_LIBFUZZER} ${JERRY_LIBFUZZER_MESSAGE}) message(STATUS "JERRY_PORT_DEFAULT " ${JERRY_PORT_DEFAULT} ${JERRY_PORT_DEFAULT_MESSAGE}) message(STATUS "JERRY_EXT " ${JERRY_EXT} ${JERRY_EXT_MESSAGE}) message(STATUS "JERRY_LIBM " ${JERRY_LIBM} ${JERRY_LIBM_MESSAGE}) message(STATUS "UNITTESTS " ${UNITTESTS}) message(STATUS "DOCTESTS " ${DOCTESTS}) # Setup directories # Note: This mimics a conventional file system layout in the build directory for # the sake of convenient location of build artefacts. Proper installation to # traditional locations is also supported, e.g., to /usr/local. set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/") set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/") set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/") # Remove rdynamic option set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS ) # Compile/link flags # Helper macros macro(jerry_add_flags VAR) foreach(_flag ${ARGN}) set(${VAR} "${${VAR}} ${_flag}") endforeach() endmacro() macro(jerry_add_compile_flags) jerry_add_flags(CMAKE_C_FLAGS ${ARGV}) endmacro() macro(jerry_add_compile_warnings) foreach(_warning ${ARGV}) jerry_add_compile_flags(-W${_warning}) jerry_add_compile_flags(-Werror=${_warning}) endforeach() endmacro() macro(jerry_add_link_flags) jerry_add_flags(LINKER_FLAGS_COMMON ${ARGV}) endmacro() # Architecture-specific compile/link flags jerry_add_compile_flags(${FLAGS_COMMON_ARCH}) jerry_add_flags(CMAKE_EXE_LINKER_FLAGS ${FLAGS_COMMON_ARCH}) # LTO if(ENABLE_LTO) if(USING_GCC OR USING_CLANG) jerry_add_compile_flags(-flto) jerry_add_link_flags(-flto) endif() if(USING_GCC) jerry_add_compile_flags(-fno-fat-lto-objects) # Use gcc-ar and gcc-ranlib to support LTO set(CMAKE_AR "gcc-ar") set(CMAKE_RANLIB "gcc-ranlib") endif() if(USING_TI) jerry_add_link_flags(-lto) endif() endif() # Compiler / Linker flags if("${PLATFORM}" STREQUAL "DARWIN") jerry_add_link_flags(-lSystem) set(CMAKE_C_ARCHIVE_CREATE " Sqc ") set(CMAKE_C_ARCHIVE_FINISH " -no_warning_for_no_symbols -c ") set(CMAKE_SHARED_LINKER_FLAGS "-undefined dynamic_lookup") elseif((NOT CYGWIN AND NOT MINGW AND NOT MSYS) AND (USING_GCC OR USING_CLANG)) jerry_add_link_flags(-Wl,-z,noexecstack) endif() if(USING_GCC OR USING_CLANG) jerry_add_compile_flags(-std=c99 -pedantic) # Turn off stack protector jerry_add_compile_flags(-fno-builtin -fno-stack-protector) jerry_add_compile_warnings(all extra format-nonliteral init-self conversion sign-conversion format-security missing-declarations shadow strict-prototypes undef old-style-definition) jerry_add_compile_flags(-Wno-stack-protector -Wno-attributes -Werror) endif() if(USING_GCC) jerry_add_compile_warnings(logical-op) # TODO: Remove workaround for gcc 7 bug if the fallthrough comment detection is fixed. if(CMAKE_C_COMPILER_VERSION VERSION_GREATER 7.0) jerry_add_compile_flags(-Wno-implicit-fallthrough) endif() endif() if(USING_CLANG) jerry_add_compile_flags(-Wno-nested-anon-types -Wno-static-in-inline) endif() if(USING_TI) jerry_add_compile_flags(--c99) endif() if(USING_MSVC) jerry_add_link_flags(/OPT:NOREF) # Disable MSVC warning 4996 globally because it stops us from using standard C functions. jerry_add_compile_flags(/wd4996) endif() if(JERRY_LIBFUZZER) jerry_add_compile_flags(-fsanitize=fuzzer-no-link) endif() # Strip binary if(ENABLE_STRIP AND NOT CMAKE_BUILD_TYPE STREQUAL "Debug") jerry_add_link_flags(-s) endif() # External compiler & linker flags if(DEFINED EXTERNAL_COMPILE_FLAGS) jerry_add_compile_flags(${EXTERNAL_COMPILE_FLAGS}) endif() if(DEFINED EXTERNAL_LINKER_FLAGS) jerry_add_link_flags(${EXTERNAL_LINKER_FLAGS}) endif() # Used for placeholder to attach single source build targets add_custom_target(generate-single-source) # Jerry's libm if(JERRY_LIBM) add_subdirectory(jerry-libm) endif() # Jerry's core add_subdirectory(jerry-core) # Jerry's extension tools if(JERRY_EXT) add_subdirectory(jerry-ext) endif() # Jerry's default port implementation if(JERRY_PORT_DEFAULT) add_subdirectory(jerry-port/default) endif() # Jerry command line tool if(JERRY_CMDLINE OR JERRY_CMDLINE_TEST OR JERRY_CMDLINE_SNAPSHOT OR JERRY_LIBFUZZER) add_subdirectory(jerry-main) endif() # Unittests if(UNITTESTS) add_subdirectory(tests/unit-core) if(JERRY_LIBM) add_subdirectory(tests/unit-libm) endif() if(JERRY_EXT) add_subdirectory(tests/unit-ext) endif() endif() # Doctests if(DOCTESTS) add_subdirectory(tests/unit-doc) endif() iotjs-1.0+715/deps/jerry/CONTRIBUTING.md000066400000000000000000000146261371012045700173420ustar00rootroot00000000000000# Contribution Guidelines ## Patch Submission Process The following guidelines on the submission process are provided to help you be more effective when submitting code to the JerryScript 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 JerryScript 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 the root cause is much easier for you and the Maintainers and Committers. Additionally, smaller patches are much more likely to be accepted. ### 2. Ensure all files have a proper license header and copyright notice Any code that you want to contribute to the project must be licensed under the [Apache License 2.0](LICENSE). Contributions under a different license can not be accepted. Each file should start with the following header: ```c /* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ``` Adding copyright notices other than the project-wide notice ("Copyright JS Foundation and other contributors, http://js.foundation") is not permitted. The only exception is adding third-party code which requires copyright notices to be preserved. Adding third-party code to the project generally requires a strong justification. ### 3. Sign your work with the JerryScript [Developer's Certificate of Origin](DCO.md) The sign-off is a simple line at the end of the commit message of 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. 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. You should use your real name and email address in the format below: > JerryScript-DCO-1.0-Signed-off-by: Random J Developer random@developer.example.org "JerryScript-DCO-1.0-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 JerryScript [Developer's Certificate of Origin](DCO.md). **Code without a proper signoff cannot be merged into the mainline.** ### 4. Open a GitHub [pull request](https://github.com/jerryscript-project/jerryscript/pulls) You can find instructions about opening a pull request [here](https://help.github.com/articles/creating-a-pull-request). ### 5. 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 from 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. ### 6. 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 through comments guided by 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 (note that only Maintainers can give binding review scores). 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](https://guides.github.com/activities/forking) the GitHub repository and clone it locally * Connect your local repository to the original upstream repository by adding it as a remote * Create a [branch](https://guides.github.com/introduction/flow) for your edits * 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 the GitHub [fork syncing](https://help.github.com/articles/syncing-a-fork) guidelines. ## How to add the DCO line to every single commit automatically It is easy to forget adding the DCO line to the end of every commit message. Fortunately there is a nice way to do it automatically. Once you've cloned 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) if "Signed-off-by" not in content: f.write("\n\nJerryScript-DCO-1.0-Signed-off-by: \n%s" % content) else: f.write(content) ``` Please refer [Git Hooks](http://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) for more information. iotjs-1.0+715/deps/jerry/DCO.md000066400000000000000000000034671371012045700160410ustar00rootroot00000000000000# JerryScript Developer's Certificate of Origin The JerryScript 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. 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 the commit message of every patch. You should use your real name and email address in the format below: > JerryScript-DCO-1.0-Signed-off-by: Random J Developer random@developer.example.org "JerryScript-DCO-1.0-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.** iotjs-1.0+715/deps/jerry/Doxyfile000066400000000000000000003146601371012045700166200ustar00rootroot00000000000000# Doxyfile 1.8.9.1 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a double hash (##) is considered a comment and is placed in # front of the TAG it is preceding. # # All text after a single hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists, items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (\" \"). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all text # before the first occurrence of this tag. Doxygen uses libiconv (or the iconv # built into libc) for the transcoding. See http://www.gnu.org/software/libiconv # for the list of possible encodings. # The default value is: UTF-8. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded by # double-quotes, unless you are using Doxywizard) that should identify the # project for which the documentation is generated. This name is used in the # title of most generated pages and in a few other places. # The default value is: My Project. PROJECT_NAME = "JerryScript" # The PROJECT_NUMBER tag can be used to enter a project or revision number. This # could be handy for archiving the generated documentation or if some version # control system is used. PROJECT_NUMBER = # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = "JavaScript Engine for Internet of Things" # With the PROJECT_LOGO tag one can specify a logo or an icon that is included # in the documentation. The maximum height of the logo should not exceed 55 # pixels and the maximum width should not exceed 200 pixels. Doxygen will copy # the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path # into which the generated documentation will be written. If a relative path is # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. OUTPUT_DIRECTORY = "docs/doxygen" # If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- # directories (in 2 levels) under the output directory of each output format and # will distribute the generated files over these directories. Enabling this # option can be useful when feeding doxygen a huge amount of source files, where # putting all generated files in the same directory would otherwise causes # performance problems for the file system. # The default value is: NO. CREATE_SUBDIRS = NO # If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII # characters to appear in the names of generated files. If set to NO, non-ASCII # characters will be escaped, for example _xE3_x81_x84 will be used for Unicode # U+3044. # The default value is: NO. # ALLOW_UNICODE_NAMES = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, # Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), # Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, # Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), # Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, # Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, # Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, # Ukrainian and Vietnamese. # The default value is: English. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member # descriptions after the members that are listed in the file and class # documentation (similar to Javadoc). Set to NO to disable this. # The default value is: YES. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief # description of a member or function before the detailed description # # Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. # The default value is: YES. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator that is # used to form the text in various listings. Each string in this list, if found # as the leading text of the brief description, will be stripped from the text # and the result, after processing the whole list, is used as the annotated # text. Otherwise, the brief description is used as-is. If left blank, the # following values are used ($name is automatically replaced with the name of # the entity):The $name class, The $name widget, The $name file, is, provides, # specifies, contains, represents, a, an and the. ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # doxygen will generate a detailed section even if there is only a brief # description. # The default value is: NO. ALWAYS_DETAILED_SEC = YES # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. # The default value is: NO. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path # before files name in the file list and in the header files. If set to NO the # shortest path that makes the file name unique will be used # The default value is: YES. FULL_PATH_NAMES = YES # The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. # Stripping is only done if one of the specified strings matches the left-hand # part of the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the path to # strip. # # Note that you can specify absolute paths here, but also relative paths, which # will be relative from the directory where doxygen is started. # This tag requires that the tag FULL_PATH_NAMES is set to YES. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # path mentioned in the documentation of a class, which tells the reader which # header file to include in order to use a class. If left blank only the name of # the header file containing the class definition is used. Otherwise one should # specify the list of include paths that are normally passed to the compiler # using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but # less readable) file names. This can be useful is your file systems doesn't # support long names like on DOS, Mac, or CD-ROM. # The default value is: NO. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the # first line (until the first dot) of a Javadoc-style comment as the brief # description. If set to NO, the Javadoc-style will behave just like regular Qt- # style comments (thus requiring an explicit @brief command for a brief # description.) # The default value is: NO. JAVADOC_AUTOBRIEF = YES # If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first # line (until the first dot) of a Qt-style comment as the brief description. If # set to NO, the Qt-style will behave just like regular Qt-style comments (thus # requiring an explicit \brief command for a brief description.) # The default value is: NO. QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a # multi-line C++ special comment block (i.e. a block of //! or /// comments) as # a brief description. This used to be the default behavior. The new default is # to treat a multi-line C++ comment block as a detailed description. Set this # tag to YES if you prefer the old behavior instead. # # Note that setting this tag to YES also means that rational rose comments are # not recognized any more. # The default value is: NO. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the # documentation from any documented member that it re-implements. # The default value is: YES. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new # page for each member. If set to NO, the documentation of a member will be part # of the file/class/namespace that contains it. # The default value is: NO. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen # uses this value to replace tabs by spaces in code fragments. # Minimum value: 1, maximum value: 16, default value: 4. TAB_SIZE = 2 # This tag can be used to specify a number of aliases that act as commands in # the documentation. An alias has the form: # name=value # For example adding # "sideeffect=@par Side Effects:\n" # will allow you to put the command \sideeffect (or @sideeffect) in the # documentation, which will result in a user-defined paragraph with heading # "Side Effects:". You can put \n's in the value part of an alias to insert # newlines. ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding "class=itcl::class" # will allow you to use the command class in the itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. For # instance, some of the names that are used will be different. The list of all # members will be omitted, etc. # The default value is: NO. OPTIMIZE_OUTPUT_FOR_C = YES # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or # Python sources only. Doxygen will then generate output that is more tailored # for that language. For instance, namespaces will be presented as packages, # qualified scopes will look different, etc. # The default value is: NO. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources. Doxygen will then generate output that is tailored for Fortran. # The default value is: NO. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for VHDL. # The default value is: NO. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, and # language is one of the parsers supported by doxygen: IDL, Java, Javascript, # C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: # FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: # Fortran. In the later case the parser tries to guess whether the code is fixed # or free formatted code, this is the default for Fortran type files), VHDL. For # instance to make doxygen treat .inc files as Fortran files (default is PHP), # and .f files as C (default is Fortran), use: inc=Fortran f=C. # # Note: For files without extension you can use no_extension as a placeholder. # # Note that for custom extensions you also need to set FILE_PATTERNS otherwise # the files are not read by doxygen. EXTENSION_MAPPING = # If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments # according to the Markdown format, which allows for more readable # documentation. See http://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you can # mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in # case of backward compatibilities issues. # The default value is: YES. MARKDOWN_SUPPORT = YES # When enabled doxygen tries to link words that correspond to documented # classes, or namespaces to their corresponding documentation. Such a link can # be prevented in individual cases by putting a % sign in front of the word or # globally by setting AUTOLINK_SUPPORT to NO. # The default value is: YES. AUTOLINK_SUPPORT = YES # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should set this # tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); # versus func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. # The default value is: NO. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. # The default value is: NO. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip (see: # http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen # will parse them like normal C++ but will assume all classes use public instead # of private inheritance when no explicit protection keyword is present. # The default value is: NO. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate # getter and setter methods for a property. Setting this option to YES will make # doxygen to replace the get and set methods by a property in the documentation. # This will only work if the methods are indeed getting or setting a simple # type. If this is not the case, or you want to show the methods anyway, you # should set this option to NO. # The default value is: YES. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. # The default value is: NO. DISTRIBUTE_GROUP_DOC = YES # Set the SUBGROUPING tag to YES to allow class member groups of the same type # (for instance a group of public functions) to be put as a subgroup of that # type (e.g. under the Public Functions section). Set it to NO to prevent # subgrouping. Alternatively, this can be done per class using the # \nosubgrouping command. # The default value is: YES. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions # are shown inside the group in which they are included (e.g. using \ingroup) # instead of on a separate page (for HTML and Man pages) or section (for LaTeX # and RTF). # # Note that this feature does not work in combination with # SEPARATE_MEMBER_PAGES. # The default value is: NO. INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions # with only public data fields or simple typedef fields will be shown inline in # the documentation of the scope in which they are defined (i.e. file, # namespace, or group documentation), provided this scope is documented. If set # to NO, structs, classes, and unions are shown on a separate page (for HTML and # Man pages) or section (for LaTeX and RTF). # The default value is: NO. INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or # enum is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically be # useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. # The default value is: NO. TYPEDEF_HIDES_STRUCT = NO # The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This # cache is used to resolve symbols given their name and scope. Since this can be # an expensive process and often the same symbol appears multiple times in the # code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small # doxygen will become slower. If the cache is too large, memory is wasted. The # cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range # is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 # symbols. At the end of a run doxygen will report the cache usage and suggest # the optimal cache size from a speed point of view. # Minimum value: 0, maximum value: 9, default value: 0. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in # documentation are documented, even if no documentation was available. Private # class members and static file members will be hidden unless the # EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. # Note: This will also disable the warnings about undocumented members that are # normally produced when WARNINGS is set to YES. # The default value is: NO. EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will # be included in the documentation. # The default value is: NO. EXTRACT_PRIVATE = YES # If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal # scope will be included in the documentation. # The default value is: NO. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES, all static members of a file will be # included in the documentation. # The default value is: NO. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined # locally in source files will be included in the documentation. If set to NO, # only classes defined in header files are included. Does not have any effect # for Java sources. # The default value is: YES. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. If set to YES, local methods, # which are defined in the implementation section but not in the interface are # included in the documentation. If set to NO, only methods in the interface are # included. # The default value is: NO. EXTRACT_LOCAL_METHODS = YES # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base name of # the file that contains the anonymous namespace. By default anonymous namespace # are hidden. # The default value is: NO. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all # undocumented members inside documented classes or files. If set to NO these # members will be included in the various overviews, but no documentation # section is generated. This option has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. If set # to NO, these classes will be included in the various overviews. This option # has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend # (class|struct|union) declarations. If set to NO, these declarations will be # included in the documentation. # The default value is: NO. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any # documentation blocks found inside the body of a function. If set to NO, these # blocks will be appended to the function's detailed documentation block. # The default value is: NO. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation that is typed after a # \internal command is included. If the tag is set to NO then the documentation # will be excluded. Set it to YES to include the internal documentation. # The default value is: NO. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file # names in lower-case letters. If set to YES, upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. # The default value is: system dependent. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with # their full class and namespace scopes in the documentation. If set to YES, the # scope will be hidden. # The default value is: NO. HIDE_SCOPE_NAMES = NO # If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will # append additional text to a page's title, such as Class Reference. If set to # YES the compound reference will be hidden. # The default value is: NO. # HIDE_COMPOUND_REFERENCE= NO # If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of # the files that are included by a file in the documentation of that file. # The default value is: YES. SHOW_INCLUDE_FILES = YES # If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each # grouped member an include statement to the documentation, telling the reader # which file to include in order to use the member. # The default value is: NO. SHOW_GROUPED_MEMB_INC = NO # If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include # files with double quotes in the documentation rather than with sharp brackets. # The default value is: NO. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the # documentation for inline members. # The default value is: YES. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the # (detailed) documentation of file and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. # The default value is: YES. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief # descriptions of file, namespace and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. Note that # this will also influence the order of the classes in the class list. # The default value is: NO. SORT_BRIEF_DOCS = YES # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the # (brief and detailed) documentation of class members so that constructors and # destructors are listed first. If set to NO the constructors will appear in the # respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. # Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief # member documentation. # Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting # detailed member documentation. # The default value is: NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy # of group names into alphabetical order. If set to NO the group names will # appear in their defined order. # The default value is: NO. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by # fully-qualified names, including namespaces. If set to NO, the class list will # be sorted only by class name, not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the alphabetical # list. # The default value is: NO. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper # type resolution of all parameters of a function it will reject a match between # the prototype and the implementation of a member function even if there is # only one candidate or it is obvious which candidate to choose by doing a # simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still # accept a match between prototype and implementation in such cases. # The default value is: NO. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo # list. This list is created by putting \todo commands in the documentation. # The default value is: YES. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test # list. This list is created by putting \test commands in the documentation. # The default value is: YES. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug # list. This list is created by putting \bug commands in the documentation. # The default value is: YES. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) # the deprecated list. This list is created by putting \deprecated commands in # the documentation. # The default value is: YES. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional documentation # sections, marked by \if ... \endif and \cond # ... \endcond blocks. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the # initial value of a variable or macro / define can have for it to appear in the # documentation. If the initializer consists of more lines than specified here # it will be hidden. Use a value of 0 to hide initializers completely. The # appearance of the value of individual variables and macros / defines can be # controlled using \showinitializer or \hideinitializer command in the # documentation regardless of this setting. # Minimum value: 0, maximum value: 10000, default value: 30. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated at # the bottom of the documentation of classes and structs. If set to YES, the # list will mention the files that were used to generate the documentation. # The default value is: YES. SHOW_USED_FILES = YES # Set the SHOW_FILES tag to NO to disable the generation of the Files page. This # will remove the Files entry from the Quick Index and from the Folder Tree View # (if specified). # The default value is: YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces # page. This will remove the Namespaces entry from the Quick Index and from the # Folder Tree View (if specified). # The default value is: YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command command input-file, where command is the value of the # FILE_VERSION_FILTER tag, and input-file is the name of an input file provided # by doxygen. Whatever the program writes to standard output is used as the file # version. For an example see the documentation. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. You can # optionally specify a file name after the option, if omitted DoxygenLayout.xml # will be used as the name of the layout file. # # Note that if you run doxygen from a directory containing a file called # DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE # tag is left empty. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files containing # the reference definitions. This must be a list of .bib files. The .bib # extension is automatically appended if omitted. This requires the bibtex tool # to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. # For LaTeX the style of the bibliography can be controlled using # LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the # search path. See also \cite for info how to create references. CITE_BIB_FILES = #--------------------------------------------------------------------------- # Configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated to # standard output by doxygen. If QUIET is set to YES this implies that the # messages are off. # The default value is: NO. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated to standard error (stderr) by doxygen. If WARNINGS is set to YES # this implies that the warnings are on. # # Tip: Turn warnings on while writing the documentation. # The default value is: YES. WARNINGS = YES # If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate # warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag # will automatically be disabled. # The default value is: YES. WARN_IF_UNDOCUMENTED = YES # If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some parameters # in a documented function, or documenting parameters that don't exist or using # markup commands wrongly. # The default value is: YES. WARN_IF_DOC_ERROR = YES # This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that # are documented, but have no documentation for their parameters or return # value. If set to NO, doxygen will only warn about wrong or incomplete # parameter documentation, but not about the absence of documentation. # The default value is: NO. WARN_NO_PARAMDOC = YES # The WARN_FORMAT tag determines the format of the warning messages that doxygen # can produce. The string should contain the $file, $line, and $text tags, which # will be replaced by the file and line number from which the warning originated # and the warning text. Optionally the format may contain $version, which will # be replaced by the version of the file (if it could be obtained via # FILE_VERSION_FILTER) # The default value is: $file:$line: $text. WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning and error # messages should be written. If left blank the output is written to standard # error (stderr). WARN_LOGFILE = #--------------------------------------------------------------------------- # Configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag is used to specify the files and/or directories that contain # documented source files. You may enter file names like myfile.cpp or # directories like /usr/src/myproject. Separate the files or directories with # spaces. # Note: If this tag is empty the current directory is searched. INPUT = jerry-core jerry-ext jerry-port # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses # libiconv (or the iconv built into libc) for the transcoding. See the libiconv # documentation (see: http://www.gnu.org/software/libiconv) for the list of # possible encodings. # The default value is: UTF-8. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and # *.h) to filter out the source-files in the directories. If left blank the # following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii, # *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, # *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, # *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, # *.qsf, *.as and *.js. FILE_PATTERNS = *.h *.c # The RECURSIVE tag can be used to specify whether or not subdirectories should # be searched for input files as well. # The default value is: NO. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # # Note that relative paths are relative to the directory from which doxygen is # run. # FIXME: None of these files are excluded light-heartedly. They should be # removed one-by-one and warnings reported by doxygen should be fixed by those # who are familiar with the undocumented parts. EXCLUDE = \ jerry-core/ecma/base/ecma-globals.h \ jerry-core/ecma/operations/ecma-exceptions.h \ jerry-core/include/jerryscript-debugger-transport.h \ jerry-core/jcontext/jcontext.h \ jerry-core/parser/js/byte-code.h \ jerry-core/parser/js/common.h \ jerry-core/parser/js/js-lexer.h \ jerry-core/parser/js/js-parser-internal.h \ jerry-core/parser/regexp/re-parser.h \ jerry-core/vm/vm-stack.h # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. # The default value is: NO. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories for example use the pattern */test/* EXCLUDE_PATTERNS = *.inc.h # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories use the pattern */test/* EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or directories # that contain example code fragments that are included (see the \include # command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and # *.h) to filter out the source-files in the directories. If left blank all # files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude commands # irrespective of the value of the RECURSIVE tag. # The default value is: NO. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or directories # that contain images that are to be included in the documentation (see the # \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command: # # # # where is the value of the INPUT_FILTER tag, and is the # name of an input file. Doxygen will then use the output that the filter # program writes to standard output. If FILTER_PATTERNS is specified, this tag # will be ignored. # # Note that the filter must not add or remove lines; it is applied before the # code is scanned, but not when the output code is generated. If lines are added # or removed, the anchors will not be placed correctly. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the # filter if there is a match. The filters are a list of the form: pattern=filter # (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how # filters are used. If the FILTER_PATTERNS tag is empty or if none of the # patterns match the file name, INPUT_FILTER is applied. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will also be used to filter the input files that are used for # producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). # The default value is: NO. FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) and # it is also possible to disable source filtering for a specific pattern using # *.ext= (so without naming a filter). # This tag requires that the tag FILTER_SOURCE_FILES is set to YES. FILTER_SOURCE_PATTERNS = # If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. USE_MDFILE_AS_MAINPAGE = #--------------------------------------------------------------------------- # Configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will be # generated. Documented entities will be cross-referenced with these sources. # # Note: To get rid of all source code in the generated output, make sure that # also VERBATIM_HEADERS is set to NO. # The default value is: NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body of functions, # classes and enums directly into the documentation. # The default value is: NO. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any # special comment blocks from generated source code fragments. Normal C, C++ and # Fortran comments will always remain visible. # The default value is: YES. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES then for each documented # function all documented functions referencing it will be listed. # The default value is: NO. REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES then for each documented function # all documented entities called/used by that function will be listed. # The default value is: NO. REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set # to YES then the hyperlinks from functions in REFERENCES_RELATION and # REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will # link to the documentation. # The default value is: YES. REFERENCES_LINK_SOURCE = YES # If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the # source code will show a tooltip with additional information such as prototype, # brief description and links to the definition and documentation. Since this # will make the HTML file larger and loading of large files a bit slower, you # can opt to disable this feature. # The default value is: YES. # This tag requires that the tag SOURCE_BROWSER is set to YES. SOURCE_TOOLTIPS = YES # If the USE_HTAGS tag is set to YES then the references to source code will # point to the HTML generated by the htags(1) tool instead of doxygen built-in # source browser. The htags tool is part of GNU's global source tagging system # (see http://www.gnu.org/software/global/global.html). You will need version # 4.8.6 or higher. # # To use it do the following: # - Install the latest version of global # - Enable SOURCE_BROWSER and USE_HTAGS in the config file # - Make sure the INPUT points to the root of the source tree # - Run doxygen as normal # # Doxygen will invoke htags (and that will in turn invoke gtags), so these # tools must be available from the command line (i.e. in the search path). # # The result: instead of the source browser generated by doxygen, the links to # source code will now point to the output of htags. # The default value is: NO. # This tag requires that the tag SOURCE_BROWSER is set to YES. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a # verbatim copy of the header file for each class for which an include is # specified. Set to NO to disable this. # See also: Section \class. # The default value is: YES. VERBATIM_HEADERS = YES # If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the # clang parser (see: http://clang.llvm.org/) for more accurate parsing at the # cost of reduced performance. This can be particularly helpful with template # rich C++ code for which doxygen's built-in parser lacks the necessary type # information. # Note: The availability of this option depends on whether or not doxygen was # compiled with the --with-libclang option. # The default value is: NO. # CLANG_ASSISTED_PARSING = NO # If clang assisted parsing is enabled you can provide the compiler with command # line options that you would normally use when invoking the compiler. Note that # the include paths will already be set by doxygen for the files and directories # specified with INPUT and INCLUDE_PATH. # This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. # CLANG_OPTIONS = #--------------------------------------------------------------------------- # Configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all # compounds will be generated. Enable this if the project contains a lot of # classes, structs, unions or interfaces. # The default value is: YES. ALPHABETICAL_INDEX = YES # The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in # which the alphabetical index list will be split. # Minimum value: 1, maximum value: 20, default value: 5. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all classes will # be put under the same header in the alphabetical index. The IGNORE_PREFIX tag # can be used to specify a prefix (or a list of prefixes) that should be ignored # while generating the index headers. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. IGNORE_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output # The default value is: YES. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for each # generated HTML page (for example: .htm, .php, .asp). # The default value is: .html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a user-defined HTML header file for # each generated HTML page. If the tag is left blank doxygen will generate a # standard header. # # To get valid HTML the header file that includes any scripts and style sheets # that doxygen needs, which is dependent on the configuration options used (e.g. # the setting GENERATE_TREEVIEW). It is highly recommended to start with a # default header using # doxygen -w html new_header.html new_footer.html new_stylesheet.css # YourConfigFile # and then modify the file new_header.html. See also section "Doxygen usage" # for information on how to generate the default header that doxygen normally # uses. # Note: The header is subject to change so you typically have to regenerate the # default header when upgrading to a newer version of doxygen. For a description # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard # footer. See HTML_HEADER for more information on how to generate a default # footer and what special commands can be used inside the footer. See also # section "Doxygen usage" for information on how to generate the default footer # that doxygen normally uses. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading style # sheet that is used by each HTML page. It can be used to fine-tune the look of # the HTML output. If left blank doxygen will generate a default style sheet. # See also section "Doxygen usage" for information on how to generate the style # sheet that doxygen normally uses. # Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as # it is more robust and this tag (HTML_STYLESHEET) will in the future become # obsolete. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined # cascading style sheets that are included after the standard style sheets # created by doxygen. Using this option one can overrule certain style aspects. # This is preferred over using HTML_STYLESHEET since it does not replace the # standard style sheet and is therefore more robust against future updates. # Doxygen will copy the style sheet files to the output directory. # Note: The order of the extra style sheet files is of importance (e.g. the last # style sheet in the list overrules the setting of the previous ones in the # list). For an example see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that the # files will be copied as-is; there are no commands or markers available. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen # will adjust the colors in the style sheet and background images according to # this color. Hue is specified as an angle on a colorwheel, see # http://en.wikipedia.org/wiki/Hue for more information. For instance the value # 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 # purple, and 360 is red again. # Minimum value: 0, maximum value: 359, default value: 220. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors # in the HTML output. For a value of 0 the output will use grayscales only. A # value of 255 will produce the most vivid colors. # Minimum value: 0, maximum value: 255, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the # luminance component of the colors in the HTML output. Values below 100 # gradually make the output lighter, whereas values above 100 make the output # darker. The value divided by 100 is the actual gamma applied, so 80 represents # a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not # change the gamma. # Minimum value: 40, maximum value: 240, default value: 80. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting this # to YES can help to show when doxygen was last run and thus if the # documentation is up to date. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_TIMESTAMP = NO # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_DYNAMIC_SECTIONS = YES # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries # shown in the various tree structured indices initially; the user can expand # and collapse entries dynamically later on. Doxygen will expand the tree to # such a level that at most the specified number of entries are visible (unless # a fully collapsed tree already exceeds this amount). So setting the number of # entries 1 will produce a full collapsed tree by default. 0 is a special value # representing an infinite number of entries and will result in a full expanded # tree by default. # Minimum value: 0, maximum value: 9999, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_INDEX_NUM_ENTRIES = 100 # If the GENERATE_DOCSET tag is set to YES, additional index files will be # generated that can be used as input for Apple's Xcode 3 integrated development # environment (see: http://developer.apple.com/tools/xcode/), introduced with # OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a # Makefile in the HTML output directory. Running make will produce the docset in # that directory and running make install will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at # startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_DOCSET = NO # This tag determines the name of the docset feed. A documentation feed provides # an umbrella under which multiple documentation sets from a single provider # (such as a company or product suite) can be grouped. # The default value is: Doxygen generated docs. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_FEEDNAME = "Doxygen generated docs" # This tag specifies a string that should uniquely identify the documentation # set bundle. This should be a reverse domain-name style string, e.g. # com.mycompany.MyDocSet. Doxygen will append .docset to the name. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_BUNDLE_ID = org.doxygen.Project # The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. # The default value is: org.doxygen.Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. # The default value is: Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three # additional HTML index files: index.hhp, index.hhc, and index.hhk. The # index.hhp is a project file that can be read by Microsoft's HTML Help Workshop # (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on # Windows. # # The HTML Help Workshop contains a compiler that can convert all HTML output # generated by doxygen into a single compiled HTML file (.chm). Compiled HTML # files are now used as the Windows 98 help format, and will replace the old # Windows help format (.hlp) on all Windows platforms in the future. Compressed # HTML files also contain an index, a table of contents, and you can search for # words in the documentation. The HTML workshop also contains a viewer for # compressed HTML files. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_HTMLHELP = NO # The CHM_FILE tag can be used to specify the file name of the resulting .chm # file. You can add a path in front of the file if the result should not be # written to the html output directory. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_FILE = # The HHC_LOCATION tag can be used to specify the location (absolute path # including file name) of the HTML help compiler (hhc.exe). If non-empty, # doxygen will try to run the HTML help compiler on the generated index.hhp. # The file has to be specified with full path. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. HHC_LOCATION = # The GENERATE_CHI flag controls if a separate .chi index file is generated # (YES) or that it should be included in the master .chm file (NO). # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. GENERATE_CHI = NO # The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) # and project file content. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_INDEX_ENCODING = # The BINARY_TOC flag controls whether a binary table of contents is generated # (YES) or a normal table of contents (NO) in the .chm file. Furthermore it # enables the Previous and Next buttons. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members to # the table of contents of the HTML help documentation and to the tree view. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that # can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help # (.qch) of the generated HTML documentation. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify # the file name of the resulting .qch file. The path specified is relative to # the HTML output folder. # This tag requires that the tag GENERATE_QHP is set to YES. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help # Project output. For more information please see Qt Help Project / Namespace # (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt # Help Project output. For more information please see Qt Help Project / Virtual # Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- # folders). # The default value is: doc. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_VIRTUAL_FOLDER = doc # If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom # filter to add. For more information please see Qt Help Project / Custom # Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- # filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_NAME = # The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see Qt Help Project / Custom # Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- # filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's filter section matches. Qt Help Project / Filter Attributes (see: # http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_SECT_FILTER_ATTRS = # The QHG_LOCATION tag can be used to specify the location of Qt's # qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the # generated .qhp file. # This tag requires that the tag GENERATE_QHP is set to YES. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be # generated, together with the HTML files, they form an Eclipse help plugin. To # install this plugin and make it available under the help contents menu in # Eclipse, the contents of the directory containing the HTML and XML files needs # to be copied into the plugins directory of eclipse. The name of the directory # within the plugins directory should be the same as the ECLIPSE_DOC_ID value. # After copying Eclipse needs to be restarted before the help appears. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_ECLIPSEHELP = NO # A unique identifier for the Eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have this # name. Each documentation set should have its own identifier. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. ECLIPSE_DOC_ID = org.doxygen.Project # If you want full control over the layout of the generated HTML pages it might # be necessary to disable the index and replace it with your own. The # DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top # of each HTML page. A value of NO enables the index and the value YES disables # it. Since the tabs in the index contain the same information as the navigation # tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. DISABLE_INDEX = YES # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. If the tag # value is set to YES, a side panel will be generated containing a tree-like # index structure (just like the one that is generated for HTML Help). For this # to work a browser that supports JavaScript, DHTML, CSS and frames is required # (i.e. any modern browser). Windows users are probably better off using the # HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can # further fine-tune the look of the index. As an example, the default style # sheet generated by doxygen has an example that shows how to put an image at # the root of the tree instead of the PROJECT_NAME. Since the tree basically has # the same information as the tab index, you could consider setting # DISABLE_INDEX to YES when enabling this option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_TREEVIEW = YES # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that # doxygen will group on one line in the generated HTML documentation. # # Note that a value of 0 will completely suppress the enum values from appearing # in the overview section. # Minimum value: 0, maximum value: 20, default value: 4. # This tag requires that the tag GENERATE_HTML is set to YES. ENUM_VALUES_PER_LINE = 4 # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used # to set the initial width (in pixels) of the frame in which the tree is shown. # Minimum value: 0, maximum value: 1500, default value: 250. # This tag requires that the tag GENERATE_HTML is set to YES. TREEVIEW_WIDTH = 250 # If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to # external symbols imported via tag files in a separate window. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of LaTeX formulas included as images in # the HTML documentation. When you change the font size after a successful # doxygen run you need to manually remove any form_*.png images from the HTML # output directory to force them to be regenerated. # Minimum value: 8, maximum value: 50, default value: 10. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are not # supported properly for IE 6.0, but are supported on all modern browsers. # # Note that when changing this option you need to delete any form_*.png files in # the HTML output directory before the changes have effect. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see # http://www.mathjax.org) which uses client side Javascript for the rendering # instead of using pre-rendered bitmaps. Use this if you do not have LaTeX # installed or if you want to formulas look prettier in the HTML output. When # enabled you may also need to install MathJax separately and configure the path # to it using the MATHJAX_RELPATH option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. USE_MATHJAX = NO # When MathJax is enabled you can set the default output format to be used for # the MathJax output. See the MathJax site (see: # http://docs.mathjax.org/en/latest/output.html) for more details. # Possible values are: HTML-CSS (which is slower, but has the best # compatibility), NativeMML (i.e. MathML) and SVG. # The default value is: HTML-CSS. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_FORMAT = HTML-CSS # When MathJax is enabled you need to specify the location relative to the HTML # output directory using the MATHJAX_RELPATH option. The destination directory # should contain the MathJax.js script. For instance, if the mathjax directory # is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax # Content Delivery Network so you can quickly see the result without installing # MathJax. However, it is strongly recommended to install a local copy of # MathJax from http://www.mathjax.org before deployment. # The default value is: http://cdn.mathjax.org/mathjax/latest. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest # The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax # extension names that should be enabled during MathJax rendering. For example # MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_EXTENSIONS = # The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces # of code that will be used on startup of the MathJax code. See the MathJax site # (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an # example see the documentation. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_CODEFILE = # When the SEARCHENGINE tag is enabled doxygen will generate a search box for # the HTML output. The underlying search engine uses javascript and DHTML and # should work on any modern browser. Note that when using HTML help # (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) # there is already a search function so this one should typically be disabled. # For large projects the javascript based search engine can be slow, then # enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to # search using the keyboard; to jump to the search box use + S # (what the is depends on the OS and browser, but it is typically # , /