repo_id
stringlengths
19
138
file_path
stringlengths
32
200
content
stringlengths
1
12.9M
__index_level_0__
int64
0
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tensorrt/init.bzl
load("//third_party/tensorrt:tensorrt_configure.bzl", "tensorrt_configure") def init(): tensorrt_configure(name = "local_config_tensorrt")
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tensorrt/BUILD.tpl
# NVIDIA TensorRT # A high-performance deep learning inference optimizer and runtime. licenses(["notice"]) load("@//third_party/gpus:common.bzl", "cuda_default_copts") load("@bazel_skylib//:bzl_library.bzl", "bzl_library") package(default_visibility = ["//visibility:public"]) exports_files(["LICENSE"]) cc_library( name = "tensorrt_headers", hdrs = [ "tensorrt/include/tensorrt_config.h", ":tensorrt_include" ], include_prefix = "third_party/tensorrt", strip_include_prefix = "tensorrt/include", ) cc_library( name = "tensorrt", srcs = [":tensorrt_lib"], copts = cuda_default_copts(), data = [":tensorrt_lib"], linkstatic = 1, deps = [ ":tensorrt_headers", "@local_config_cuda//cuda", ], ) bzl_library( name = "build_defs_bzl", srcs = ["build_defs.bzl"], deps = [ "@bazel_skylib//lib:selects", ], ) %{copy_rules}
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tensorrt/LICENSE
Copyright 2018 The TensorFlow Authors. All rights reserved. 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018, The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tensorrt/cyberfile.xml
<package format="2"> <name>3rd-tensorrt</name> <version>local</version> <description> Apollo packaged tensorrt Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-wrapper</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/tensorrt</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tensorrt/build_defs.bzl.tpl
# Build configurations for TensorRT. def if_tensorrt(if_true, if_false=[]): """Tests whether TensorRT was enabled during the configure process.""" return %{if_tensorrt}
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tensorrt/tensorrt_configure.bzl
"""Repository rule for TensorRT configuration. `tensorrt_configure` depends on the following environment variables: * `TF_TENSORRT_VERSION`: The TensorRT libnvinfer version. * `TENSORRT_INSTALL_PATH`: The installation path of the TensorRT library. """ load( "//third_party/gpus:cuda_configure.bzl", "find_cuda_config", "lib_name", ) load( "//tools/platform:common.bzl", "make_copy_files_rule", "config_repo_label", "get_cpu_value", "get_host_environ", ) _TENSORRT_INSTALL_PATH = "TENSORRT_INSTALL_PATH" _TF_TENSORRT_CONFIG_REPO = "TF_TENSORRT_CONFIG_REPO" _TF_TENSORRT_VERSION = "TF_TENSORRT_VERSION" _TF_NEED_TENSORRT = "TF_NEED_TENSORRT" _TF_TENSORRT_LIBS = ["nvinfer", "nvinfer_plugin", "nvparsers", "nvonnxparser"] _TF_TENSORRT_HEADERS = ["NvInfer.h", "NvUtils.h", "NvInferPlugin.h"] _TF_TENSORRT_HEADERS_V6 = [ "NvInfer.h", "NvUtils.h", "NvInferPlugin.h", "NvInferVersion.h", "NvInferRuntime.h", "NvInferRuntimeCommon.h", "NvInferPluginUtils.h", "NvUffParser.h", "NvCaffeParser.h", ] _DEFINE_TENSORRT_SONAME_MAJOR = "#define NV_TENSORRT_SONAME_MAJOR" _DEFINE_TENSORRT_SONAME_MINOR = "#define NV_TENSORRT_SONAME_MINOR" _DEFINE_TENSORRT_SONAME_PATCH = "#define NV_TENSORRT_SONAME_PATCH" def _at_least_version(actual_version, required_version): actual = [int(v) for v in actual_version.split(".")] required = [int(v) for v in required_version.split(".")] return actual >= required def _get_tensorrt_headers(tensorrt_version): if _at_least_version(tensorrt_version, "6"): return _TF_TENSORRT_HEADERS_V6 return _TF_TENSORRT_HEADERS def _tpl_path(repository_ctx, filename): return repository_ctx.path(Label("//third_party/tensorrt:%s.tpl" % filename)) def _tpl(repository_ctx, tpl, substitutions): repository_ctx.template( tpl, _tpl_path(repository_ctx, tpl), substitutions, ) def _create_dummy_repository(repository_ctx): """Create a dummy TensorRT repository.""" _tpl(repository_ctx, "build_defs.bzl", {"%{if_tensorrt}": "if_false"}) _tpl(repository_ctx, "BUILD", { "%{copy_rules}": "", "\":tensorrt_include\"": "", "\":tensorrt_lib\"": "", }) _tpl(repository_ctx, "tensorrt/include/tensorrt_config.h", { "%{tensorrt_version}": "", }) # Copy license file in non-remote build. repository_ctx.template( "LICENSE", Label("//third_party/tensorrt:LICENSE"), {}, ) def enable_tensorrt(repository_ctx): """Returns whether to build with TensorRT support.""" return int(get_host_environ(repository_ctx, _TF_NEED_TENSORRT, False)) def _create_local_tensorrt_repository(repository_ctx): # Resolve all labels before doing any real work. Resolving causes the # function to be restarted with all previous state being lost. This # can easily lead to a O(n^2) runtime in the number of labels. # See https://github.com/tensorflow/tensorflow/commit/62bd3534525a036f07d9851b3199d68212904778 find_cuda_config_path = repository_ctx.path(Label("@//third_party/gpus:find_cuda_config.py.gz.base64")) tpl_paths = { "build_defs.bzl": _tpl_path(repository_ctx, "build_defs.bzl"), "BUILD": _tpl_path(repository_ctx, "BUILD"), "tensorrt/include/tensorrt_config.h": _tpl_path(repository_ctx, "tensorrt/include/tensorrt_config.h"), } config = find_cuda_config(repository_ctx, find_cuda_config_path, ["tensorrt"]) trt_version = config["tensorrt_version"] cpu_value = get_cpu_value(repository_ctx) # Copy the library and header files. libraries = [lib_name(lib, cpu_value, trt_version) for lib in _TF_TENSORRT_LIBS] library_dir = config["tensorrt_library_dir"] + "/" headers = _get_tensorrt_headers(trt_version) include_dir = config["tensorrt_include_dir"] + "/" copy_rules = [ make_copy_files_rule( repository_ctx, name = "tensorrt_lib", srcs = [library_dir + library for library in libraries], outs = ["tensorrt/lib/" + library for library in libraries], ), make_copy_files_rule( repository_ctx, name = "tensorrt_include", srcs = [include_dir + header for header in headers], outs = ["tensorrt/include/" + header for header in headers], ), ] # Set up config file. repository_ctx.template( "build_defs.bzl", tpl_paths["build_defs.bzl"], {"%{if_tensorrt}": "if_true"}, ) # Set up BUILD file. repository_ctx.template( "BUILD", tpl_paths["BUILD"], {"%{copy_rules}": "\n".join(copy_rules)}, ) # Copy license file in non-remote build. repository_ctx.template( "LICENSE", Label("//third_party/tensorrt:LICENSE"), {}, ) # Set up tensorrt_config.h, which is used by # tensorflow/stream_executor/dso_loader.cc. repository_ctx.template( "tensorrt/include/tensorrt_config.h", tpl_paths["tensorrt/include/tensorrt_config.h"], {"%{tensorrt_version}": trt_version}, ) def _tensorrt_configure_impl(repository_ctx): """Implementation of the tensorrt_configure repository rule.""" if get_host_environ(repository_ctx, _TF_TENSORRT_CONFIG_REPO) != None: # Forward to the pre-configured remote repository. remote_config_repo = repository_ctx.os.environ[_TF_TENSORRT_CONFIG_REPO] repository_ctx.template("BUILD", config_repo_label(remote_config_repo, ":BUILD"), {}) repository_ctx.template( "build_defs.bzl", config_repo_label(remote_config_repo, ":build_defs.bzl"), {}, ) repository_ctx.template( "tensorrt/include/tensorrt_config.h", config_repo_label(remote_config_repo, ":tensorrt/include/tensorrt_config.h"), {}, ) repository_ctx.template( "LICENSE", config_repo_label(remote_config_repo, ":LICENSE"), {}, ) return if not enable_tensorrt(repository_ctx): _create_dummy_repository(repository_ctx) return _create_local_tensorrt_repository(repository_ctx) _ENVIRONS = [ _TENSORRT_INSTALL_PATH, _TF_TENSORRT_VERSION, _TF_NEED_TENSORRT, "TF_CUDA_PATHS", ] #remote_tensorrt_configure = repository_rule( # implementation = _create_local_tensorrt_repository, # environ = _ENVIRONS, # remotable = True, # attrs = { # "environ": attr.string_dict(), # }, #) # tensorrt_configure = repository_rule( implementation = _tensorrt_configure_impl, environ = _ENVIRONS + [_TF_TENSORRT_CONFIG_REPO], ) """Detects and configures the local CUDA toolchain. Add the following to your WORKSPACE FILE: ```python tensorrt_configure(name = "local_config_tensorrt") ``` Args: name: A unique name for this workspace rule. """
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tensorrt/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-tensorrt", data = [ ":cyberfile.xml", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-tensorrt/src", filter = "*", )
0
apollo_public_repos/apollo/third_party/tensorrt/tensorrt
apollo_public_repos/apollo/third_party/tensorrt/tensorrt/include/tensorrt_config.h.tpl
/* Copyright 2019 The TensorFlow Authors. 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. ==============================================================================*/ #ifndef TENSORRT_TENSORRT_INCLUDE_CONFIG_H_ #define TENSORRT_TENSORRT_INCLUDE_CONFIG_H_ #define TF_TENSORRT_VERSION "%{tensorrt_version}" #endif // TENSORRT_TENSORRT_INCLUDE_CONFIG_H_
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/find_cuda_config.py.gz.base64
eJzlPO1y4ziO//0UPOVSkbodOZnbmtrzbeYqk07X5DaXdCXunptKe72KRDuayJJWkp14t/bdDwBJiaRkJ3F6ertqVNUdiyJAAARAgF877CTLV0U8u6vYdweH/8lGd5yNeFpmxfske2DHi+ouK0qfHScJu8JqJbviJS+WPPJ7O70ddh6HUJ1HbJFGvGAVwB/nQQh/5Jc++8SLMs5S9p1/wFys4MhPjvdfgGGVLdg8WLE0q9ii5IAiLtk0TjjjjyHPKxanLMzmeRIHacjZQ1zdUTMSCZDBfpEostsqgNoB1M/hbarXY0FFBONzV1X5cDB4eHjwAyLWz4rZIBEVy8H52cnpxfXpPhBMIB/ThJclK/jfFnEBrN6uWJADPWFwC1QmwQPLChbMCg7fqgzpfSjiKk5nfVZm0+ohKDhgieKyKuLbRWUIS1EHPOsVQFxBypzja3Z27bAfj6/PrvuA4+ez0U+XH0fs5+Orq+OL0dnpNbu8YieXF+/ORmeXF/D2nh1f/ML+fHbxrs84iAqa4Y95gfQDkTGKkbqOXXNuEDDNBEFlzsN4GofAVzpbBDPOZtmSFymww3JezOMSO7ME8iLAksTzuAoqKmkxhc0cfdGnBxgvLkenblllxSq/X3hDNgriJCuE6MtFnmdFBQSki0d2eXH+C9JwCQoep0NWkWJPQbEHoGRFNMmDoloNZvmiHEzjNJqEiyiYhFk6jWd+vvry1DuO86GIUzCik4/vjkF4t0VQrFCU7I4HKL0IFCwE3mJOEmZLYTtgEBmIF9WC+mhVVnzu93pormVYxGAlJQ8K0OSSOnIdejSr0sTSB33FPq/KHhTOUYoRr7CjU1KQuFBEEKJc0I/wQlCLgrqfpF9F2aLyiao8qO5KYQ2EnYARqraimjUwD6V12It3RbaY3TGeLuMiS+c8rXrLoIjR1sARnU3BUbBlkMSRRUAshdQXzAmpKHKJOF4UpLYFrxYFqTCDIhBXmEVcSjMBI0TPIYSH3QCwqByIv6EyQLJnC6QOiLoWagflDRgaPXWDG6dhsoigKFz8eH587fXhx7uLiz67ODk575NghMu9GpldWgX3iKim6TYAO9U1pKEHXBJyPXo/wTYnH45HP133NBEyJUKkHLzpPNgvOah/gETPkuyWGvGZ1nqSZfdCm4TylD2kVCmV0CRytndBEe2jCCNQQiK0XNzqZE6LbI7kAfXEAumG34OuNOhFCeMgUHMFsmGX141Hivg0WCQV1oOBIhr2ekxY+hB8+mBRFoMkC4NkgGbcpwIhXaGLRMVeEgmtYfv5Hkj7PbB3G4T34KMjEgzUjW/jJK5W6LznXO/RpMxohAoSsI8UKi4FQ70Ws5lwvB3yB5nRsLQy1d4HRqiTe1LA+zXXnVgk76IvWD3EQt2mp9lxFMVoGkHSUh2A3n/lAyhIv+lRHfnp9OoaBiJRSN8no8vL8z+fjaiPAUYYQQ2DLwZUNwzYi9bOxYXZkCg6u7geHZ+fKyC0rpo4fLGIoyIdRhjk5Kd3VwqFMktCMYKY4PLqaqShqYuMpnuflGfrVoAQ/M4tV+EJGBio5eMeDs97j/5qDx0OOkkO+hD0ajWQ7hJG9XlerbD2ItW8ZsaCkKKlIF2putKbgE/OF2SXgRxGlBGDIWlUDHvVdPIn+e2HiUQyZECU/3fzm/AIE1CoIfN93/wofzRfYdjr9SD0wJE5ztSvrFS/0P+o33kSVEiMegcvKn+BU8mLLIRIpi5ZlRgQ5KsEnPwQ4ycU8NFsX3zfB2eyH1T7VZb3qmI17GGvk3mWd4sqTphE83AXh3c9GWyeUdkpDgsaAIZmCFL6ZR48pAqSggb+yMNFpXyrQNYQxdO1NPV6YRJAXHZCDomadE+JChC7J1rPoQJUBM/HJnEJogVv58pvYhirJeaL8dz1IGrBEBtqOgp0HlQYG6g+dYOwWgTJpNYpNSirEtkCdNzJHQ/vkS1OLo1coooH5pzLUEDCi+Gw15MWRlkDT0Sx0jS7KZbKsBlMAuNUtJWYApQajUmthl9IwcJnVccaJYwaBtBLnFzzHDL7OfTNslGx4CaI/50NYr2/h2HlSRj/P56AaT92O0Ra0zPFrBxqGGwpDikSUCJsxRkwCha+Bm6K3ATGaDLEMEOFAWLYgLiwCpKEYrcG1ZUIzYbsZ6lwWF9gb9ROKLMZTWYp95XO0l8YZi1FAG93AdUatqUBCWlSKaRFkILlwHAQaoFLHauKJiy8R7aCYhqXu16vS7BQ2y6y6hNNLYyQqZSY+rotU1U2HlSThAdl9VIjl9I9YjfgsNylRyHfkkI7iwjIHSvX8R1vbLDWBdrmsQWs8cl+aKSi2JnxSg0ziiGM4/osDea88U9SYdB1yNEBSAAEkL1QeHqipz6+Ug6kM8EEB2rEmZ/lXGF3CgeG2BTCWUh4j5xFNd3/o+P5BSBBgFI5X3xIEalDffrpFs6OaJrtluyt+zl66zlslyjuU3teDQvqSTBDy5mRVOiLP4NEKHcPDb1wapcegkbwMg7SCfAdLcLKncZFWUHUyiHCjdoSAmOjSBij3Ns4lUk7eGWCo0BZgNZSkm3eZKWPgP6vWZy6U2hBdPQUpSeA8ZXELTCM9U5MIplSTygOd7spa4XQZqSuWTWmCK2xUCdXKJgCp1ahk2hgdh1V7HgYQjmDEkQxqAsJUsZLR1rE4Yc4DE7EF/fGwA06s587Y0+O1xXmBkIpMJ0ArQOtf8OOfmCu/8ZzVG/ikIRN8Eoavq6Soh1hMy2tq0MZWw1l21IXEc6POOZlrhOUYRw7XqN+Mtr5mMZY4R1V04IeG7U54KzTXeTJD6LIVQoDnYq675r67BkaXVLi7GL66QoUnqerj0z6xNyM0CD6aToxqRf6l4Y6vRSYcd6IfuaJhAKvRJOMzwE2Xt8CKCAzjMWxEtH93RJ9gA4HGmNVcmSR0zdEalVLU2cMbXZblZKZ9JnrbK2drBc8EalsPWWDmb+W+Itcv+UVakodjWpHTnZ0FElG2+Vv9smU92fpQv/MH6siKAcnHz+MzgZPoBW19K+NbAcbENWOSuUsX0RsxhzJM+UGMN//wSqwXtcJCj89msAGy2/WyKXd5BqZ6RVriYHhTCibnNAcmoszDEJ8/Vo26h0FIb2TFG1TGw3SEUPLjfM5VcTs7ZZ7YDcbglzy6yhu+hHXnqRB7Y2Vp9HJ2brBzkZN3GPDtemJXSPlk2yRROR3aFoR8/VdMZMGv7SZs9Vwt/ycZlP6o1PmauJsy1pjv/YJlKci1At7SWe0I+BYj0wbrihSwNUcwIGJvo//uUZIIUZRvXmvMyzCGkK+QVzy7VXQEIs0VgNYeQMRuK1PjpV3EEGQmJQmeYE3UNkJL5t54VUTgDbkoD76tUKi2YOPNylwyswZb9LMt5sC7pvh4djDseqN4YjWaIXtCjeITjbFX6ZbZX89JzYXfYZj3YvkHghtq+6CqpUpir5QEtJiymqVc92sIMJFAwWVvcHApM+qRZ7wsabVWl3Mf/T38Re3HaUpcWo0bBrJlzA0fFrZrdYFJCOvBRJvP8XU1oDa1PsWKZtMv8a1QQkbFwwWJZMZo8vBRITK4Fqn4l+OC236DVMQkZLRqzIQ6/YhWym2DMdeoNqGqW8wVytqNIl/Ykh8ymoNOWkrrJYJtLSDmkXINTMBmgI1uorzEOunDhx9jUJPh2Qi0Ar+NRni1JGdajq7kb8boXa4ioTBgB0eHBz0a5p26V2Ue4IpEoIm8VrcDR9rtcpBYP/OebpXntVTW2Fpy9dr+Gp4sJhiO7iSgPMTnAW32ZL7mjT0Qadmv2toJv6LyukbrXmmtqTLMFynK1qG7pwACiaydLWInSXCcXBcMPscvf3sw3999slVv+k/zzF8tMrb104YqHmCfUmUM/bWZPf4tOaV6mBvc1KPT3duLvp+3dyS9pW0nApJhmj/GJ/gi9MUy4k4Tcp1n21wMmsyn9s4XZOENF/G/YaevpVL2x3uKfqXc1OdNhGEtTHPifgyDo00s4TUr527Ys6VLuMoDvYpyUfFuY+rbhQaS53tAHdOXfbGPzzwb0On9hV5FevOYj07LSfuEDA4C09D9RJLg/pOh2/W7BYnEsVSH+Cyp31qXfGaHtEWBzshZKd5aj7+/86PFQFisJOSrodFSqLy6jEQG2ZqOfoSwejy3aUblvFs5g1pOQ0N9TYDYH3KEVcjQHp+w5lsp84ZmxBDEZ1mBW4XuDNjLEssGGpADO71nwluC4ngBxoKT8WsbSpvDsbs3466PhxqoauIoPTc1DlLYUguIdDFxTdandGlPMT8dFkymsjaMGC02/WMqbF/NBahW7AzNA3aqiUnbFAWUNNWGHso9WxwTZTrwHWLaME3Pano1PrW9B9WW62e1DGjJT7FmWX4XgvBU7zZ5t5iTu8sxZ6tUQLmn1YUd5sE5XPiOGuYllFd3LVcZc2Qghc8dBQAPs8LBfFpxiS3pa5PrCu16uPwTqMgeA3XafarTP73+H8urxyKKZuyswss2xxU6QAfjkcnP9lDuAou1aSA6Xbx2T52pH4L8njbCPKLBJDr4kd8dtQGoUUpHf48+DVr9iBmabJqloslQ+tiTn0S5GDck7P+pbYEvINL1QUXW8/qRuJ0CvnWMoCwELd13HLQArlsjWrZZ78uSjl9p+9T2BGLjHY3dS8edHXmy8Z2rS875KetetN+SNThQG48Vd9cCMi9DdK0e1tI8CURBCKkWF3HvGFY0KuBRzIl2G/V3OxC1zpPgt3sPTv8pu0DyywBwn5jL3joH3yDXvD68hzdl+UH9dJnekIN5Kv7wrr/5nNwFd+qQ6zp3N7JvdIPGRxpMjTKbQdlfOwQ9kYGX+93BEryPCb2Db7HrLjZ+8i6W/ofCf1qD1QEafS79D9XxxfvbO/TlD3T99QAX93zYL99ww6H1Opf5m6eCnuk8DYQ/Hr3gQjJeeiYN7gOvdpmx0E1t3QbBPtqpzGdVr9Ln/H+/ch2GXWR8Bh60Vf3CdAt37BLQKX5Zj2CEN16cl/vDwAfuQMN7wZvoNXa7Ayw4pa+AEFf7QqiNP0tF+NuDD18if3atovHezS7pdfGZvGV7PX89NPpudphrPVOy2DRj8nfOGmK2qotfWxnxC81OtehDkCjZ+JnbVCgzC9G92onsGFVryHtWcb/osW8NBVreU0bm2aNm1pivrJ579v1tjQsBH391EAeFMDm73GYvf5wfHV92poa0EqfOzXQgHz9qQHqv294PJYK9s0OybUANxL9BfJ8QinyfAP7pjzfqPhEni/qbpvnC+hXupM0DJPfcpg2fcD2wzSdnq1tXrypQZreWma82YS3NV+U1zam+5uNoNSBv80AiqhBvnoLazVfr4Trk9pr36q1lb4T5Ct1XVzRUTwrQ/2X6/un5kx4o/Z64VMjnVG7ZR077K+SoL/iKk4ATKa8CCogIrv9lYd41itjD3QRB1SsWFyJfYJ0X4RctFqUcTrTUEIdd76IqzjHTbLxnJdQM8ketGWgRlJ0KKc1+sjNckGSuE1P6GztqPsIxH0O8laOeXDPW9tEmbqLg04Y+QaaTRvvuj2GcTRqW/dxsTxLp7z4Jgd/eWxL27xhLGWq6wq+Z/NsySP96CqtaRbz+q4WyeUnlXG0Vi23lVuN8RsTn1AQ5V6e6Y0R5gXOeBmjBMAN2O2s9cl2RWfYgu131N7KP9fQ2/todAgTPJ454enShX9yR548pHd0M27vZbZvmyHvREc8u67H0HflK/x0JLL0ZfXWgc/m042CGKt+7NcHLqmqpNM4nspnQSi4fSZDgdh7ZhyKB6dLeLp5Er3fvqWk33UJSeelInTqrMoIz544FYinvv74/eT7PzSnwvbYAx0uygu+jLNFmazEJgXa7ta+DoqwkfL67B2d0gePkeEFN1BFSowa2+uLG20eYnFRGN6Wg07E0gevdQL/qR5s7XQ1BwDnL+7g5i8DNn7jvSWGPz+8bbgd/Pe/Wz6mSxOeeeT6xtwXaxxSf0rtveZMHHjYJP67cAl6BKKpT11JbO3vixvtlFTLJCjvxB1dP0PXZQ+tA4TKXgseJE0zkoTWJvsu9Y3ikK4FKuiOvE13hUntUBQ0dyEdsZugmC19iBxgHBDnwbGAdkGvSh9/3xwOx2M1haRvDG+6yQcLdB3r8iAMo6TZGscErW5wjMujnjHaPOs4cUe7tHvbOM+jfQalUh3CH4G+UnTHWDl8ec77H/9UJkE77+i8cS1N67DxOn5bNyM5xmk/zS3SQexFHoG/ddvnLppGrMknberE6jGB8sbctznWatOOGkV4Q5Rue3SEyrUvitAxaoOvx/7E3MODPjtsxZY/tnZjyR1PD0Epb44Ru53qg5S470nfpyXwyI2OZsxpcdKIyub1CW3Wr7XS9LndPWYu0rG7UqfI3ki1qf/kHoMv3icg7wOrT1qNdYqttcujU3DNhqDtRGduyjIpa+8G2SRAWm39OuIzmuoUnrXC3Sk6tZ9hO8Hpe0l0iuxV8E0iw0WpryMxvaVOgZkrgJ3ykku924lLW0VvDTwaee1RySCt6/NagxaTiV/JoM3Gug3ans7tNuh6Gn9LgzaWUkzK2tO+3doph9003TDupmkz8Np5gdMO3deMvfZiWXeo09xfuFEeHcu0GqH2qpnGK80KrmGVZunWc9pKSNYwas1pdvCpX7n4DDb1We6GRmtqU+NRZbPr+Kyz3fW8dmZaa/jtmDno4Nm+I/IZfNsznibdHVMJUgZo3Pd9ddsW4Y0rPjcOE4Kc7oHGSNwc5lDCT/ceGaXYkNO6cYECvvsxCs5Ka5bmbIa8Xk/kH/MgThUFxmwckctXfTzUvODadR3tjEXxYZFEV/m6zm45FCeRmNvg89ZNj2Hop616YWoiLgL28Ypu7pZV4XJtzhUrQBxf4dHIXg+XYSnVm0zoUsXJBPmbTByBUTDb+38R1Xck
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/init.bzl
load("//third_party/gpus:cuda_configure.bzl", "cuda_configure") def init(): cuda_configure(name = "local_config_cuda")
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/check_cuda_libs.py
# Copyright 2020 The TensorFlow Authors. 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. # ============================================================================== """Verifies that a list of libraries is installed on the system. Takes a a list of arguments with every two subsequent arguments being a logical tuple of (path, check_soname). The path to the library and either True or False to indicate whether to check the soname field on the shared library. Example Usage: ./check_cuda_libs.py /path/to/lib1.so True /path/to/lib2.so False """ import os import os.path import platform import subprocess import sys # pylint: disable=g-import-not-at-top,g-importing-member try: from shutil import which except ImportError: from distutils.spawn import find_executable as which # pylint: enable=g-import-not-at-top,g-importing-member class ConfigError(Exception): pass def check_cuda_lib(path, check_soname=True): """Tests if a library exists on disk and whether its soname matches the filename. Args: path: the path to the library. check_soname: whether to check the soname as well. Raises: ConfigError: If the library does not exist or if its soname does not match the filename. """ if not os.path.isfile(path): raise ConfigError("No library found under: " + path) objdump = which("objdump") if check_soname and objdump is not None: # Decode is necessary as in py3 the return type changed from str to bytes output = subprocess.check_output([objdump, "-p", path]).decode("utf-8") output = [line for line in output.splitlines() if "SONAME" in line] sonames = [line.strip().split(" ")[-1] for line in output] if not any(soname == os.path.basename(path) for soname in sonames): raise ConfigError("None of the libraries match their SONAME: " + path) def main(): try: args = [argv for argv in sys.argv[1:]] if len(args) % 2 == 1: raise ConfigError("Expected even number of arguments") checked_paths = [] for i in range(0, len(args), 2): path = args[i] check_cuda_lib(path, check_soname=args[i + 1] == "True") checked_paths.append(path) # pylint: disable=superfluous-parens print(os.linesep.join(checked_paths)) # pylint: enable=superfluous-parens except ConfigError as e: sys.stderr.write(str(e)) sys.exit(1) if __name__ == "__main__": main()
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/rocm_configure.bzl
"""Repository rule for ROCm autoconfiguration. `rocm_configure` depends on the following environment variables: * `TF_NEED_ROCM`: Whether to enable building with ROCm. * `GCC_HOST_COMPILER_PATH`: The GCC host compiler path * `ROCM_PATH`: The path to the ROCm toolkit. Default is `/opt/rocm`. * `TF_ROCM_AMDGPU_TARGETS`: The AMDGPU targets. """ load( "//tools/platform:common.bzl", "err_out", "execute", "files_exist", "get_bash_bin", "get_cpu_value", "get_host_environ", "get_crosstool_verbose", "get_python_bin", "raw_exec", "realpath", "to_list_of_strings", "which", "make_copy_dir_rule", "make_copy_files_rule", "tpl_gpus_path", "tpl_gpus", ) _GCC_HOST_COMPILER_PATH = "GCC_HOST_COMPILER_PATH" _GCC_HOST_COMPILER_PREFIX = "GCC_HOST_COMPILER_PREFIX" _TF_NEED_ROCM = "TF_NEED_ROCM" _ROCM_TOOLKIT_PATH = "ROCM_PATH" _TF_ROCM_AMDGPU_TARGETS = "TF_ROCM_AMDGPU_TARGETS" _TF_ROCM_CONFIG_REPO = "TF_ROCM_CONFIG_REPO" def verify_build_defines(params): """Verify all variables that crosstool/BUILD.rocm.tpl expects are substituted. Args: params: dict of variables that will be passed to the BUILD.rocm.tpl template. """ missing = [] for param in [ "cxx_builtin_include_directories", "extra_no_canonical_prefixes_flags", "host_compiler_path", "host_compiler_prefix", "linker_bin_path", "unfiltered_compile_flags", ]: if ("%{" + param + "}") not in params: missing.append(param) if missing: auto_configure_fail( "BUILD.rocm.tpl template is missing these variables: " + str(missing) + ".\nWe only got: " + str(params) + ".", ) def find_cc(repository_ctx): """Find the C++ compiler.""" target_cc_name = "gcc" cc_path_envvar = _GCC_HOST_COMPILER_PATH cc_name = target_cc_name cc_name_from_env = get_host_environ(repository_ctx, cc_path_envvar) if cc_name_from_env: cc_name = cc_name_from_env if cc_name.startswith("/"): # Absolute path, maybe we should make this supported by our which function. return cc_name cc = which(repository_ctx, cc_name) if cc == None: fail(("Cannot find {}, either correct your path or set the {}" + " environment variable").format(target_cc_name, cc_path_envvar)) return cc _INC_DIR_MARKER_BEGIN = "#include <...>" def _cxx_inc_convert(path): """Convert path returned by cc -E xc++ in a complete path.""" return path.strip() def _get_cxx_inc_directories_impl(repository_ctx, cc, lang_is_cpp): """Compute the list of default C or C++ include directories.""" if lang_is_cpp: lang = "c++" else: lang = "c" # TODO: We pass -no-canonical-prefixes here to match the compiler flags, # but in rocm_clang CROSSTOOL file that is a `feature` and we should # handle the case when it's disabled and no flag is passed result = raw_exec(repository_ctx, [ cc, "-no-canonical-prefixes", "-E", "-x" + lang, "-", "-v", ]) stderr = err_out(result) index1 = stderr.find(_INC_DIR_MARKER_BEGIN) if index1 == -1: return [] index1 = stderr.find("\n", index1) if index1 == -1: return [] index2 = stderr.rfind("\n ") if index2 == -1 or index2 < index1: return [] index2 = stderr.find("\n", index2 + 1) if index2 == -1: inc_dirs = stderr[index1 + 1:] else: inc_dirs = stderr[index1 + 1:index2].strip() return [ str(repository_ctx.path(_cxx_inc_convert(p))) for p in inc_dirs.split("\n") ] def get_cxx_inc_directories(repository_ctx, cc): """Compute the list of default C and C++ include directories.""" # For some reason `clang -xc` sometimes returns include paths that are # different from the ones from `clang -xc++`. (Symlink and a dir) # So we run the compiler with both `-xc` and `-xc++` and merge resulting lists includes_cpp = _get_cxx_inc_directories_impl(repository_ctx, cc, True) includes_c = _get_cxx_inc_directories_impl(repository_ctx, cc, False) includes_cpp_set = depset(includes_cpp) return includes_cpp + [ inc for inc in includes_c if inc not in includes_cpp_set.to_list() ] def auto_configure_fail(msg): """Output failure message when ROCm configuration fails.""" red = "\033[0;31m" no_color = "\033[0m" fail("\n%sROCm Configuration Error:%s %s\n" % (red, no_color, msg)) def auto_configure_warning(msg): """Output warning message during auto configuration.""" yellow = "\033[1;33m" no_color = "\033[0m" print("\n%sAuto-Configuration Warning:%s %s\n" % (yellow, no_color, msg)) # END cc_configure common functions. def _rocm_include_path(repository_ctx, rocm_config, bash_bin): """Generates the cxx_builtin_include_directory entries for rocm inc dirs. Args: repository_ctx: The repository context. rocm_config: The path to the gcc host compiler. Returns: A string containing the Starlark string for each of the gcc host compiler include directories, which can be added to the CROSSTOOL file. """ inc_dirs = [] rocm_toolkit_path = realpath(repository_ctx, rocm_config.rocm_toolkit_path, bash_bin) # Add HSA headers (needs to match $HSA_PATH) inc_dirs.append(rocm_toolkit_path + "/hsa/include") # Add HIP headers (needs to match $HIP_PATH) inc_dirs.append(rocm_toolkit_path + "/hip/include") # Add HIP-Clang headers (realpath relative to compiler binary) inc_dirs.append(rocm_toolkit_path + "/llvm/lib/clang/14.0.0/include") inc_dirs.append(rocm_toolkit_path + "/llvm/lib/clang/15.0.0/include") return inc_dirs def _enable_rocm(repository_ctx): enable_rocm = get_host_environ(repository_ctx, "TF_NEED_ROCM") if enable_rocm == "1": if get_cpu_value(repository_ctx) != "Linux": auto_configure_warning("ROCm configure is only supported on Linux") return False return True return False def _amdgpu_targets(repository_ctx, rocm_toolkit_path, bash_bin): """Returns a list of strings representing AMDGPU targets.""" amdgpu_targets_str = get_host_environ(repository_ctx, _TF_ROCM_AMDGPU_TARGETS) if not amdgpu_targets_str: cmd = "%s/bin/rocm_agent_enumerator" % rocm_toolkit_path result = execute(repository_ctx, [bash_bin, "-c", cmd]) targets = [target for target in result.stdout.strip().split("\n") if target != "gfx000"] targets = {x: None for x in targets} targets = list(targets.keys()) amdgpu_targets_str = ",".join(targets) amdgpu_targets = amdgpu_targets_str.split(",") for amdgpu_target in amdgpu_targets: if amdgpu_target[:3] != "gfx": auto_configure_fail("Invalid AMDGPU target: %s" % amdgpu_target) return amdgpu_targets def _hipcc_env(repository_ctx): """Returns the environment variable string for hipcc. Args: repository_ctx: The repository context. Returns: A string containing environment variables for hipcc. """ hipcc_env = "" for name in [ "HIP_CLANG_PATH", "DEVICE_LIB_PATH", "HIP_VDI_HOME", "HIPCC_VERBOSE", "HIPCC_COMPILE_FLAGS_APPEND", "HIPPCC_LINK_FLAGS_APPEND", "HCC_AMDGPU_TARGET", "HIP_PLATFORM", ]: env_value = get_host_environ(repository_ctx, name) if env_value: hipcc_env = (hipcc_env + " " + name + "=\"" + env_value + "\";") return hipcc_env.strip() def lib_name(lib, version = "", static = False): """Constructs the name of a library on Linux. Args: lib: The name of the library, such as "hip" version: The version of the library. static: True the library is static or False if it is a shared object. Returns: The platform-specific name of the library. """ if static: return "lib%s.a" % lib else: if version: version = ".%s" % version return "lib%s.so%s" % (lib, version) def _rocm_lib_paths(repository_ctx, lib, basedir): file_name = lib_name(lib, version = "", static = False) return [ repository_ctx.path("%s/lib64/%s" % (basedir, file_name)), repository_ctx.path("%s/lib64/stubs/%s" % (basedir, file_name)), repository_ctx.path("%s/lib/x86_64-linux-gnu/%s" % (basedir, file_name)), repository_ctx.path("%s/lib/%s" % (basedir, file_name)), repository_ctx.path("%s/%s" % (basedir, file_name)), ] def _batch_files_exist(repository_ctx, libs_paths, bash_bin): all_paths = [] for _, lib_paths in libs_paths: for lib_path in lib_paths: all_paths.append(lib_path) return files_exist(repository_ctx, all_paths, bash_bin) def _select_rocm_lib_paths(repository_ctx, libs_paths, bash_bin): test_results = _batch_files_exist(repository_ctx, libs_paths, bash_bin) libs = {} i = 0 for name, lib_paths in libs_paths: selected_path = None for path in lib_paths: if test_results[i] and selected_path == None: # For each lib select the first path that exists. selected_path = path i = i + 1 if selected_path == None: auto_configure_fail("Cannot find rocm library %s" % name) libs[name] = struct(file_name = selected_path.basename, path = realpath(repository_ctx, selected_path, bash_bin)) return libs def _find_libs(repository_ctx, rocm_config, hipfft_or_rocfft, bash_bin): """Returns the ROCm libraries on the system. Args: repository_ctx: The repository context. rocm_config: The ROCm config as returned by _get_rocm_config bash_bin: the path to the bash interpreter Returns: Map of library names to structs of filename and path """ libs_paths = [ (name, _rocm_lib_paths(repository_ctx, name, path)) for name, path in [ ("amdhip64", rocm_config.rocm_toolkit_path + "/hip"), ("hipblas", rocm_config.rocm_toolkit_path + "/hipblas"), ("rocblas", rocm_config.rocm_toolkit_path + "/rocblas"), ("MIOpen", rocm_config.rocm_toolkit_path + "/miopen"), ("migraphx", rocm_config.rocm_toolkit_path + "/migraphx"), ] ] return _select_rocm_lib_paths(repository_ctx, libs_paths, bash_bin) def _exec_find_rocm_config(repository_ctx, script_path): python_bin = get_python_bin(repository_ctx) compressed_contents = repository_ctx.read(script_path) decompress_and_execute_cmd = ( "from zlib import decompress;" + "from base64 import b64decode;" + "from os import system;" + "script = decompress(b64decode('%s'));" % compressed_contents + "f = open('script.py', 'wb');" + "f.write(script);" + "f.close();" + "system('\"%s\" script.py');" % (python_bin) ) return execute(repository_ctx, [python_bin, "-c", decompress_and_execute_cmd]) def find_rocm_config(repository_ctx, script_path): """Returns ROCm config dictionary from running find_rocm_config.py""" exec_result = _exec_find_rocm_config(repository_ctx, script_path) if exec_result.return_code: auto_configure_fail("Failed to run find_rocm_config.py: %s" % err_out(exec_result)) # Parse the dict from stdout. return dict([tuple(x.split(": ")) for x in exec_result.stdout.splitlines()]) def _get_rocm_config(repository_ctx, bash_bin, find_rocm_config_script): """Detects and returns information about the ROCm installation on the system. Args: repository_ctx: The repository context. bash_bin: the path to the path interpreter Returns: A struct containing the following fields: rocm_toolkit_path: The ROCm toolkit installation directory. amdgpu_targets: A list of the system's AMDGPU targets. rocm_version_number: The version of ROCm on the system. miopen_version_number: The version of MIOpen on the system. migraphx_version_number: The version of MIGraphX on the system. hipruntime_version_number: The version of HIP Runtime on the system. """ config = find_rocm_config(repository_ctx, find_rocm_config_script) rocm_toolkit_path = config["rocm_toolkit_path"] rocm_version_number = config["rocm_version_number"] miopen_version_number = config["miopen_version_number"] migraphx_version_number = config["migraphx_version_number"] hipruntime_version_number = config["hipruntime_version_number"] return struct( amdgpu_targets = _amdgpu_targets(repository_ctx, rocm_toolkit_path, bash_bin), rocm_toolkit_path = rocm_toolkit_path, rocm_version_number = rocm_version_number, miopen_version_number = miopen_version_number, migraphx_version_number = migraphx_version_number, hipruntime_version_number = hipruntime_version_number, config = config ) _DUMMY_CROSSTOOL_BZL_FILE = """ def error_gpu_disabled(): fail("ERROR: Building with --config=rocm but Apollo is not configured " + "to build with GPU support. Please re-run ./scripts/apollo_config.sh" + "to build with GPU support.") native.genrule( name = "error_gen_crosstool", outs = ["CROSSTOOL"], cmd = "echo 'Should not be run.' && exit 1", ) native.filegroup( name = "crosstool", srcs = [":CROSSTOOL"], output_licenses = ["unencumbered"], ) """ _DUMMY_CROSSTOOL_BUILD_FILE = """ load("//crosstool:error_gpu_disabled.bzl", "error_gpu_disabled") error_gpu_disabled() """ def _create_dummy_repository(repository_ctx): # Set up build_defs.bzl file for rocm/ tpl_gpus( repository_ctx, "rocm:build_defs.bzl", { "%{rocm_is_configured}": "False", "%{rocm_extra_copts}": "[]", "%{rocm_gpu_architectures}": "[]", "%{rocm_version_number}": "0", }, ) # Set up BUILD file for rocm/ tpl_gpus( repository_ctx, "rocm:BUILD", { "%{hip_lib}": lib_name("hip"), "%{hipblas_lib}": lib_name("hipblas"), "%{rocblas_lib}": lib_name("rocblas"), "%{miopen_lib}": lib_name("miopen"), "%{migraphx_lib}": lib_name("migraphx"), "%{migraphx_c_lib}": lib_name("migraphx_c"), "%{migraphx_tf_lib}": lib_name("migraphx_tf"), "%{migraphx_device_lib}": lib_name("migraphx_device"), "%{migraphx_gpu_lib}": lib_name("migraphx_gpu"), "%{migraphx_ref_lib}": lib_name("migraphx_ref"), "%{migraphx_onnx_lib}": lib_name("migraphx_onnx"), "%{copy_rules}": "", "%{rocm_headers}": "", }, ) # Create dummy files for the ROCm toolkit since they are still required by # tensorflow/core/platform/default/build_config:rocm. repository_ctx.file("rocm/hip/include/hip/hip_runtime.h", "") # Set up rocm_config.h, which is used by # tensorflow/stream_executor/dso_loader.cc. tpl_gpus( repository_ctx, "rocm:rocm_config.h", { "%{rocm_amdgpu_targets}": "", "%{rocm_toolkit_path}": "", "%{rocm_version_number}": "", "%{miopen_version_number}": "", "%{migraphx_version_number}": "", "%{hipruntime_version_number}": "", "%{hipblas_version_number}": "", "%{rocblas_version_number}": "", }, "rocm/rocm/rocm_config.h", ) # Set up rocm_config.py, which is used by gen_build_info to provide # static build environment info to the API tpl_gpus( repository_ctx, "rocm:rocm_config.py", { "%{rocm_config}": str({}), }, "rocm/rocm/rocm_config.py", ) # If rocm_configure is not configured to build with GPU support, and the user # attempts to build with --config=rocm, add a dummy build rule to intercept # this and fail with an actionable error message. repository_ctx.file( "crosstool/error_gpu_disabled.bzl", _DUMMY_CROSSTOOL_BZL_FILE, ) repository_ctx.file("crosstool/BUILD", _DUMMY_CROSSTOOL_BUILD_FILE) def _compute_rocm_extra_copts(repository_ctx, amdgpu_targets): copts = [] for amdgpu_target in amdgpu_targets: copts.append("--offload-arch=%s" % amdgpu_target) return str(copts) def _create_local_rocm_repository(repository_ctx): """Creates the repository containing files set up to build with ROCm.""" tpl_paths = {labelname: tpl_gpus_path(repository_ctx, labelname) for labelname in [ "rocm:build_defs.bzl", "crosstool:BUILD.rocm", "crosstool:hipcc_cc_toolchain_config.bzl", "crosstool:clang/bin/crosstool_wrapper_driver_is_clang_for_hip", "rocm:rocm_config.h", "rocm:rocm_config.py", ]} tpl_paths["rocm:BUILD"] = tpl_gpus_path(repository_ctx, "rocm:BUILD") find_rocm_config_script = repository_ctx.path(Label("//third_party/gpus:find_rocm_config.py.gz.base64")) bash_bin = get_bash_bin(repository_ctx) rocm_config = _get_rocm_config(repository_ctx, bash_bin, find_rocm_config_script) rocm_lib_srcs = [rocm_config.config["hipruntime_library_dir"] + "/" + lib_name("amdhip64"), rocm_config.config["miopen_library_dir"] + "/" + lib_name("MIOpen"), rocm_config.config["migraphx_library_dir"] + "/" + lib_name("migraphx"), rocm_config.config["migraphx_library_dir"] + "/" + lib_name("migraphx_c"), rocm_config.config["migraphx_library_dir"] + "/" + lib_name("migraphx_tf"), rocm_config.config["migraphx_library_dir"] + "/" + lib_name("migraphx_device"), rocm_config.config["migraphx_library_dir"] + "/" + lib_name("migraphx_gpu"), rocm_config.config["migraphx_library_dir"] + "/" + lib_name("migraphx_ref"), rocm_config.config["migraphx_library_dir"] + "/" + lib_name("migraphx_onnx"), rocm_config.config["hipblas_library_dir"] + "/" + lib_name("hipblas"), rocm_config.config["rocblas_library_dir"] + "/" + lib_name("rocblas")] rocm_lib_outs = ["rocm/lib/" + lib_name("amdhip64"), "rocm/lib/" + lib_name("MIOpen"), "rocm/lib/" + lib_name("migraphx"), "rocm/lib/" + lib_name("migraphx_c"), "rocm/lib/" + lib_name("migraphx_tf"), "rocm/lib/" + lib_name("migraphx_device"), "rocm/lib/" + lib_name("migraphx_gpu"), "rocm/lib/" + lib_name("migraphx_ref"), "rocm/lib/" + lib_name("migraphx_onnx"), "rocm/lib/" + lib_name("hipblas"), "rocm/lib/" + lib_name("rocblas")] clang_offload_bundler_path = rocm_config.rocm_toolkit_path + "/llvm/bin/clang-offload-bundler" # Copy header and library files to execroot. copy_rules = [ make_copy_dir_rule( repository_ctx, name = "rocm-include", src_dir = rocm_config.config["rocm_header_path"], out_dir = "rocm/include", exceptions = ["gtest", "gmock"], ), make_copy_dir_rule( repository_ctx, name = "miopen-include", src_dir = rocm_config.rocm_toolkit_path + "/miopen/include", out_dir = "rocm/include/miopen", ), make_copy_dir_rule( repository_ctx, name = "migraphx-include", src_dir = rocm_config.rocm_toolkit_path + "/migraphx/include", out_dir = "rocm/include/migraphx", ), make_copy_dir_rule( repository_ctx, name = "hipblas-include", src_dir = rocm_config.rocm_toolkit_path + "/hipblas/include", out_dir = "rocm/include/hipblas", ), make_copy_files_rule( repository_ctx, name = "rocm-lib", srcs = rocm_lib_srcs, outs = rocm_lib_outs, ), make_copy_files_rule( repository_ctx, name = "rocm-bin", srcs = [ clang_offload_bundler_path, ], outs = [ "rocm/bin/" + "clang-offload-bundler", ], ) ] repository_dict = { "%{hip_lib}": lib_name("amdhip64"), "%{hipblas_lib}": lib_name("hipblas"), "%{rocblas_lib}": lib_name("rocblas"), "%{miopen_lib}": lib_name("MIOpen"), "%{migraphx_lib}": lib_name("migraphx"), "%{migraphx_c_lib}": lib_name("migraphx_c"), "%{migraphx_tf_lib}": lib_name("migraphx_tf"), "%{migraphx_device_lib}": lib_name("migraphx_device"), "%{migraphx_gpu_lib}": lib_name("migraphx_gpu"), "%{migraphx_ref_lib}": lib_name("migraphx_ref"), "%{migraphx_onnx_lib}": lib_name("migraphx_onnx"), "%{copy_rules}": "\n".join(copy_rules), "%{rocm_headers}": ('":rocm-include"') } # Set up BUILD file for rocm/ tpl_gpus( repository_ctx, "rocm:BUILD", repository_dict, ) repository_ctx.template( "rocm/build_defs.bzl", tpl_paths["rocm:build_defs.bzl"], { "%{rocm_extra_copts}": _compute_rocm_extra_copts( repository_ctx, rocm_config.amdgpu_targets, ), }, ) # Set up crosstool/ cc = find_cc(repository_ctx) host_compiler_includes = get_cxx_inc_directories(repository_ctx, cc) host_compiler_prefix = get_host_environ(repository_ctx, _GCC_HOST_COMPILER_PREFIX, "/usr/bin") rocm_defines = {} rocm_defines["%{host_compiler_prefix}"] = host_compiler_prefix rocm_defines["%{linker_bin_path}"] = host_compiler_prefix # For gcc, do not canonicalize system header paths; some versions of gcc # pick the shortest possible path for system includes when creating the # .d file - given that includes that are prefixed with "../" multiple # time quickly grow longer than the root of the tree, this can lead to # bazel's header check failing. rocm_defines["%{extra_no_canonical_prefixes_flags}"] = "\"-fno-canonical-system-headers\"" rocm_defines["%{unfiltered_compile_flags}"] = to_list_of_strings([ "-DTENSORFLOW_USE_ROCM=1", "-D__HIP_PLATFORM_AMD__", "-DEIGEN_USE_HIP", ]) rocm_defines["%{host_compiler_path}"] = "clang/bin/crosstool_wrapper_driver_is_clang_for_hip" rocm_defines["%{cxx_builtin_include_directories}"] = to_list_of_strings( host_compiler_includes + _rocm_include_path(repository_ctx, rocm_config, bash_bin), ) verify_build_defines(rocm_defines) # Only expand template variables in the BUILD file repository_ctx.template( "crosstool/BUILD", tpl_paths["crosstool:BUILD.rocm"], rocm_defines, ) # No templating of cc_toolchain_config - use attributes and templatize the # BUILD file. repository_ctx.template( "crosstool/hipcc_cc_toolchain_config.bzl", tpl_paths["crosstool:hipcc_cc_toolchain_config.bzl"], ) repository_ctx.template( "crosstool/clang/bin/crosstool_wrapper_driver_is_clang_for_hip", tpl_paths["crosstool:clang/bin/crosstool_wrapper_driver_is_clang_for_hip"], { "%{cpu_compiler}": str(cc), "%{hipcc_path}": rocm_config.rocm_toolkit_path + "/hip/bin/hipcc", "%{hipcc_env}": _hipcc_env(repository_ctx), "%{rocr_runtime_path}": rocm_config.rocm_toolkit_path + "/lib", "%{rocr_runtime_library}": "hsa-runtime64", "%{hip_runtime_path}": rocm_config.rocm_toolkit_path + "/hip/lib", "%{hip_runtime_library}": "amdhip64", "%{crosstool_verbose}": get_crosstool_verbose(repository_ctx), "%{gcc_host_compiler_path}": str(cc), }, ) # Set up rocm_config.h, which is used by # tensorflow/stream_executor/dso_loader.cc. repository_ctx.template( "rocm/rocm/rocm_config.h", tpl_paths["rocm:rocm_config.h"], { "%{rocm_amdgpu_targets}": ",".join( ["\"%s\"" % c for c in rocm_config.amdgpu_targets], ), "%{rocm_toolkit_path}": rocm_config.rocm_toolkit_path, "%{rocm_version_number}": rocm_config.rocm_version_number, "%{miopen_version_number}": rocm_config.miopen_version_number, "%{migraphx_version_number}": rocm_config.migraphx_version_number, "%{hipruntime_version_number}": rocm_config.hipruntime_version_number, "%{hipblas_version_number}": rocm_config.config["hipblas_version_number"], }, ) # Set up rocm_config.py, which is used by gen_build_info to provide # static build environment info to the API repository_ctx.template( "rocm/rocm/rocm_config.py", tpl_paths["rocm:rocm_config.py"], { "%{rocm_config}": str( { "rocm_version": rocm_config.rocm_version_number, "hip_version": rocm_config.hipruntime_version_number, "rocm_amdgpu_targets": ",".join( ["\"%s\"" % c for c in rocm_config.amdgpu_targets], ), "cpu_compiler": str(cc), } ), }, ) def _create_remote_rocm_repository(repository_ctx, remote_config_repo): """Creates pointers to a remotely configured repo set up to build with ROCm.""" def _rocm_autoconf_impl(repository_ctx): """Implementation of the rocm_autoconf repository rule.""" if not _enable_rocm(repository_ctx): _create_dummy_repository(repository_ctx) elif get_host_environ(repository_ctx, _TF_ROCM_CONFIG_REPO) != None: _create_remote_rocm_repository( repository_ctx, get_host_environ(repository_ctx, _TF_ROCM_CONFIG_REPO), ) else: _create_local_rocm_repository(repository_ctx) _ENVIRONS = [ _GCC_HOST_COMPILER_PATH, _GCC_HOST_COMPILER_PREFIX, _TF_NEED_ROCM, _ROCM_TOOLKIT_PATH, _TF_ROCM_AMDGPU_TARGETS, ] rocm_configure = repository_rule( implementation = _rocm_autoconf_impl, environ = _ENVIRONS + [_TF_ROCM_CONFIG_REPO], ) """Detects and configures the local ROCm toolchain. Add the following to your WORKSPACE FILE: ```python rocm_configure(name = "local_config_rocm") ``` Args: name: A unique name for this workspace rule. """
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/find_cuda_config.py
# Copyright 2019 The TensorFlow Authors. 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. # ============================================================================== # NOTE(storypku): Tailored to support Linux ONLY. # Origin: tensorflow/third_party/gpus/find_cuda_config.py # ============================================================================== """Prints CUDA library and header directories and versions found on the system. The script searches for CUDA library and header files on the system, inspects them to determine their version and prints the configuration to stdout. The paths to inspect and the required versions are specified through environment variables. If no valid configuration is found, the script prints to stderr and returns an error code. The list of libraries to find is specified as arguments. Supported libraries are CUDA (includes cuBLAS), cuDNN, NCCL, and TensorRT. The script takes a list of base directories specified by the TF_CUDA_PATHS environment variable as comma-separated glob list. The script looks for headers and library files in a hard-coded set of subdirectories from these base paths. If TF_CUDA_PATHS is not specified, a OS specific default is used: Linux: /usr/local/cuda, /usr, and paths from 'ldconfig -p'. For backwards compatibility, some libraries also use alternative base directories from other environment variables if they are specified. List of library-specific environment variables: Library Version env variable Additional base directories ---------------------------------------------------------------- CUDA TF_CUDA_VERSION CUDA_TOOLKIT_PATH cuBLAS TF_CUBLAS_VERSION CUDA_TOOLKIT_PATH cuDNN TF_CUDNN_VERSION CUDNN_INSTALL_PATH NCCL TF_NCCL_VERSION NCCL_INSTALL_PATH, NCCL_HDR_PATH TensorRT TF_TENSORRT_VERSION TENSORRT_INSTALL_PATH Versions environment variables can be of the form 'x' or 'x.y' to request a specific version, empty or unspecified to accept any version. The output of a found library is of the form: tf_<library>_version: x.y.z tf_<library>_header_dir: ... tf_<library>_library_dir: ... """ import io import os import glob import platform import re import subprocess import sys # pylint: disable=g-import-not-at-top try: from shutil import which except ImportError: from distutils.spawn import find_executable as which # pylint: enable=g-import-not-at-top class ConfigError(Exception): pass def _is_linux(): return platform.system() == "Linux" def _matches_version(actual_version, required_version): """Checks whether some version meets the requirements. All elements of the required_version need to be present in the actual_version. required_version actual_version result ----------------------------------------- 1 1.1 True 1.2 1 False 1.2 1.3 False 1 True Args: required_version: The version specified by the user. actual_version: The version detected from the CUDA installation. Returns: Whether the actual version matches the required one. """ if actual_version is None: return False # Strip spaces from the versions. actual_version = actual_version.strip() required_version = required_version.strip() return actual_version.startswith(required_version) def _at_least_version(actual_version, required_version): actual = [int(v) for v in actual_version.split(".")] required = [int(v) for v in required_version.split(".")] return actual >= required def _get_header_version(path, name): """Returns preprocessor defines in C header file.""" for line in io.open(path, "r", encoding="utf-8").readlines(): match = re.match(r"#define %s +(\d+)" % name, line) if match: return match.group(1) return "" def _cartesian_product(first, second): """Returns all path combinations of first and second.""" return [os.path.join(f, s) for f in first for s in second] def _get_ld_config_paths(): """Returns all directories from 'ldconfig -p'.""" if not _is_linux(): return [] ldconfig_path = which("ldconfig") or "/sbin/ldconfig" output = subprocess.check_output([ldconfig_path, "-p"]) pattern = re.compile(".* => (.*)") result = set() for line in output.splitlines(): try: match = pattern.match(line.decode("ascii")) except UnicodeDecodeError: match = False if match: result.add(os.path.dirname(match.group(1))) return sorted(list(result)) def _get_default_cuda_paths(cuda_version): if not cuda_version: cuda_version = "*" elif not "." in cuda_version: cuda_version = cuda_version + ".*" return ["/usr/local/cuda-%s" % cuda_version, "/usr/local/cuda", "/usr", "/usr/local/cudnn"] + _get_ld_config_paths() def _header_paths(): """Returns hard-coded set of relative paths to look for header files.""" return [ "", "include", "include/cuda", "include/*-linux-gnu", "extras/CUPTI/include", "include/cuda/CUPTI", "local/cuda/extras/CUPTI/include", ] def _library_paths(): """Returns hard-coded set of relative paths to look for library files.""" return [ "", "lib64", "lib", "lib/*-linux-gnu", "lib/x64", "extras/CUPTI/*", "local/cuda/lib64", "local/cuda/extras/CUPTI/lib64", ] def _not_found_error(base_paths, relative_paths, filepattern): base_paths = "".join(["\n '%s'" % path for path in sorted(base_paths)]) relative_paths = "".join(["\n '%s'" % path for path in relative_paths]) return ConfigError( "Could not find any %s in any subdirectory:%s\nof:%s\n" % (filepattern, relative_paths, base_paths)) def _find_file(base_paths, relative_paths, filepattern): for path in _cartesian_product(base_paths, relative_paths): for file in glob.glob(os.path.join(path, filepattern)): return file raise _not_found_error(base_paths, relative_paths, filepattern) def _find_library(base_paths, library_name, required_version): """Returns first valid path to the requested library.""" filepattern = ".".join(["lib" + library_name, "so"] + required_version.split(".")[:1]) + "*" return _find_file(base_paths, _library_paths(), filepattern) def _find_versioned_file(base_paths, relative_paths, filepatterns, required_version, get_version): """Returns first valid path to a file that matches the requested version.""" if type(filepatterns) not in [list, tuple]: filepatterns = [filepatterns] for path in _cartesian_product(base_paths, relative_paths): for filepattern in filepatterns: for file in glob.glob(os.path.join(path, filepattern)): actual_version = get_version(file) if _matches_version(actual_version, required_version): return file, actual_version raise _not_found_error( base_paths, relative_paths, ", ".join(filepatterns) + " matching version '%s'" % required_version) def _find_header(base_paths, header_name, required_version, get_version): """Returns first valid path to a header that matches the requested version.""" return _find_versioned_file(base_paths, _header_paths(), header_name, required_version, get_version) def _find_cuda_config(base_paths, required_version): def get_header_version(path): version = int(_get_header_version(path, "CUDA_VERSION")) if not version: return None return "%d.%d" % (version // 1000, version % 1000 // 10) cuda_header_path, header_version = _find_header(base_paths, "cuda.h", required_version, get_header_version) cuda_version = header_version # x.y, see above. cuda_library_path = _find_library(base_paths, "cudart", cuda_version) def get_nvcc_version(path): pattern = r"Cuda compilation tools, release \d+\.\d+, V(\d+\.\d+\.\d+)" for line in subprocess.check_output([path, "--version"]).splitlines(): match = re.match(pattern, line.decode("ascii")) if match: return match.group(1) return None nvcc_name = "nvcc" nvcc_path, nvcc_version = _find_versioned_file(base_paths, [ "", "bin", "local/cuda/bin", ], nvcc_name, cuda_version, get_nvcc_version) nvvm_path = _find_file(base_paths, [ "nvvm/libdevice", "share/cuda", "lib/nvidia-cuda-toolkit/libdevice", "local/cuda/nvvm/libdevice", ], "libdevice*.10.bc") cupti_header_path = _find_file(base_paths, _header_paths(), "cupti.h") cupti_library_path = _find_library(base_paths, "cupti", required_version) cuda_binary_dir = os.path.dirname(nvcc_path) nvvm_library_dir = os.path.dirname(nvvm_path) # XLA requires the toolkit path to find ptxas and libdevice. # TODO(csigg): pass in both directories instead. cuda_toolkit_paths = ( os.path.normpath(os.path.join(cuda_binary_dir, "..")), os.path.normpath(os.path.join(nvvm_library_dir, "../..")), ) if cuda_toolkit_paths[0] != cuda_toolkit_paths[1]: raise ConfigError("Inconsistent CUDA toolkit path: %s vs %s" % cuda_toolkit_paths) return { "cuda_version": cuda_version, "cuda_include_dir": os.path.dirname(cuda_header_path), "cuda_library_dir": os.path.dirname(cuda_library_path), "cuda_binary_dir": cuda_binary_dir, "nvvm_library_dir": nvvm_library_dir, "cupti_include_dir": os.path.dirname(cupti_header_path), "cupti_library_dir": os.path.dirname(cupti_library_path), "cuda_toolkit_path": cuda_toolkit_paths[0], } def _find_cublas_config(base_paths, required_version, cuda_version): if _at_least_version(cuda_version, "10.1"): def get_header_version(path): version = ( _get_header_version(path, name) for name in ("CUBLAS_VER_MAJOR", "CUBLAS_VER_MINOR", "CUBLAS_VER_PATCH")) return ".".join(version) header_path, header_version = _find_header(base_paths, "cublas_api.h", required_version, get_header_version) # cuBLAS uses the major version only. cublas_version = header_version.split(".")[0] else: # There is no version info available before CUDA 10.1, just find the # file. header_version = cuda_version header_path = _find_file(base_paths, _header_paths(), "cublas_api.h") # cuBLAS version is the same as CUDA version (x.y). cublas_version = required_version library_path = _find_library(base_paths, "cublas", cublas_version) return { "cublas_version": header_version, "cublas_include_dir": os.path.dirname(header_path), "cublas_library_dir": os.path.dirname(library_path), } def _find_cusolver_config(base_paths, required_version, cuda_version): if _at_least_version(cuda_version, "11.0"): def get_header_version(path): version = ( _get_header_version(path, name) for name in ("CUSOLVER_VER_MAJOR", "CUSOLVER_VER_MINOR", "CUSOLVER_VER_PATCH")) return ".".join(version) header_path, header_version = _find_header(base_paths, "cusolver_common.h", required_version, get_header_version) cusolver_version = header_version.split(".")[0] else: header_version = cuda_version header_path = _find_file( base_paths, _header_paths(), "cusolver_common.h") cusolver_version = required_version library_path = _find_library(base_paths, "cusolver", cusolver_version) return { "cusolver_version": header_version, "cusolver_include_dir": os.path.dirname(header_path), "cusolver_library_dir": os.path.dirname(library_path), } def _find_curand_config(base_paths, required_version, cuda_version): if _at_least_version(cuda_version, "11.0"): def get_header_version(path): version = ( _get_header_version(path, name) for name in ("CURAND_VER_MAJOR", "CURAND_VER_MINOR", "CURAND_VER_PATCH")) return ".".join(version) header_path, header_version = _find_header(base_paths, "curand.h", required_version, get_header_version) curand_version = header_version.split(".")[0] else: header_version = cuda_version header_path = _find_file(base_paths, _header_paths(), "curand.h") curand_version = required_version library_path = _find_library(base_paths, "curand", curand_version) return { "curand_version": header_version, "curand_include_dir": os.path.dirname(header_path), "curand_library_dir": os.path.dirname(library_path), } def _find_cufft_config(base_paths, required_version, cuda_version): if _at_least_version(cuda_version, "11.0"): def get_header_version(path): version = ( _get_header_version(path, name) for name in ("CUFFT_VER_MAJOR", "CUFFT_VER_MINOR", "CUFFT_VER_PATCH")) return ".".join(version) header_path, header_version = _find_header(base_paths, "cufft.h", required_version, get_header_version) cufft_version = header_version.split(".")[0] else: header_version = cuda_version header_path = _find_file(base_paths, _header_paths(), "cufft.h") cufft_version = required_version library_path = _find_library(base_paths, "cufft", cufft_version) return { "cufft_version": header_version, "cufft_include_dir": os.path.dirname(header_path), "cufft_library_dir": os.path.dirname(library_path), } def _find_cudnn_config(base_paths, required_version): def get_header_version(path): version = [ _get_header_version(path, name) for name in ("CUDNN_MAJOR", "CUDNN_MINOR", "CUDNN_PATCHLEVEL")] return ".".join(version) if version[0] else None header_path, header_version = _find_header(base_paths, ("cudnn.h", "cudnn_version.h"), required_version, get_header_version) cudnn_version = header_version.split(".")[0] library_path = _find_library(base_paths, "cudnn", cudnn_version) return { "cudnn_version": cudnn_version, "cudnn_include_dir": os.path.dirname(header_path), "cudnn_library_dir": os.path.dirname(library_path), } def _find_cusparse_config(base_paths, required_version, cuda_version): if _at_least_version(cuda_version, "11.0"): def get_header_version(path): version = ( _get_header_version(path, name) for name in ("CUSPARSE_VER_MAJOR", "CUSPARSE_VER_MINOR", "CUSPARSE_VER_PATCH")) return ".".join(version) header_path, header_version = _find_header(base_paths, "cusparse.h", required_version, get_header_version) cusparse_version = header_version.split(".")[0] else: header_version = cuda_version header_path = _find_file(base_paths, _header_paths(), "cusparse.h") cusparse_version = required_version library_path = _find_library(base_paths, "cusparse", cusparse_version) return { "cusparse_version": header_version, "cusparse_include_dir": os.path.dirname(header_path), "cusparse_library_dir": os.path.dirname(library_path), } def _find_nccl_config(base_paths, required_version): def get_header_version(path): version = ( _get_header_version(path, name) for name in ("NCCL_MAJOR", "NCCL_MINOR", "NCCL_PATCH")) return ".".join(version) header_path, header_version = _find_header(base_paths, "nccl.h", required_version, get_header_version) nccl_version = header_version.split(".")[0] library_path = _find_library(base_paths, "nccl", nccl_version) return { "nccl_version": nccl_version, "nccl_include_dir": os.path.dirname(header_path), "nccl_library_dir": os.path.dirname(library_path), } def _find_tensorrt_config(base_paths, required_version): def get_header_version(path): version = ( _get_header_version(path, name) for name in ("NV_TENSORRT_MAJOR", "NV_TENSORRT_MINOR", "NV_TENSORRT_PATCH")) # `version` is a generator object, so we convert it to a list before using # it (muitiple times below). version = list(version) if not all(version): # Versions not found, make _matches_version returns False. return None return ".".join(version) try: header_path, header_version = _find_header(base_paths, "NvInfer.h", required_version, get_header_version) except ConfigError: # TensorRT 6 moved the version information to NvInferVersion.h. header_path, header_version = _find_header(base_paths, "NvInferVersion.h", required_version, get_header_version) tensorrt_version = header_version.split(".")[0] library_path = _find_library(base_paths, "nvinfer", tensorrt_version) return { "tensorrt_version": tensorrt_version, "tensorrt_include_dir": os.path.dirname(header_path), "tensorrt_library_dir": os.path.dirname(library_path), } def _list_from_env(env_name, default=[]): """Returns comma-separated list from environment variable.""" if env_name in os.environ: return os.environ[env_name].split(",") return default def _get_legacy_path(env_name, default=[]): """Returns a path specified by a legacy environment variable. CUDNN_INSTALL_PATH, NCCL_INSTALL_PATH, TENSORRT_INSTALL_PATH set to '/usr/lib/x86_64-linux-gnu' would previously find both library and header paths. Detect those and return '/usr', otherwise forward to _list_from_env(). """ if env_name in os.environ: match = re.match( r"^(/[^/ ]*)+/lib/\w+-linux-gnu/?$", os.environ[env_name]) if match: return [match.group(1)] return _list_from_env(env_name, default) def _normalize_path(path): """Returns normalized path, with forward slashes on Windows.""" return os.path.realpath(path) def find_cuda_config(): """Returns a dictionary of CUDA library and header file paths.""" libraries = [argv.lower() for argv in sys.argv[1:]] cuda_version = os.environ.get("TF_CUDA_VERSION", "") base_paths = _list_from_env("TF_CUDA_PATHS", _get_default_cuda_paths(cuda_version)) base_paths = [path for path in base_paths if os.path.exists(path)] result = {} if "cuda" in libraries: cuda_paths = _list_from_env("CUDA_TOOLKIT_PATH", base_paths) result.update(_find_cuda_config(cuda_paths, cuda_version)) cuda_version = result["cuda_version"] cublas_paths = base_paths if tuple(int(v) for v in cuda_version.split(".")) < (10, 1): # Before CUDA 10.1, cuBLAS was in the same directory as the # toolkit. cublas_paths = cuda_paths cublas_version = os.environ.get("TF_CUBLAS_VERSION", "") result.update( _find_cublas_config(cublas_paths, cublas_version, cuda_version)) cusolver_paths = base_paths if tuple(int(v) for v in cuda_version.split(".")) < (11, 0): cusolver_paths = cuda_paths cusolver_version = os.environ.get("TF_CUSOLVER_VERSION", "") result.update( _find_cusolver_config(cusolver_paths, cusolver_version, cuda_version)) curand_paths = base_paths if tuple(int(v) for v in cuda_version.split(".")) < (11, 0): curand_paths = cuda_paths curand_version = os.environ.get("TF_CURAND_VERSION", "") result.update( _find_curand_config(curand_paths, curand_version, cuda_version)) cufft_paths = base_paths if tuple(int(v) for v in cuda_version.split(".")) < (11, 0): cufft_paths = cuda_paths cufft_version = os.environ.get("TF_CUFFT_VERSION", "") result.update( _find_cufft_config( cufft_paths, cufft_version, cuda_version)) cusparse_paths = base_paths if tuple(int(v) for v in cuda_version.split(".")) < (11, 0): cusparse_paths = cuda_paths cusparse_version = os.environ.get("TF_CUSPARSE_VERSION", "") result.update( _find_cusparse_config(cusparse_paths, cusparse_version, cuda_version)) if "cudnn" in libraries: cudnn_paths = _get_legacy_path("CUDNN_INSTALL_PATH", base_paths) cudnn_version = os.environ.get("TF_CUDNN_VERSION", "") result.update(_find_cudnn_config(cudnn_paths, cudnn_version)) if "nccl" in libraries: nccl_paths = _get_legacy_path("NCCL_INSTALL_PATH", base_paths) nccl_version = os.environ.get("TF_NCCL_VERSION", "") result.update(_find_nccl_config(nccl_paths, nccl_version)) if "tensorrt" in libraries: tensorrt_paths = _get_legacy_path("TENSORRT_INSTALL_PATH", base_paths) tensorrt_version = os.environ.get("TF_TENSORRT_VERSION", "") result.update(_find_tensorrt_config(tensorrt_paths, tensorrt_version)) for k, v in result.items(): if k.endswith("_dir") or k.endswith("_path"): result[k] = _normalize_path(v) return result def main(): try: for key, value in sorted(find_cuda_config().items()): print("%s: %s" % (key, value)) except ConfigError as e: sys.stderr.write(str(e)) sys.exit(1) if __name__ == "__main__": main()
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/compress_find_rocm_config.py
#! /usr/bin/env python3 # Copyright 2020 The TensorFlow Authors. 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. # ============================================================================== """Compresses the contents of 'find_rocm_config.py'. The compressed file is what is actually being used. It works around remote config not being able to upload files yet. """ import base64 import zlib def main(): with open('find_rocm_config.py', 'rb') as f: data = f.read() compressed = zlib.compress(data) b64encoded = base64.b64encode(compressed) with open('find_rocm_config.py.gz.base64', 'wb') as f: f.write(b64encoded) if __name__ == '__main__': main()
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/cyberfile.xml
<package format="2"> <name>3rd-gpus</name> <version>local</version> <description> Apollo packaged 3rd-gpu Libs. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <depend expose="False">3rd-bazel-skylib-dev</depend> <type>third-wrapper</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/gpus</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/README.md
# CUDA Support for Bazel ## Introduction Since there is no native CUDA support in Bazel (Ref: [Bazel Issue #6578: Native CUDA Support](https://github.com/bazelbuild/bazel/issues/6578)), the Authors of Apollo borrowed CUDA support for Bazel from [TensorFlow](https://https://github.com/tensorflow/tensorflow) project. ## Status Support upto CUDA Toolkit 11.1 and cuDNN8 ## How to generate `find_cuda_config.py.gz.base64` ``` cd ${APOLLO_ROOT_DIR}/third_party/gpus/ python3 compress_find_cuda_config.py ``` ## Notes Please note that CUDA support for Bazel in Apollo was tailored to run on Linux ONLY. Windows and MacOS support were stripped off which are available in the original TensorFlow project. As for CPU architecture, only `x86_64` and `aarch64(arm64)` support was reserved.
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/find_rocm_config.py
# Copyright 2020 The TensorFlow Authors. 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. # ============================================================================== """Prints ROCm library and header directories and versions found on the system. The script searches for ROCm library and header files on the system, inspects them to determine their version and prints the configuration to stdout. The path to inspect is specified through an environment variable (ROCM_PATH). If no valid configuration is found, the script prints to stderr and returns an error code. The script takes the directory specified by the ROCM_PATH environment variable. The script looks for headers and library files in a hard-coded set of subdirectories from base path of the specified directory. If ROCM_PATH is not specified, then "/opt/rocm" is used as it default value """ import io import os import re import sys import glob def _header_paths(): """Returns hard-coded set of relative paths to look for header files.""" return [ "", "include", "include/rocm", "include/*-linux-gnu", ".info" ] def _library_paths(): """Returns hard-coded set of relative paths to look for library files.""" return [ "", "lib64", "lib", "lib/*-linux-gnu", "lib64/stubs" ] class ConfigError(Exception): pass def _matches_version(actual_version, required_version): """Checks whether some version meets the requirements. All elements of the required_version need to be present in the actual_version. required_version actual_version result ----------------------------------------- 1 1.1 True 1.2 1 False 1.2 1.3 False 1 True Args: required_version: The version specified by the user. actual_version: The version detected from the CUDA installation. Returns: Whether the actual version matches the required one. """ if actual_version is None: return False # Strip spaces from the versions. actual_version = str(actual_version).strip() required_version = str(required_version).strip() return actual_version.startswith(required_version) def _cartesian_product(first, second): """Returns all path combinations of first and second.""" return [os.path.join(f, s) for f in first for s in second] def _not_found_error(base_paths, relative_paths, filepattern): base_paths = "".join(["\n '%s'" % path for path in sorted(base_paths)]) relative_paths = "".join(["\n '%s'" % path for path in relative_paths]) return ConfigError( "Could not find any %s in any subdirectory:%s\nof:%s\n" % (filepattern, relative_paths, base_paths)) def _find_file(base_paths, relative_paths, filepattern): for path in _cartesian_product(base_paths, relative_paths): for file in glob.glob(os.path.join(path, filepattern)): return file raise _not_found_error(base_paths, relative_paths, filepattern) def _find_library(base_paths, library_name, required_version, library_paths): """Returns first valid path to the requested library.""" filepattern = ".".join(["lib" + library_name, "so"] + required_version.split(".")[:1]) + "*" return _find_file(base_paths, library_paths(), filepattern) def _find_versioned_file(base_paths, relative_paths, filepatterns, required_version, get_version): """Returns first valid path to a file that matches the requested version.""" if type(filepatterns) not in [list, tuple]: filepatterns = [filepatterns] for path in _cartesian_product(base_paths, relative_paths): for filepattern in filepatterns: for file in glob.glob(os.path.join(path, filepattern)): actual_version = get_version(file) if _matches_version(actual_version, required_version): return file, actual_version raise _not_found_error( base_paths, relative_paths, ", ".join(filepatterns) + " matching version '%s'" % required_version) def _find_header(base_paths, header_name, required_version, get_version, header_paths): """Returns first valid path to a header that matches the requested version.""" return _find_versioned_file(base_paths, header_paths(), header_name, required_version, get_version) def _get_path_if_link(path): if os.path.islink(path): return os.path.realpath(path) return path def _get_default_rocm_path(): return "/opt/rocm" def _get_rocm_install_path(): """Determines and returns the ROCm installation path.""" rocm_install_path = os.environ.get("ROCM_PATH", _get_default_rocm_path()) return _get_path_if_link(rocm_install_path) def _get_composite_version_number(major, minor, patch): return 10000 * major + 100 * minor + patch def _get_header_version(path, name): """Returns preprocessor defines in C header file.""" for line in io.open(path, "r", encoding="utf-8"): match = re.match(r"#define %s +(\d+)" % name, line) if match: value = match.group(1) return int(value) raise ConfigError('#define "{}" is either\n'.format(name) + " not present in file {} OR\n".format(path) + " its value is not an integer literal") def _find_rocm_config(rocm_install_path, required_version=""): def rocm_version_numbers_pre_rocm50(version_file): if not os.path.exists(version_file): return None version_numbers = [] with open(version_file) as f: version_string = f.read().strip() version_numbers = version_string.split(".") major = int(version_numbers[0]) minor = int(version_numbers[1]) patch = int(version_numbers[2].split("-")[0]) return _get_composite_version_number(major, minor, patch) def rocm_version_numbers_post_rocm50(version_file): if not os.path.exists(version_file): return None major = _get_header_version(version_file, "ROCM_VERSION_MAJOR") minor = _get_header_version(version_file, "ROCM_VERSION_MINOR") patch = _get_header_version(version_file, "ROCM_VERSION_PATCH") return _get_composite_version_number(major, minor, patch) try: rocm_header_path, header_version = _find_header([rocm_install_path], "rocm_version.h", required_version, rocm_version_numbers_post_rocm50, _header_paths) except ConfigError as e:\ rocm_header_path, header_version = _find_header([rocm_install_path], "version-dev", required_version, rocm_version_numbers_pre_rocm50, _header_paths) rocm_config = { "rocm_version_number": header_version, "rocm_header_path": os.path.dirname(rocm_header_path) } return rocm_config def _find_hipruntime_config(rocm_install_path, required_version=""): def hipruntime_version_number(version_file): if not os.path.exists(version_file): raise ConfigError( 'HIP Runtime version file "{}" not found'.format(version_file)) # This header file has an explicit #define for HIP_VERSION, whose value # is (HIP_VERSION_MAJOR * 100 + HIP_VERSION_MINOR) # Retreive the major + minor and re-calculate here, since we do not # want get into the business of parsing arith exprs major = _get_header_version(version_file, "HIP_VERSION_MAJOR") minor = _get_header_version(version_file, "HIP_VERSION_MINOR") return 100 * major + minor header_path, header_version = _find_header([rocm_install_path], "hip/include/hip/hip_version.h", required_version, hipruntime_version_number, _header_paths) library_path = _find_library([rocm_install_path], "amdhip64", required_version, _library_paths) library_path = _get_path_if_link(library_path) hipruntime_config = { "hipruntime_include_dir": os.path.dirname(header_path), "hipruntime_version_number": header_version, "hipruntime_library_dir": os.path.dirname(library_path) } return hipruntime_config def _find_miopen_config(rocm_install_path, required_version=''): def miopen_version_numbers(version_file): if not os.path.exists(version_file): raise ConfigError( 'MIOpen version file "{}" not found'.format(version_file)) major = _get_header_version(version_file, "MIOPEN_VERSION_MAJOR") minor = _get_header_version(version_file, "MIOPEN_VERSION_MINOR") patch = _get_header_version(version_file, "MIOPEN_VERSION_PATCH") return _get_composite_version_number(major, minor, patch) header_path, header_version = _find_header([rocm_install_path], "miopen/include/miopen/version.h", required_version, miopen_version_numbers, _header_paths) library_path = _find_library([rocm_install_path], "MIOpen", required_version, _library_paths) library_path = _get_path_if_link(library_path) miopen_config = { "miopen_version_number": header_version, "miopen_include_dir": os.path.dirname(header_path), "miopen_library_dir": os.path.dirname(library_path) } return miopen_config def _find_migraphx_config(rocm_install_path, required_version=''): def migraphx_version_numbers(version_file): if not os.path.exists(version_file): raise ConfigError( 'MIGraphX version file "{}" not found'.format(version_file)) major = _get_header_version(version_file, "MIGRAPHX_VERSION_MAJOR") minor = _get_header_version(version_file, "MIGRAPHX_VERSION_MINOR") patch = 0 return _get_composite_version_number(major, minor, patch) header_path, header_version = _find_header([rocm_install_path], "migraphx/include/migraphx/version.h", required_version, migraphx_version_numbers, _header_paths) library_path = _find_library([rocm_install_path], "migraphx", required_version, _library_paths) library_path = _get_path_if_link(library_path) migraphx_config = { "migraphx_version_number": header_version, "migraphx_include_dir": os.path.dirname(header_path), "migraphx_library_dir": os.path.dirname(library_path) } return migraphx_config def _find_hipblas_config(rocm_install_path, required_version=''): def hipblas_version_numbers(version_file): if not os.path.exists(version_file): raise ConfigError( 'hipblas version file "{}" not found'.format(version_file)) major = _get_header_version(version_file, "hipblasVersionMajor") # ToDo: Fix typo in "hipblaseVersionMinor" with switching to ROCM 5.1.0 or higher, where the typo is fixed minor = _get_header_version(version_file, "hipblaseVersionMinor") patch = _get_header_version(version_file, "hipblasVersionPatch") return _get_composite_version_number(major, minor, patch) header_path, header_version = _find_header([rocm_install_path], "hipblas/include/hipblas-version.h", required_version, hipblas_version_numbers, _header_paths) library_path = _find_library([rocm_install_path], "hipblas", required_version, _library_paths) library_path = _get_path_if_link(library_path) hipblas_config = { "hipblas_version_number": header_version, "hipblas_include_dir": os.path.dirname(header_path), "hipblas_library_dir": os.path.dirname(library_path) } return hipblas_config def _find_rocblas_config(rocm_install_path, required_version=''): def rocblas_version_numbers(version_file): if not os.path.exists(version_file): raise ConfigError( 'rocblas version file "{}" not found'.format(version_file)) major = _get_header_version(version_file, "ROCBLAS_VERSION_MAJOR") minor = _get_header_version(version_file, "ROCBLAS_VERSION_MINOR") patch = _get_header_version(version_file, "ROCBLAS_VERSION_PATCH") return _get_composite_version_number(major, minor, patch) header_path, header_version = _find_header([rocm_install_path], "rocblas/include/internal/rocblas-version.h", required_version, rocblas_version_numbers, _header_paths) library_path = _find_library([rocm_install_path], "rocblas", required_version, _library_paths) library_path = _get_path_if_link(library_path) rocblas_config = { "rocblas_version_number": header_version, "rocblas_include_dir": os.path.dirname(header_path), "rocblas_library_dir": os.path.dirname(library_path) } return rocblas_config def find_rocm_config(): """Returns a dictionary of ROCm components config info.""" rocm_install_path = _get_rocm_install_path() if not os.path.exists(rocm_install_path): raise ConfigError( 'Specified ROCM_PATH "{}" does not exist'.format(rocm_install_path)) result = {} result["rocm_toolkit_path"] = rocm_install_path result.update(_find_rocm_config(rocm_install_path, os.environ.get("TF_ROCM_VERSION", ""))) result.update(_find_hipruntime_config(rocm_install_path, os.environ.get("TF_HIP_VERSION", ""))) result.update(_find_miopen_config(rocm_install_path, os.environ.get("TF_MIOPEN_VERSION", ""))) result.update(_find_migraphx_config(rocm_install_path, os.environ.get("TF_MIGRAPHX_VERSION", ""))) result.update(_find_hipblas_config(rocm_install_path, os.environ.get("TF_HIPBLAS_VERSION", ""))) result.update(_find_rocblas_config(rocm_install_path, os.environ.get("TF_ROCBLAS_VERSION", ""))) return result def main(): try: for key, value in sorted(find_rocm_config().items()): print("%s: %s" % (key, value)) except ConfigError as e: sys.stderr.write("\nERROR: {}\n\n".format(str(e))) sys.exit(1) if __name__ == "__main__": main()
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/find_rocm_config.py.gz.base64
eJzVW+tP40gS/47E/9DyaoSzEwzM3Z5OOfGBZZgd7mZgFNiXAEVO3El6x3H7um0eWs3/flX9cLptk5CEBV20O/jRVV1dj19VP/wdOeb5g2CTaUHe7b/bJ5dTSi5pJrn4kPI7clQWUy5kRI7SlPSxmSR9Kqm4pUm0vfUd/Ec+sREQ0ISUWUIFKYDDUR6P4I950yW/UCEZz8i7aJ+E2CAwr4LOv5DFAy/JLH4gGS9IKSnwYJKMWUoJvR/RvCAsIyM+y1MWZyNK7lgxVf0YLigJ+d3w4MMihuYxEORwN3YbkrgwQuNvWhR5b2/v7u4uipXAEReTvVQ3lXufTo9Pzi5OdkFoQ/RzllIpiaD/LZmAAQ8fSJyDUKN4CKKm8R3hgsQTQeFdwVHoO8EKlk26RPJxcRcLimwSJgvBhmXh6cyKCCN3G4DW4owERxfk9CIgPx5dnF50kcmvp5cfz3++JL8e9ftHZ5enJxfkvE+Oz8/en16enp/B3QdydPY7+c/p2fsuoaAx6Ife5wJHAGIy1KY2Irmg1BNhzLVIMqcjNmYjGFo2KeMJJRN+S0UGIyI5FTMm0aoSBEyQTcpmrIgL9agxLtXR4bP+treCIPgiWIZOeX48AwGGIhYPKA+Z0hglSMBQo4ILRpWY5FZ7IngXBxFRu2qgD7KgMxBxewsDQI4EA6eTNBbgFVLp47EO0Eulz6cLlkfVFXJ7C57O0BcSWqDCMqVoJqwcilOuh4AMRjwbs0kplBaRThYJL4tIy5XH6PfcskdXMSZCh5sKXk6m6C00u2WCZzOaFeQ2Fky5Zwgj+Dz4cnT5sQPsTscQbPAyZUmtU2Z009Uj0qqwIiqBqBDa5IIWpVD2J/AMlDTiCa1rsYi/Uj04a4sHR2oIIXxVydYqe+QxTDn/qm2iTaANa02j7aEAYBqLZBdFSsCUBUDB9pYsh65HjAWfkWEsjWoNWMylqySOCChsLiToCKAK2NmWSlkQpns8L/YEH80CbFMiKsYgTQH2H8dlikNKS4oaAtfFPxCGXIAleXXJZXWJcGEuwbOq60nKh0i7vQVcyUBrYYAjkGGnt72F2Abs+8Y6DTUA3xRsfatHrayKOnVUqrUYKRmRmzY0udJ3mn/XuWHZKC0T2vZMa6Ptxfe7KcvK+91JVnrvI5aNuen4xhmnsfAzDdTzl6ePFMj+8ff6k/r9o0NT1HuyKIfSH+AojQGWj1UgnmAohScq8UFA2oHm0MLRxiwuEJsGBkjCeFSUcWpvu1WSsk8cfR1P6Qgi6G5KVVKQfEYrPJpRaqDIMMBAlCqm7SiwFKCpfmFDpt4byUwOHILuIeVgNDOFkXM+vsReF9oSNZY1AmwhIaR8qt2n/nyyA1L/HUT+s0tR0hpN9K5OU7v/EKdyOVH0t2VEzV+9Jy2dYyMxkT2XSV2bPVXpWVU28BiQS0Quva97nxpz2whrFQWnSH788/sjzFJFnKYqqzi8TLT2yK/G/5BAs597oXZuz7Ugx9Ko8mF9wcZ1pwDUPYOGzthNRBu16udQ8kCBlcO445FNA8V8RNL0U+N9CMlP1AKtE2GplocdCx81p9U0jWCsUykRawEB2hOFxFq3Se8AwQhaUQmF8SAXPClHRThmQhZQclJI7EkLToJRdL6DknrIMlOxQSQrQpVNNW0TFrmMkDL6g7MsHEMfHQWmYwxuTY23Kv9qFi6AQ8ocqNJioKqFEBOvRvNuhdT2HmEZLqFoqpBr3hy0GgRahqvgOrOW3nkjdwLyZlHsqGGjiOoCpYSEShNHlM5NZRRXovW7bO3WZ37j+4GbBpzkcczLNFFTpDEDE8XZA3mjKx24cgqbh94beZ3xsfrjCRc6Wm2q3NGB61/Y2QAJV7WXO94WL32cW8eJXuVdOBEEJlj3RPhP6LkhXvkCdHr1VKL0ik2MomMGNd/aDlnXjqklPHpbrWTxjDaz8fy9N2InSHU06QLd1v0WDqlEtDUc5kHqiIjuGlX+iiUKeVsTKZA8uFnouG8bYkcSJo1FCKw7V72Dmw40Cb73IeIRf6kVb4v1aXqjq/md7C4YTdMAE1q01EaL1B9rTyymcdHIUNokVk1ugioecuoGHkAmxjD481XKEKeLMk/pjevzTmMw5JV7f/MXxJb1GZZ5XdeC6FkiEX+NrOpYQimq06RhG1S8TVeo0KBbE2YhOsy5LXBIB68hxEye9IwPIaO9B1dRrBJMHmmOoR4aen7mGdjM/x4DGke7VdtVQCe2c8JV/N4DgwXh7M9d/bEsS6rLgtpRHT7GPgZsDGCdfVWeqscPnmV9mMnaO2ckto2gcYoXuhU2Mg3wvtajmfMPcAasujeTVkPhLBbUCBWBKZ9dQlDve7uOpFc97AqMWUOZeUW3ksnapMETAg8GZZZbIug2DKoFDvDdx0bgjrmp10YvdSvgKi6XrKDWTIOsnA3Bo2fxH1x0CQwN/+ToZp62DvbhR74nqh0E0YG+w+Zwp9rXujK+ZOFCgxN6VqVM6/YwQwXkhJkAVIO4UqPUCzB37C6HWEXqxYNM4SDjEc+p5R0I0BvNRjyB0D4MymK8+8/AepIKHNC5oJG6DEXwne4Kq7i34XXytoMIoMMYO+hUKUQRVB6plpCAk3oaTQQv8/CgU/NXlhWhatjRcx6NaW5luWO7D/78plar9BrxdbYTwRCBeah0Rd62x2FAVBpzJvcqOfz5jZz3oey0PJQPLODBCmkGpNfUcC0RZKcTiloGX4/ToAGCysv0qmXT45oYeBgoK6AMyENR+N4nIXNSxfaH/dC+UqmoVxkBhbMoQO8hc8vWlpUFcBqqH9X6wpRu0rjayFAe5LHCNcPx3N7mFU4ZIWUckjGiUBLWJpFt/fikTvVmfRJj6VA7i098tW8nJTrE2hsd2Ea58e62Ru9ubMe7UDbu1yY7q6PCMktyWfxlprQaawMYlwWAgQLTX076F6fnZ4PPR/8+7wc1ja7M5PRszsRqfFUmAO/HH4PNbUBIATPNSlFoCSeZV5l8XuV59ctVI2xvED8de0bT4AkVQPuvUReszWiJg63N2Fu0V9o0G50OQiMK0N7186rYNN5N6O36+n0+BS8D4/UZNzXsZA3Q1Z+Wc9AiQtCrKbfrt3Z4Q1MLJQkTmDLDehPV+zeTh3XEObI0KnyWizIr2Iyun+IcHrVg3hgRG3WEa6Gdj6dfSF/3XM1tVF2gigy1doUzqqrE8Drp2MXZS9z+d0ovMo31JuM9brazgtjSBWsx6NKCW5fcTTmIZzbZNDNgFTptNBRD6YgF5FvivUF8rYSA4lBQ3DvC2tpWnRq6deW9O4rTUQmlNshHBQCtZOpwAiUJ19uDmtFdDPURICwmR72GMywllphqzTWPQQOQ1mOBtQBu0MuVU01jeGtkmoYiajniwKu+FWN8vyEgrRjeATj2nt0/xGv4f4OEsSmMPRpmqzJqgpW7XlYp0q4ztkN7PEtAIH938qkDr+2utorQmOy5DRRFA7o8nHXeGhMOADFb8NOFzm4b+ZPB2qGxwrZ32RiKD9eNgdVBe8awil8FsHd2XMA29LVE+Fej9efTc+h1baBeAaGgpy8nZxuDVJ3NmgVxjc1zlcQvj4ck0I5TYaK53aCG3ri0a3flldk8CyRqB389QPRgwQPDVi0tQDLTfh3gNKQbAaA3kDr0TUScT+83AT/D4cXh7yfs97eXAcCf+kdfPv72DBBYZ9QGgvv/p2CmHcGBM/PgdQGt3T1fB9KsNK8Jal7A12CtVVcLgc1QrAdthnhDcPMG1JiOD9NYro9ulsELg5vp9iWwzXT1i376GQmD+Vyev+c98oHd40a4OhNv21NLgMAT6LVwPO6kd0ZhqozrluSH6CDaxwPrUzaBaTZO8WGyrabRmiHuWt7TZGUgbZVi9VrSH/wXJHyW1dWXxl4zDnd2jfe7r4m8j4TO6wCvEea1cNfMrx0sqk+uW1S1eGqsCNaciivaTefUzmAaG3ybga5l8MKga7p9CdAFcPzx09HFc+ww+XzW32Ty+DzfPtNLI6ExYoWEuB0NHp3umRevComPOPbrQKIR5jUh0UeK+r7OapBoCdaBREu7EST6g7GQ2Djy0Di/EpOEjfDED37Qwsf6JJCKs0x9pGGUg9/VLDoO9NjZI2zfDpLN4z4GKRfh5M5F9bXB/IsqBZIJp/oQiGJfIWWzF2t89QEIGv2b++BKb9IVnKdfmXah4AaP3tT5zEmiMk/igoZPOl9SPzZ1+WHgbrHjwb+gYw9KNbk/aYOvpQ9nh2ZZF0uXo1vY+4uiy3tYuurT2oe/ePEEVS2pA9r15GaiZX0srzXa7d3ehxvN5vMkG8ezmGUmdudHJ3AH8yt96NpDUNUXCc2ojyBnzmTonKlVX2WGwRvZI28kHh4L56w6C08VaA7yQUb6e84IP1SmYXCdnfT75/0eRNR15hzjwo9YaMeWKUgHIVqoY2fqK0Yo3NShzcGAHB6SYDDAwQ4GgepID3x7638EZzkz
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/cuda_configure.bzl
"""Repository rule for CUDA autoconfiguration. `cuda_configure` depends on the following environment variables: * `TF_NEED_CUDA`: Whether to enable building with CUDA. * `GCC_HOST_COMPILER_PATH`: The GCC host compiler path * `TF_CUDA_CLANG`: Whether to use clang as a cuda compiler. * `CLANG_CUDA_COMPILER_PATH`: The clang compiler path that will be used for both host and device code compilation if TF_CUDA_CLANG is 1. * `TF_SYSROOT`: The sysroot to use when compiling. * `TF_CUDA_PATHS`: The base paths to look for CUDA and cuDNN. Default is `/usr/local/cuda,usr/`. * `CUDA_TOOLKIT_PATH` (deprecated): The path to the CUDA toolkit. Default is `/usr/local/cuda`. * `TF_CUDA_VERSION`: The version of the CUDA toolkit. If this is blank, then use the system default. * `TF_CUDNN_VERSION`: The version of the cuDNN library. * `CUDNN_INSTALL_PATH` (deprecated): The path to the cuDNN library. Default is `/usr/local/cuda`. * `TF_CUDA_COMPUTE_CAPABILITIES`: The CUDA compute capabilities. Default is `5.2,6.0` * `PYTHON_BIN_PATH`: The python binary path """ load( "//tools/platform:common.bzl", "config_repo_label", "err_out", "execute", "get_bash_bin", "get_cpu_value", "get_host_environ", "get_crosstool_verbose", "get_python_bin", "raw_exec", "read_dir", "realpath", "make_copy_files_rule", "make_copy_dir_rule", "to_list_of_strings", "flag_enabled", "which", "tpl_gpus_path", "tpl_gpus", ) _GCC_HOST_COMPILER_PATH = "GCC_HOST_COMPILER_PATH" _GCC_HOST_COMPILER_PREFIX = "GCC_HOST_COMPILER_PREFIX" _CLANG_CUDA_COMPILER_PATH = "CLANG_CUDA_COMPILER_PATH" _TF_SYSROOT = "TF_SYSROOT" _CUDA_TOOLKIT_PATH = "CUDA_TOOLKIT_PATH" _TF_CUDA_VERSION = "TF_CUDA_VERSION" _TF_CUDNN_VERSION = "TF_CUDNN_VERSION" _CUDNN_INSTALL_PATH = "CUDNN_INSTALL_PATH" _TF_CUDA_COMPUTE_CAPABILITIES = "TF_CUDA_COMPUTE_CAPABILITIES" _TF_CUDA_CONFIG_REPO = "TF_CUDA_CONFIG_REPO" _PYTHON_BIN_PATH = "PYTHON_BIN_PATH" _GPU_PLATFORM = "GPU_PLATFORM" def verify_build_defines(params): """Verify all variables that crosstool/BUILD.tpl expects are substituted. Args: params: dict of variables that will be passed to the BUILD.tpl template. """ missing = [] for param in [ "cxx_builtin_include_directories", "extra_no_canonical_prefixes_flags", "host_compiler_path", "host_compiler_prefix", "host_compiler_warnings", "linker_bin_path", "compiler_deps", "unfiltered_compile_flags", ]: if ("%{" + param + "}") not in params: missing.append(param) if missing: auto_configure_fail( "BUILD.tpl template is missing these variables: " + str(missing) + ".\nWe only got: " + str(params) + ".", ) # TODO(dzc): Once these functions have been factored out of Bazel's # cc_configure.bzl, load them from @bazel_tools instead. # BEGIN cc_configure common functions. def find_cc(repository_ctx): """Find the C++ compiler.""" if _use_cuda_clang(repository_ctx): target_cc_name = "clang" cc_path_envvar = _CLANG_CUDA_COMPILER_PATH else: target_cc_name = "gcc" cc_path_envvar = _GCC_HOST_COMPILER_PATH cc_name = target_cc_name cc_name_from_env = get_host_environ(repository_ctx, cc_path_envvar) if cc_name_from_env: cc_name = cc_name_from_env if cc_name.startswith("/"): # Absolute path, maybe we should make this supported by our which function. return cc_name cc = which(repository_ctx, cc_name) if cc == None: fail(("Cannot find {}, either correct your path or set the {}" + " environment variable").format(target_cc_name, cc_path_envvar)) return cc _INC_DIR_MARKER_BEGIN = "#include <...>" def _cxx_inc_convert(path): """Convert path returned by cc -E xc++ in a complete path.""" return path.strip() def _normalize_include_path(repository_ctx, path): """Normalizes include paths before writing them to the crosstool. If path points inside the 'crosstool' folder of the repository, a relative path is returned. If path points outside the 'crosstool' folder, an absolute path is returned. """ path = str(repository_ctx.path(path)) crosstool_folder = str(repository_ctx.path(".").get_child("crosstool")) if path.startswith(crosstool_folder): # We drop the path to "$REPO/crosstool" and a trailing path separator. return path[len(crosstool_folder) + 1:] return path def _get_cxx_inc_directories_impl(repository_ctx, cc, lang_is_cpp, tf_sysroot): """Compute the list of default C or C++ include directories.""" if lang_is_cpp: lang = "c++" else: lang = "c" sysroot = [] if tf_sysroot: sysroot += ["--sysroot", tf_sysroot] result = raw_exec(repository_ctx, [cc, "-E", "-x" + lang, "-", "-v"] + sysroot) stderr = err_out(result) index1 = stderr.find(_INC_DIR_MARKER_BEGIN) if index1 == -1: return [] index1 = stderr.find("\n", index1) if index1 == -1: return [] index2 = stderr.rfind("\n ") if index2 == -1 or index2 < index1: return [] index2 = stderr.find("\n", index2 + 1) if index2 == -1: inc_dirs = stderr[index1 + 1:] else: inc_dirs = stderr[index1 + 1:index2].strip() return [ _normalize_include_path(repository_ctx, _cxx_inc_convert(p)) for p in inc_dirs.split("\n") ] def get_cxx_inc_directories(repository_ctx, cc, tf_sysroot): """Compute the list of default C and C++ include directories.""" # For some reason `clang -xc` sometimes returns include paths that are # different from the ones from `clang -xc++`. (Symlink and a dir) # So we run the compiler with both `-xc` and `-xc++` and merge resulting lists includes_cpp = _get_cxx_inc_directories_impl( repository_ctx, cc, True, tf_sysroot, ) includes_c = _get_cxx_inc_directories_impl( repository_ctx, cc, False, tf_sysroot, ) return includes_cpp + [ inc for inc in includes_c if inc not in includes_cpp ] def auto_configure_fail(msg): """Output failure message when cuda configuration fails.""" red = "\033[0;31m" no_color = "\033[0m" fail("\n%sCuda Configuration Error:%s %s\n" % (red, no_color, msg)) # END cc_configure common functions (see TODO above). def _cuda_include_path(repository_ctx, cuda_config): """Generates the Starlark string with cuda include directories. Args: repository_ctx: The repository context. cc: The path to the gcc host compiler. Returns: A list of the gcc host compiler include directories. """ nvcc_path = repository_ctx.path("{}/bin/nvcc".format(cuda_config.cuda_toolkit_path)) # The expected exit code of this command is non-zero. Bazel remote execution # only caches commands with zero exit code. So force a zero exit code. cmd = "%s -v /dev/null -o /dev/null ; [ $? -eq 1 ]" % str(nvcc_path) result = raw_exec(repository_ctx, [get_bash_bin(repository_ctx), "-c", cmd]) target_dir = "" for one_line in err_out(result).splitlines(): if one_line.startswith("#$ _TARGET_DIR_="): target_dir = ( cuda_config.cuda_toolkit_path + "/" + one_line.replace( "#$ _TARGET_DIR_=", "", ) + "/include" ) inc_entries = [] if target_dir != "": inc_entries.append(realpath(repository_ctx, target_dir)) inc_entries.append(realpath(repository_ctx, cuda_config.cuda_toolkit_path + "/include")) return inc_entries def enable_cuda(repository_ctx): """Returns whether to build with CUDA support.""" return int(get_host_environ(repository_ctx, "TF_NEED_CUDA", False)) def matches_version(environ_version, detected_version): """Checks whether the user-specified version matches the detected version. This function performs a weak matching so that if the user specifies only the major or major and minor versions, the versions are still considered matching if the version parts match. To illustrate: environ_version detected_version result ----------------------------------------- 5.1.3 5.1.3 True 5.1 5.1.3 True 5 5.1 True 5.1.3 5.1 False 5.2.3 5.1.3 False Args: environ_version: The version specified by the user via environment variables. detected_version: The version autodetected from the CUDA installation on the system. Returns: True if user-specified version matches detected version and False otherwise. """ environ_version_parts = environ_version.split(".") detected_version_parts = detected_version.split(".") if len(detected_version_parts) < len(environ_version_parts): return False for i, part in enumerate(detected_version_parts): if i >= len(environ_version_parts): break if part != environ_version_parts[i]: return False return True _NVCC_VERSION_PREFIX = "Cuda compilation tools, release " _DEFINE_CUDNN_MAJOR = "#define CUDNN_MAJOR" def compute_capabilities(repository_ctx): """Returns a list of strings representing cuda compute capabilities. Args: repository_ctx: the repo rule's context. Returns: list of cuda architectures to compile for. 'compute_xy' refers to both PTX and SASS, 'sm_xy' refers to SASS only. """ capabilities = get_host_environ( repository_ctx, _TF_CUDA_COMPUTE_CAPABILITIES, "compute_52,compute_60", ).split(",") # Map old 'x.y' capabilities to 'compute_xy'. for i, capability in enumerate(capabilities): parts = capability.split(".") if len(parts) != 2: continue capabilities[i] = "compute_%s%s" % (parts[0], parts[1]) # Make list unique capabilities = dict(zip(capabilities, capabilities)).keys() # Validate capabilities. for capability in capabilities: if not capability.startswith(("compute_", "sm_")): auto_configure_fail("Invalid compute capability: %s" % capability) for prefix in ["compute_", "sm_"]: if not capability.startswith(prefix): continue if len(capability) == len(prefix) + 2 and capability[-2:].isdigit(): continue auto_configure_fail("Invalid compute capability: %s" % capability) return capabilities def _nvcc_verbose(repository_ctx): """Returns the environment variable value NVCC_VERBOSE. Args: repository_ctx: The repository context. Returns: A string containing value of environment variable NVCC_VERBOSE. """ return get_host_environ(repository_ctx, "NVCC_VERBOSE", "0") def lib_name(base_name, cpu_value, version = None, static = False): """Constructs the platform-specific name of a library. Args: base_name: The name of the library, such as "cudart" cpu_value: The name of the host operating system. version: The version of the library. static: True the library is static or False if it is a shared object. Returns: The platform-specific name of the library. """ version = "" if not version else "." + version if cpu_value == "Linux": if static: return "lib%s.a" % base_name return "lib%s.so%s" % (base_name, version) else: auto_configure_fail("Support for cpu_value {} either removed or invalid".format(cpu_value)) def _lib_path(lib, cpu_value, basedir, version, static): file_name = lib_name(lib, cpu_value, version, static) return "%s/%s" % (basedir, file_name) def _should_check_soname(version, static): return version and not static def _check_cuda_lib_params(lib, cpu_value, basedir, version, static = False): return ( _lib_path(lib, cpu_value, basedir, version, static), _should_check_soname(version, static), ) def _check_cuda_libs(repository_ctx, script_path, libs): python_bin = get_python_bin(repository_ctx) contents = repository_ctx.read(script_path).splitlines() cmd = "from os import linesep;" cmd += "f = open('script.py', 'w');" for line in contents: cmd += "f.write('%s' + linesep);" % line cmd += "f.close();" cmd += "from os import system;" args = " ".join(["\"" + path + "\" " + str(check) for path, check in libs]) cmd += "system('%s script.py %s');" % (python_bin, args) all_paths = [path for path, _ in libs] checked_paths = execute(repository_ctx, [python_bin, "-c", cmd]).stdout.splitlines() # Filter out empty lines from splitting on '\r\n' on Windows checked_paths = [path for path in checked_paths if len(path) > 0] if all_paths != checked_paths: auto_configure_fail("Error with installed CUDA libs. Expected '%s'. Actual '%s'." % (all_paths, checked_paths)) def _find_libs(repository_ctx, check_cuda_libs_script, cuda_config): """Returns the CUDA and cuDNN libraries on the system. Also, verifies that the script actually exist. Args: repository_ctx: The repository context. check_cuda_libs_script: The path to a script verifying that the cuda libraries exist on the system. cuda_config: The CUDA config as returned by _get_cuda_config Returns: Map of library names to structs of filename and path. """ cpu_value = cuda_config.cpu_value stub_dir = "/stubs" check_cuda_libs_params = { "cuda": _check_cuda_lib_params( "cuda", cpu_value, cuda_config.config["cuda_library_dir"] + stub_dir, version = None, static = False, ), "cudart": _check_cuda_lib_params( "cudart", cpu_value, cuda_config.config["cuda_library_dir"], cuda_config.cudart_version, static = False, ), "cudart_static": _check_cuda_lib_params( "cudart_static", cpu_value, cuda_config.config["cuda_library_dir"], cuda_config.cudart_version, static = True, ), "cublas": _check_cuda_lib_params( "cublas", cpu_value, cuda_config.config["cublas_library_dir"], cuda_config.cublas_version, static = False, ), "cublasLt": _check_cuda_lib_params( "cublasLt", cpu_value, cuda_config.config["cublas_library_dir"], cuda_config.cublas_version, static = False, ), "cusolver": _check_cuda_lib_params( "cusolver", cpu_value, cuda_config.config["cusolver_library_dir"], cuda_config.cusolver_version, static = False, ), "curand": _check_cuda_lib_params( "curand", cpu_value, cuda_config.config["curand_library_dir"], cuda_config.curand_version, static = False, ), "cufft": _check_cuda_lib_params( "cufft", cpu_value, cuda_config.config["cufft_library_dir"], cuda_config.cufft_version, static = False, ), "cudnn": _check_cuda_lib_params( "cudnn", cpu_value, cuda_config.config["cudnn_library_dir"], cuda_config.cudnn_version, static = False, ), "cupti": _check_cuda_lib_params( "cupti", cpu_value, cuda_config.config["cupti_library_dir"], cuda_config.cuda_version, static = False, ), "cusparse": _check_cuda_lib_params( "cusparse", cpu_value, cuda_config.config["cusparse_library_dir"], cuda_config.cusparse_version, static = False, ), } # Verify that the libs actually exist at their locations. _check_cuda_libs(repository_ctx, check_cuda_libs_script, check_cuda_libs_params.values()) paths = {filename: v[0] for (filename, v) in check_cuda_libs_params.items()} return paths def _cudart_static_linkopt(cpu_value): """Returns additional platform-specific linkopts for cudart.""" return "\"-lrt\"," def _exec_find_cuda_config(repository_ctx, script_path, cuda_libraries): python_bin = get_python_bin(repository_ctx) # If used with remote execution then repository_ctx.execute() can't # access files from the source tree. A trick is to read the contents # of the file in Starlark and embed them as part of the command. In # this case the trick is not sufficient as the find_cuda_config.py # script has more than 8192 characters. 8192 is the command length # limit of cmd.exe on Windows. Thus we additionally need to compress # the contents locally and decompress them as part of the execute(). compressed_contents = repository_ctx.read(script_path) decompress_and_execute_cmd = ( "from zlib import decompress;" + "from base64 import b64decode;" + "from os import system;" + "script = decompress(b64decode('%s'));" % compressed_contents + "f = open('script.py', 'wb');" + "f.write(script);" + "f.close();" + "system('\"%s\" script.py %s');" % (python_bin, " ".join(cuda_libraries)) ) return execute(repository_ctx, [python_bin, "-c", decompress_and_execute_cmd]) # TODO(csigg): Only call once instead of from here, tensorrt_configure.bzl, # and nccl_configure.bzl. def find_cuda_config(repository_ctx, script_path, cuda_libraries): """Returns CUDA config dictionary from running find_cuda_config.py""" exec_result = _exec_find_cuda_config(repository_ctx, script_path, cuda_libraries) if exec_result.return_code: auto_configure_fail("Failed to run find_cuda_config.py: %s" % err_out(exec_result)) # Parse the dict from stdout. return dict([tuple(x.split(": ")) for x in exec_result.stdout.splitlines()]) def _get_cuda_config(repository_ctx, find_cuda_config_script): """Detects and returns information about the CUDA installation on the system. Args: repository_ctx: The repository context. Returns: A struct containing the following fields: cuda_toolkit_path: The CUDA toolkit installation directory. cudnn_install_basedir: The cuDNN installation directory. cuda_version: The version of CUDA on the system. cudart_version: The CUDA runtime version on the system. cudnn_version: The version of cuDNN on the system. compute_capabilities: A list of the system's CUDA compute capabilities. cpu_value: The name of the host operating system. """ config = find_cuda_config(repository_ctx, find_cuda_config_script, ["cuda", "cudnn"]) cpu_value = get_cpu_value(repository_ctx) toolkit_path = config["cuda_toolkit_path"] cuda_version = config["cuda_version"].split(".") cuda_major = cuda_version[0] cuda_minor = cuda_version[1] cuda_version = "{}.{}".format(cuda_major, cuda_minor) cudnn_version = config["cudnn_version"] if int(cuda_major) >= 11: # The libcudart soname in CUDA 11.x is versioned as 11.0 for backward compatability. if int(cuda_major) == 11: cudart_version = "11.0" else: cudart_version = cuda_major cublas_version = config["cublas_version"].split(".")[0] cusolver_version = config["cusolver_version"].split(".")[0] curand_version = config["curand_version"].split(".")[0] cufft_version = config["cufft_version"].split(".")[0] cusparse_version = config["cusparse_version"].split(".")[0] elif (int(cuda_major), int(cuda_minor)) >= (10, 1): # cuda_lib_version is for libraries like cuBLAS, cuFFT, cuSOLVER, etc. # It changed from 'x.y' to just 'x' in CUDA 10.1. cuda_lib_version = cuda_major cudart_version = cuda_version cublas_version = cuda_lib_version cusolver_version = cuda_lib_version curand_version = cuda_lib_version cufft_version = cuda_lib_version cusparse_version = cuda_lib_version else: cudart_version = cuda_version cublas_version = cuda_version cusolver_version = cuda_version curand_version = cuda_version cufft_version = cuda_version cusparse_version = cuda_version return struct( cuda_toolkit_path = toolkit_path, cuda_version = cuda_version, cuda_version_major = cuda_major, cudart_version = cudart_version, cublas_version = cublas_version, cusolver_version = cusolver_version, curand_version = curand_version, cufft_version = cufft_version, cusparse_version = cusparse_version, cudnn_version = cudnn_version, compute_capabilities = compute_capabilities(repository_ctx), cpu_value = cpu_value, config = config, ) def _file(repository_ctx, label): repository_ctx.template( label.replace(":", "/"), Label("//third_party/gpus/%s.tpl" % label), {}, ) _DUMMY_CROSSTOOL_BZL_FILE = """ def error_gpu_disabled(): fail("ERROR: Building with --config=cuda but Apollo is not configured " + "to build with GPU support. Please re-run ./scripts/apollo_config.sh" + "to build with GPU support.") native.genrule( name = "error_gen_crosstool", outs = ["CROSSTOOL"], cmd = "echo 'Should not be run.' && exit 1", ) native.filegroup( name = "crosstool", srcs = [":CROSSTOOL"], output_licenses = ["unencumbered"], ) """ _DUMMY_CROSSTOOL_BUILD_FILE = """ load("//crosstool:error_gpu_disabled.bzl", "error_gpu_disabled") error_gpu_disabled() """ def _create_dummy_repository(repository_ctx): cpu_value = get_cpu_value(repository_ctx) # Set up BUILD file for cuda/. tpl_gpus( repository_ctx, "cuda:build_defs.bzl", { "%{cuda_is_configured}": "False", "%{cuda_extra_copts}": "[]", "%{cuda_gpu_architectures}": "[]", }, ) tpl_gpus( repository_ctx, "cuda:BUILD", { "%{cuda_driver_lib}": lib_name("cuda", cpu_value), "%{cudart_static_lib}": lib_name( "cudart_static", cpu_value, static = True, ), "%{cudart_static_linkopt}": _cudart_static_linkopt(cpu_value), "%{cudart_lib}": lib_name("cudart", cpu_value), "%{cublas_lib}": lib_name("cublas", cpu_value), "%{cublasLt_lib}": lib_name("cublasLt", cpu_value), "%{cusolver_lib}": lib_name("cusolver", cpu_value), "%{cudnn_lib}": lib_name("cudnn", cpu_value), "%{cufft_lib}": lib_name("cufft", cpu_value), "%{curand_lib}": lib_name("curand", cpu_value), "%{cupti_lib}": lib_name("cupti", cpu_value), "%{cusparse_lib}": lib_name("cusparse", cpu_value), "%{cub_actual}": ":cuda_headers", "%{copy_rules}": """ filegroup(name="cuda-include") filegroup(name="cublas-include") filegroup(name="cusolver-include") filegroup(name="cufft-include") filegroup(name="cusparse-include") filegroup(name="curand-include") filegroup(name="cudnn-include") """, }, ) # Create dummy files for the CUDA toolkit since they are still required by # tensorflow/core/platform/default/build_config:cuda. repository_ctx.file("cuda/cuda/include/cuda.h") repository_ctx.file("cuda/cuda/include/cublas.h") repository_ctx.file("cuda/cuda/include/cudnn.h") repository_ctx.file("cuda/cuda/extras/CUPTI/include/cupti.h") repository_ctx.file("cuda/cuda/lib/%s" % lib_name("cuda", cpu_value)) repository_ctx.file("cuda/cuda/lib/%s" % lib_name("cudart", cpu_value)) repository_ctx.file( "cuda/cuda/lib/%s" % lib_name("cudart_static", cpu_value), ) repository_ctx.file("cuda/cuda/lib/%s" % lib_name("cublas", cpu_value)) repository_ctx.file("cuda/cuda/lib/%s" % lib_name("cublasLt", cpu_value)) repository_ctx.file("cuda/cuda/lib/%s" % lib_name("cusolver", cpu_value)) repository_ctx.file("cuda/cuda/lib/%s" % lib_name("cudnn", cpu_value)) repository_ctx.file("cuda/cuda/lib/%s" % lib_name("curand", cpu_value)) repository_ctx.file("cuda/cuda/lib/%s" % lib_name("cufft", cpu_value)) repository_ctx.file("cuda/cuda/lib/%s" % lib_name("cupti", cpu_value)) repository_ctx.file("cuda/cuda/lib/%s" % lib_name("cusparse", cpu_value)) # Set up cuda_config.h tpl_gpus( repository_ctx, "cuda:cuda_config.h", { "%{cuda_version}": "", "%{cudart_version}": "", "%{cublas_version}": "", "%{cusolver_version}": "", "%{curand_version}": "", "%{cufft_version}": "", "%{cusparse_version}": "", "%{cudnn_version}": "", "%{cuda_toolkit_path}": "", }, "cuda/cuda/cuda_config.h", ) # Set up cuda_config.py, which is used by gen_build_info to provide # static build environment info to the API tpl_gpus( repository_ctx, "cuda:cuda_config.py", _py_tmpl_dict({}), "cuda/cuda/cuda_config.py", ) # If cuda_configure is not configured to build with GPU support, and the user # attempts to build with --config=cuda, add a dummy build rule to intercept # this and fail with an actionable error message. repository_ctx.file( "crosstool/error_gpu_disabled.bzl", _DUMMY_CROSSTOOL_BZL_FILE, ) repository_ctx.file("crosstool/BUILD", _DUMMY_CROSSTOOL_BUILD_FILE) def _use_cuda_clang(repository_ctx): return flag_enabled(repository_ctx, "TF_CUDA_CLANG") def _tf_sysroot(repository_ctx): return get_host_environ(repository_ctx, _TF_SYSROOT, "") def _compute_cuda_extra_copts(repository_ctx, compute_capabilities): copts = [] for capability in compute_capabilities: if capability.startswith("compute_"): capability = capability.replace("compute_", "sm_") copts.append("--cuda-include-ptx=%s" % capability) copts.append("--cuda-gpu-arch=%s" % capability) return str(copts) def _basename(repository_ctx, path_str): """Returns the basename of a path of type string. This method is different from path.basename in that it also works if the host platform is different from the execution platform i.e. linux -> windows. """ num_chars = len(path_str) for i in range(num_chars): r_i = num_chars - 1 - i if path_str[r_i] == "/": return path_str[r_i + 1:] return path_str def _create_local_cuda_repository(repository_ctx): """Creates the repository containing files set up to build with CUDA.""" # Resolve all labels before doing any real work. Resolving causes the # function to be restarted with all previous state being lost. This # can easily lead to a O(n^2) runtime in the number of labels. # See https://github.com/tensorflow/tensorflow/commit/62bd3534525a036f07d9851b3199d68212904778 tpl_paths = {filename: tpl_gpus_path(repository_ctx, filename) for filename in [ "cuda:build_defs.bzl", "crosstool:clang/bin/crosstool_wrapper_driver_is_not_gcc", "crosstool:BUILD", "crosstool:cc_toolchain_config.bzl", "cuda:cuda_config.h", "cuda:cuda_config.py", ]} tpl_paths["cuda:BUILD"] = tpl_gpus_path(repository_ctx, "cuda:BUILD") find_cuda_config_script = repository_ctx.path(Label("//third_party/gpus:find_cuda_config.py.gz.base64")) cuda_config = _get_cuda_config(repository_ctx, find_cuda_config_script) cuda_include_path = cuda_config.config["cuda_include_dir"] cublas_include_path = cuda_config.config["cublas_include_dir"] cudnn_header_dir = cuda_config.config["cudnn_include_dir"] cupti_header_dir = cuda_config.config["cupti_include_dir"] nvvm_libdevice_dir = cuda_config.config["nvvm_library_dir"] # Create genrule to copy files from the installed CUDA toolkit into execroot. copy_rules = [ make_copy_dir_rule( repository_ctx, name = "cuda-include", src_dir = cuda_include_path, out_dir = "cuda/include", ), make_copy_dir_rule( repository_ctx, name = "cuda-nvvm", src_dir = nvvm_libdevice_dir, out_dir = "cuda/nvvm/libdevice", ), make_copy_dir_rule( repository_ctx, name = "cuda-extras", src_dir = cupti_header_dir, out_dir = "cuda/extras/CUPTI/include", ), ] copy_rules.append(make_copy_files_rule( repository_ctx, name = "cublas-include", srcs = [ cublas_include_path + "/cublas.h", cublas_include_path + "/cublas_v2.h", cublas_include_path + "/cublas_api.h", cublas_include_path + "/cublasLt.h", ], outs = [ "cublas/include/cublas.h", "cublas/include/cublas_v2.h", "cublas/include/cublas_api.h", "cublas/include/cublasLt.h", ], )) cusolver_include_path = cuda_config.config["cusolver_include_dir"] copy_rules.append(make_copy_files_rule( repository_ctx, name = "cusolver-include", srcs = [ cusolver_include_path + "/cusolver_common.h", cusolver_include_path + "/cusolverDn.h", ], outs = [ "cusolver/include/cusolver_common.h", "cusolver/include/cusolverDn.h", ], )) cufft_include_path = cuda_config.config["cufft_include_dir"] copy_rules.append(make_copy_files_rule( repository_ctx, name = "cufft-include", srcs = [ cufft_include_path + "/cufft.h", ], outs = [ "cufft/include/cufft.h", ], )) cusparse_include_path = cuda_config.config["cusparse_include_dir"] copy_rules.append(make_copy_files_rule( repository_ctx, name = "cusparse-include", srcs = [ cusparse_include_path + "/cusparse.h", ], outs = [ "cusparse/include/cusparse.h", ], )) curand_include_path = cuda_config.config["curand_include_dir"] copy_rules.append(make_copy_files_rule( repository_ctx, name = "curand-include", srcs = [ curand_include_path + "/curand.h", ], outs = [ "curand/include/curand.h", ], )) check_cuda_libs_script = repository_ctx.path(Label("//third_party/gpus:check_cuda_libs.py")) cuda_libs = _find_libs(repository_ctx, check_cuda_libs_script, cuda_config) cuda_lib_srcs = [] cuda_lib_outs = [] for path in cuda_libs.values(): cuda_lib_srcs.append(path) cuda_lib_outs.append("cuda/lib/" + _basename(repository_ctx, path)) copy_rules.append(make_copy_files_rule( repository_ctx, name = "cuda-lib", srcs = cuda_lib_srcs, outs = cuda_lib_outs, )) # copy files mentioned in third_party/nccl/build_defs.bzl.tpl file_ext = "" copy_rules.append(make_copy_files_rule( repository_ctx, name = "cuda-bin", srcs = [ cuda_config.cuda_toolkit_path + "/bin/" + "crt/link.stub", cuda_config.cuda_toolkit_path + "/bin/" + "nvlink" + file_ext, cuda_config.cuda_toolkit_path + "/bin/" + "fatbinary" + file_ext, cuda_config.cuda_toolkit_path + "/bin/" + "bin2c" + file_ext, ], outs = [ "cuda/bin/" + "crt/link.stub", "cuda/bin/" + "nvlink" + file_ext, "cuda/bin/" + "fatbinary" + file_ext, "cuda/bin/" + "bin2c" + file_ext, ], )) # Select the headers based on the cuDNN version (strip '64_' for Windows). cudnn_headers = ["cudnn.h"] if cuda_config.cudnn_version.rsplit("_", 1)[0] >= "8": cudnn_headers += [ "cudnn_backend.h", "cudnn_adv_infer.h", "cudnn_adv_train.h", "cudnn_cnn_infer.h", "cudnn_cnn_train.h", "cudnn_ops_infer.h", "cudnn_ops_train.h", "cudnn_version.h", ] cudnn_srcs = [] cudnn_outs = [] for header in cudnn_headers: cudnn_srcs.append(cudnn_header_dir + "/" + header) cudnn_outs.append("cudnn/include/" + header) copy_rules.append(make_copy_files_rule( repository_ctx, name = "cudnn-include", srcs = cudnn_srcs, outs = cudnn_outs, )) # Set up BUILD file for cuda/ repository_ctx.template( "cuda/build_defs.bzl", tpl_paths["cuda:build_defs.bzl"], { "%{cuda_is_configured}": "True", "%{cuda_extra_copts}": _compute_cuda_extra_copts( repository_ctx, cuda_config.compute_capabilities, ), "%{cuda_gpu_architectures}": str(cuda_config.compute_capabilities), }, ) cub_actual = "@cub_archive//:cub" if int(cuda_config.cuda_version_major) >= 11: cub_actual = ":cuda_headers" repository_ctx.template( "cuda/BUILD", tpl_paths["cuda:BUILD"], { "%{cuda_driver_lib}": _basename(repository_ctx, cuda_libs["cuda"]), "%{cudart_static_lib}": _basename(repository_ctx, cuda_libs["cudart_static"]), "%{cudart_static_linkopt}": _cudart_static_linkopt(cuda_config.cpu_value), "%{cudart_lib}": _basename(repository_ctx, cuda_libs["cudart"]), "%{cublas_lib}": _basename(repository_ctx, cuda_libs["cublas"]), "%{cublasLt_lib}": _basename(repository_ctx, cuda_libs["cublasLt"]), "%{cusolver_lib}": _basename(repository_ctx, cuda_libs["cusolver"]), "%{cudnn_lib}": _basename(repository_ctx, cuda_libs["cudnn"]), "%{cufft_lib}": _basename(repository_ctx, cuda_libs["cufft"]), "%{curand_lib}": _basename(repository_ctx, cuda_libs["curand"]), "%{cupti_lib}": _basename(repository_ctx, cuda_libs["cupti"]), "%{cusparse_lib}": _basename(repository_ctx, cuda_libs["cusparse"]), "%{cub_actual}": cub_actual, "%{copy_rules}": "\n".join(copy_rules), }, ) is_cuda_clang = _use_cuda_clang(repository_ctx) tf_sysroot = _tf_sysroot(repository_ctx) # Set up crosstool/ cc = find_cc(repository_ctx) cc_fullpath = cc host_compiler_includes = get_cxx_inc_directories( repository_ctx, cc_fullpath, tf_sysroot, ) cuda_defines = {} cuda_defines["%{builtin_sysroot}"] = tf_sysroot cuda_defines["%{cuda_toolkit_path}"] = "" cuda_defines["%{compiler}"] = "unknown" if is_cuda_clang: cuda_defines["%{cuda_toolkit_path}"] = cuda_config.config["cuda_toolkit_path"] cuda_defines["%{compiler}"] = "clang" host_compiler_prefix = get_host_environ(repository_ctx, _GCC_HOST_COMPILER_PREFIX) if not host_compiler_prefix: host_compiler_prefix = "/usr/bin" cuda_defines["%{host_compiler_prefix}"] = host_compiler_prefix # Bazel sets '-B/usr/bin' flag to workaround build errors on RHEL (see # https://github.com/bazelbuild/bazel/issues/760). # However, this stops our custom clang toolchain from picking the provided # LLD linker, so we're only adding '-B/usr/bin' when using non-downloaded # toolchain. # TODO: when bazel stops adding '-B/usr/bin' by default, remove this # flag from the CROSSTOOL completely (see # https://github.com/bazelbuild/bazel/issues/5634) cuda_defines["%{linker_bin_path}"] = host_compiler_prefix cuda_defines["%{extra_no_canonical_prefixes_flags}"] = "" cuda_defines["%{unfiltered_compile_flags}"] = "" if is_cuda_clang: cuda_defines["%{host_compiler_path}"] = str(cc) cuda_defines["%{host_compiler_warnings}"] = """ # Some parts of the codebase set -Werror and hit this warning, so # switch it off for now. "-Wno-invalid-partial-specialization" """ cuda_defines["%{cxx_builtin_include_directories}"] = to_list_of_strings(host_compiler_includes) cuda_defines["%{compiler_deps}"] = ":empty" repository_ctx.file( "crosstool/clang/bin/crosstool_wrapper_driver_is_not_gcc", "", ) else: cuda_defines["%{host_compiler_path}"] = "clang/bin/crosstool_wrapper_driver_is_not_gcc" cuda_defines["%{host_compiler_warnings}"] = "" # nvcc has the system include paths built in and will automatically # search them; we cannot work around that, so we add the relevant cuda # system paths to the allowed compiler specific include paths. cuda_defines["%{cxx_builtin_include_directories}"] = to_list_of_strings( host_compiler_includes + _cuda_include_path( repository_ctx, cuda_config, ) + [cupti_header_dir, cudnn_header_dir], ) # For gcc, do not canonicalize system header paths; some versions of gcc # pick the shortest possible path for system includes when creating the # .d file - given that includes that are prefixed with "../" multiple # time quickly grow longer than the root of the tree, this can lead to # bazel's header check failing. cuda_defines["%{extra_no_canonical_prefixes_flags}"] = "\"-fno-canonical-system-headers\"" nvcc_path = "{}/nvcc".format(cuda_config.config["cuda_binary_dir"]) cuda_defines["%{compiler_deps}"] = ":crosstool_wrapper_driver_is_not_gcc" wrapper_defines = { "%{cpu_compiler}": str(cc), "%{cuda_version}": cuda_config.cuda_version, "%{nvcc_path}": nvcc_path, "%{gcc_host_compiler_path}": str(cc), "%{crosstool_verbose}": get_crosstool_verbose(repository_ctx), "%{nvcc_verbose}": _nvcc_verbose(repository_ctx), } repository_ctx.template( "crosstool/clang/bin/crosstool_wrapper_driver_is_not_gcc", tpl_paths["crosstool:clang/bin/crosstool_wrapper_driver_is_not_gcc"], wrapper_defines, ) verify_build_defines(cuda_defines) # Only expand template variables in the BUILD file repository_ctx.template( "crosstool/BUILD", tpl_paths["crosstool:BUILD"], cuda_defines, ) # No templating of cc_toolchain_config - use attributes and templatize the # BUILD file. repository_ctx.template( "crosstool/cc_toolchain_config.bzl", tpl_paths["crosstool:cc_toolchain_config.bzl"], {}, ) # Set up cuda_config.h, which is used by # tensorflow/stream_executor/dso_loader.cc. repository_ctx.template( "cuda/cuda/cuda_config.h", tpl_paths["cuda:cuda_config.h"], { "%{cuda_version}": cuda_config.cuda_version, "%{cudart_version}": cuda_config.cudart_version, "%{cublas_version}": cuda_config.cublas_version, "%{cusolver_version}": cuda_config.cusolver_version, "%{curand_version}": cuda_config.curand_version, "%{cufft_version}": cuda_config.cufft_version, "%{cusparse_version}": cuda_config.cusparse_version, "%{cudnn_version}": cuda_config.cudnn_version, "%{cuda_toolkit_path}": cuda_config.cuda_toolkit_path, }, ) # Set up cuda_config.py, which is used by gen_build_info to provide # static build environment info to the API repository_ctx.template( "cuda/cuda/cuda_config.py", tpl_paths["cuda:cuda_config.py"], _py_tmpl_dict({ "cuda_version": cuda_config.cuda_version, "cudnn_version": cuda_config.cudnn_version, "cuda_compute_capabilities": cuda_config.compute_capabilities, "cpu_compiler": str(cc), }), ) def _py_tmpl_dict(d): return {"%{cuda_config}": str(d)} def _create_remote_cuda_repository(repository_ctx, remote_config_repo): """Creates pointers to a remotely configured repo set up to build with CUDA.""" tpl_gpus( repository_ctx, "cuda:build_defs.bzl", { "%{cuda_is_configured}": "True", "%{cuda_extra_copts}": _compute_cuda_extra_copts( repository_ctx, compute_capabilities(repository_ctx), ), }, ) repository_ctx.template( "cuda/BUILD", config_repo_label(remote_config_repo, "cuda:BUILD"), {}, ) repository_ctx.template( "cuda/build_defs.bzl", config_repo_label(remote_config_repo, "cuda:build_defs.bzl"), {}, ) repository_ctx.template( "cuda/cuda/cuda_config.h", config_repo_label(remote_config_repo, "cuda:cuda/cuda_config.h"), {}, ) repository_ctx.template( "cuda/cuda/cuda_config.py", config_repo_label(remote_config_repo, "cuda:cuda/cuda_config.py"), _py_tmpl_dict({}), ) repository_ctx.template( "crosstool/BUILD", config_repo_label(remote_config_repo, "crosstool:BUILD"), {}, ) repository_ctx.template( "crosstool/cc_toolchain_config.bzl", config_repo_label(remote_config_repo, "crosstool:cc_toolchain_config.bzl"), {}, ) repository_ctx.template( "crosstool/clang/bin/crosstool_wrapper_driver_is_not_gcc", config_repo_label(remote_config_repo, "crosstool:clang/bin/crosstool_wrapper_driver_is_not_gcc"), {}, ) def _cuda_autoconf_impl(repository_ctx): """Implementation of the cuda_autoconf repository rule.""" if not enable_cuda(repository_ctx): _create_dummy_repository(repository_ctx) elif get_host_environ(repository_ctx, _TF_CUDA_CONFIG_REPO) != None: has_cuda_version = get_host_environ(repository_ctx, _TF_CUDA_VERSION) != None has_cudnn_version = get_host_environ(repository_ctx, _TF_CUDNN_VERSION) != None if not has_cuda_version or not has_cudnn_version: auto_configure_fail("%s and %s must also be set if %s is specified" % (_TF_CUDA_VERSION, _TF_CUDNN_VERSION, _TF_CUDA_CONFIG_REPO)) _create_remote_cuda_repository( repository_ctx, get_host_environ(repository_ctx, _TF_CUDA_CONFIG_REPO), ) else: _create_local_cuda_repository(repository_ctx) _ENVIRONS = [ _GCC_HOST_COMPILER_PATH, _GCC_HOST_COMPILER_PREFIX, _CLANG_CUDA_COMPILER_PATH, "TF_NEED_CUDA", "TF_CUDA_CLANG", _CUDA_TOOLKIT_PATH, _CUDNN_INSTALL_PATH, _TF_CUDA_VERSION, _TF_CUDNN_VERSION, _TF_CUDA_COMPUTE_CAPABILITIES, "NVVMIR_LIBRARY_DIR", _PYTHON_BIN_PATH, "TF_CUDA_PATHS", _GPU_PLATFORM, ] # Note(storypku): Uncomment the following rule iff "--experimental_repo_remote_exec" # is enabled in //tools/bazelrc # remote_cuda_configure = repository_rule( # implementation = _create_local_cuda_repository, # environ = _ENVIRONS, # remotable = True, # attrs = { # "environ": attr.string_dict(), # }, # ) cuda_configure = repository_rule( implementation = _cuda_autoconf_impl, environ = _ENVIRONS + [_TF_CUDA_CONFIG_REPO], ) """Detects and configures the local CUDA toolchain. Add the following to your WORKSPACE FILE: ```python cuda_configure(name = "local_config_cuda") ``` Args: name: A unique name for this workspace rule. """
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-gpus", data = [ ":cyberfile.xml", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-gpus/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/common.bzl
load("@local_config_cuda//cuda:build_defs.bzl", "cuda_extra_copts") load("@local_config_rocm//rocm:build_defs.bzl", "rocm_extra_copts") def if_gpu(if_true, if_false = []): """Shorthand for select()'ing on whether we're building with gpu enabled Returns a select statement which evaluates to if_true if we're building with use_gpu enabled. Otherwise, the select statement evaluates to if_false. """ return select({ "//tools/platform:use_gpu": if_true, "//conditions:default": if_false, }) def if_cuda(if_true, if_false = []): return select({ "@local_config_cuda//cuda:using_nvcc": if_true, "@local_config_cuda//cuda:using_clang": if_true, "//conditions:default": if_false, }) def if_rocm(if_true, if_false = []): return select({ "@local_config_rocm//rocm:using_hipcc": if_true, "//conditions:default": if_false }) def if_cuda_clang(if_true, if_false = []): return select({ "@local_config_cuda//cuda:using_clang": if_true, "//conditions:default": if_false }) def if_cuda_clang_opt(if_true, if_false = []): return select({ "@local_config_cuda//cuda:using_clang_opt": if_true, "//conditions:default": if_false }) def if_rocm_clang_opt(if_true, if_false = []): return select({ "@local_config_rocm//rocm:using_clang_opt": if_true, "//conditions:default": if_false }) def rocm_default_copts(): return if_rocm(["-x", "hip"] + rocm_extra_copts()) + if_rocm_clang_opt(["-O3"]) def cuda_default_copts(): return if_cuda(["-x", "cuda", "-Xcuda-fatbinary=--compress-all", "--no-cuda-include-ptx=all"] + cuda_extra_copts()) + if_cuda_clang_opt(["-O3"]) def gpu_default_copts(): return cuda_default_copts() + rocm_default_copts() def gpu_library(copts = [], **kwargs): native.cc_library(copts = gpu_default_copts() + copts, **kwargs)
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/gpus/compress_find_cuda_config.py
#! /usr/bin/env python3 # Copyright 2020 The TensorFlow Authors. 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. # ============================================================================== """Compresses the contents of 'find_cuda_config.py' The compressed file is what is actually being used. It works around remote config not being able to upload files yet. """ import base64 import zlib def main(): with open('find_cuda_config.py', 'rb') as f: data = f.read() compressed = zlib.compress(data) b64encoded = base64.b64encode(compressed) with open('find_cuda_config.py.gz.base64', 'wb') as f: f.write(b64encoded) if __name__ == '__main__': main()
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/crosstool/BUILD.tpl
# This file is expanded from a template by cuda_configure.bzl # Update cuda_configure.bzl#verify_build_defines when adding new variables. load(":cc_toolchain_config.bzl", "cc_toolchain_config") licenses(["restricted"]) package(default_visibility = ["//visibility:public"]) toolchain( name = "toolchain-linux-x86_64", exec_compatible_with = [ "@bazel_tools//platforms:linux", "@bazel_tools//platforms:x86_64", ], target_compatible_with = [ "@bazel_tools//platforms:linux", "@bazel_tools//platforms:x86_64", ], toolchain = ":cc-compiler-local", toolchain_type = "@bazel_tools//tools/cpp:toolchain_type", ) cc_toolchain_suite( name = "toolchain", toolchains = { "local|compiler": ":cc-compiler-local", "arm": ":cc-compiler-local", "aarch64": ":cc-compiler-local", "k8": ":cc-compiler-local", }, ) cc_toolchain( name = "cc-compiler-local", all_files = "%{compiler_deps}", compiler_files = "%{compiler_deps}", ar_files = "%{compiler_deps}", as_files = "%{compiler_deps}", dwp_files = ":empty", linker_files = "%{compiler_deps}", objcopy_files = ":empty", strip_files = ":empty", # To support linker flags that need to go to the start of command line # we need the toolchain to support parameter files. Parameter files are # last on the command line and contain all shared libraries to link, so all # regular options will be left of them. supports_param_files = 1, toolchain_identifier = "local_linux", toolchain_config = ":cc-compiler-local-config", ) cc_toolchain_config( name = "cc-compiler-local-config", cpu = "local", builtin_include_directories = [%{cxx_builtin_include_directories}], extra_no_canonical_prefixes_flags = [%{extra_no_canonical_prefixes_flags}], host_compiler_path = "%{host_compiler_path}", host_compiler_prefix = "%{host_compiler_prefix}", host_compiler_warnings = [%{host_compiler_warnings}], host_unfiltered_compile_flags = [%{unfiltered_compile_flags}], linker_bin_path = "%{linker_bin_path}", builtin_sysroot = "%{builtin_sysroot}", cuda_path = "%{cuda_toolkit_path}", compiler = "%{compiler}", ) filegroup( name = "empty", srcs = [], ) filegroup( name = "crosstool_wrapper_driver_is_not_gcc", srcs = ["clang/bin/crosstool_wrapper_driver_is_not_gcc"], )
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/crosstool/hipcc_cc_toolchain_config.bzl.tpl
"""cc_toolchain_config rule for configuring ROCm toolchain on Linux.""" load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "feature", "feature_set", "flag_group", "flag_set", "tool_path", "variable_with_value", "with_feature_set", ) load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") all_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.clif_match, ACTION_NAMES.lto_backend, ] all_cpp_compile_actions = [ ACTION_NAMES.cpp_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.clif_match, ] preprocessor_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.clif_match, ] codegen_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend, ] all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] lto_index_actions = [ ACTION_NAMES.lto_index_for_executable, ACTION_NAMES.lto_index_for_dynamic_library, ACTION_NAMES.lto_index_for_nodeps_dynamic_library, ] def _impl(ctx): tool_paths = [ tool_path(name = "gcc", path = ctx.attr.host_compiler_path), tool_path(name = "ar", path = ctx.attr.host_compiler_prefix + "/ar"), tool_path(name = "compat-ld", path = ctx.attr.host_compiler_prefix + "/ld"), tool_path(name = "cpp", path = ctx.attr.host_compiler_prefix + "/cpp"), tool_path(name = "dwp", path = ctx.attr.host_compiler_prefix + "/dwp"), tool_path(name = "gcov", path = ctx.attr.host_compiler_prefix + "/gcov"), tool_path(name = "ld", path = ctx.attr.host_compiler_prefix + "/ld"), tool_path(name = "nm", path = ctx.attr.host_compiler_prefix + "/nm"), tool_path(name = "objcopy", path = ctx.attr.host_compiler_prefix + "/objcopy"), tool_path(name = "objdump", path = ctx.attr.host_compiler_prefix + "/objdump"), tool_path(name = "strip", path = ctx.attr.host_compiler_prefix + "/strip"), ] action_configs = [] supports_pic_feature = feature( name = "supports_pic", enabled = True, ) supports_start_end_lib_feature = feature( name = "supports_start_end_lib", enabled = True, ) default_compile_flags_feature = feature( name = "default_compile_flags", enabled = True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups = ([ flag_group( flags = ctx.attr.compile_flags, ), ] if ctx.attr.compile_flags else []), ), flag_set( actions = all_compile_actions, flag_groups = ([ flag_group( flags = ctx.attr.dbg_compile_flags, ), ] if ctx.attr.dbg_compile_flags else []), with_features = [with_feature_set(features = ["dbg"])], ), flag_set( actions = all_compile_actions, flag_groups = ([ flag_group( flags = ctx.attr.opt_compile_flags, ), ] if ctx.attr.opt_compile_flags else []), with_features = [with_feature_set(features = ["opt"])], ), flag_set( actions = all_cpp_compile_actions + [ACTION_NAMES.lto_backend], flag_groups = ([ flag_group( flags = ctx.attr.cxx_flags, ), ] if ctx.attr.cxx_flags else []), ), ], ) default_link_flags_feature = feature( name = "default_link_flags", enabled = True, flag_sets = [ flag_set( actions = all_link_actions + lto_index_actions, flag_groups = ([ flag_group( flags = ctx.attr.link_flags, ), ] if ctx.attr.link_flags else []), ), flag_set( actions = all_link_actions + lto_index_actions, flag_groups = ([ flag_group( flags = ctx.attr.opt_link_flags, ), ] if ctx.attr.opt_link_flags else []), with_features = [with_feature_set(features = ["opt"])], ), ], ) dbg_feature = feature(name = "dbg") opt_feature = feature(name = "opt") sysroot_feature = feature( name = "sysroot", enabled = True, flag_sets = [ flag_set( actions = [ ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend, ACTION_NAMES.clif_match, ] + all_link_actions + lto_index_actions, flag_groups = [ flag_group( flags = ["--sysroot=%{sysroot}"], expand_if_available = "sysroot", ), ], ), ], ) fdo_optimize_feature = feature( name = "fdo_optimize", flag_sets = [ flag_set( actions = [ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile], flag_groups = [ flag_group( flags = [ "-fprofile-use=%{fdo_profile_path}", "-fprofile-correction", ], expand_if_available = "fdo_profile_path", ), ], ), ], provides = ["profile"], ) supports_dynamic_linker_feature = feature(name = "supports_dynamic_linker", enabled = True) user_compile_flags_feature = feature( name = "user_compile_flags", enabled = True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups = [ flag_group( flags = ["%{user_compile_flags}"], iterate_over = "user_compile_flags", expand_if_available = "user_compile_flags", ), ], ), ], ) unfiltered_compile_flags_feature = feature( name = "unfiltered_compile_flags", enabled = True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups = ([ flag_group( flags = ctx.attr.unfiltered_compile_flags, ), ] if ctx.attr.unfiltered_compile_flags else []), ), ], ) library_search_directories_feature = feature( name = "library_search_directories", flag_sets = [ flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [ flag_group( flags = ["-L%{library_search_directories}"], iterate_over = "library_search_directories", expand_if_available = "library_search_directories", ), ], ), ], ) static_libgcc_feature = feature( name = "static_libgcc", enabled = True, flag_sets = [ flag_set( actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.lto_index_for_executable, ACTION_NAMES.lto_index_for_dynamic_library, ], flag_groups = [flag_group(flags = ["-static-libgcc"])], with_features = [ with_feature_set(features = ["static_link_cpp_runtimes"]), ], ), ], ) pic_feature = feature( name = "pic", enabled = True, flag_sets = [ flag_set( actions = [ ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.cpp_module_compile, ], flag_groups = [ flag_group(flags = ["-fPIC"], expand_if_available = "pic"), ], ), ], ) per_object_debug_info_feature = feature( name = "per_object_debug_info", flag_sets = [ flag_set( actions = [ ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_module_codegen, ], flag_groups = [ flag_group( flags = ["-gsplit-dwarf"], expand_if_available = "per_object_debug_info_file", ), ], ), ], ) preprocessor_defines_feature = feature( name = "preprocessor_defines", enabled = True, flag_sets = [ flag_set( actions = [ ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.clif_match, ], flag_groups = [ flag_group( flags = ["-D%{preprocessor_defines}"], iterate_over = "preprocessor_defines", ), ], ), ], ) cs_fdo_optimize_feature = feature( name = "cs_fdo_optimize", flag_sets = [ flag_set( actions = [ACTION_NAMES.lto_backend], flag_groups = [ flag_group( flags = [ "-fprofile-use=%{fdo_profile_path}", "-Xclang-only=-Wno-profile-instr-unprofiled", "-Xclang-only=-Wno-profile-instr-out-of-date", "-fprofile-correction", ], expand_if_available = "fdo_profile_path", ), ], ), ], provides = ["csprofile"], ) autofdo_feature = feature( name = "autofdo", flag_sets = [ flag_set( actions = [ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile], flag_groups = [ flag_group( flags = [ "-fauto-profile=%{fdo_profile_path}", "-fprofile-correction", ], expand_if_available = "fdo_profile_path", ), ], ), ], provides = ["profile"], ) runtime_library_search_directories_feature = feature( name = "runtime_library_search_directories", flag_sets = [ flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [ flag_group( iterate_over = "runtime_library_search_directories", flag_groups = [ flag_group( flags = [ "-Wl,-rpath,$EXEC_ORIGIN/%{runtime_library_search_directories}", ], expand_if_true = "is_cc_test", ), flag_group( flags = [ "-Wl,-rpath,$ORIGIN/%{runtime_library_search_directories}", ], expand_if_false = "is_cc_test", ), ], expand_if_available = "runtime_library_search_directories", ), ], with_features = [ with_feature_set(features = ["static_link_cpp_runtimes"]), ], ), flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [ flag_group( iterate_over = "runtime_library_search_directories", flag_groups = [ flag_group( flags = [ "-Wl,-rpath,$ORIGIN/%{runtime_library_search_directories}", ], ), ], expand_if_available = "runtime_library_search_directories", ), ], with_features = [ with_feature_set( not_features = ["static_link_cpp_runtimes"], ), ], ), ], ) fission_support_feature = feature( name = "fission_support", flag_sets = [ flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [ flag_group( flags = ["-Wl,--gdb-index"], expand_if_available = "is_using_fission", ), ], ), ], ) shared_flag_feature = feature( name = "shared_flag", flag_sets = [ flag_set( actions = [ ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ACTION_NAMES.lto_index_for_dynamic_library, ACTION_NAMES.lto_index_for_nodeps_dynamic_library, ], flag_groups = [flag_group(flags = ["-shared"])], ), ], ) random_seed_feature = feature( name = "random_seed", enabled = True, flag_sets = [ flag_set( actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.cpp_module_compile, ], flag_groups = [ flag_group( flags = ["-frandom-seed=%{output_file}"], expand_if_available = "output_file", ), ], ), ], ) includes_feature = feature( name = "includes", enabled = True, flag_sets = [ flag_set( actions = [ ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.clif_match, ACTION_NAMES.objc_compile, ACTION_NAMES.objcpp_compile, ], flag_groups = [ flag_group( flags = ["-include", "%{includes}"], iterate_over = "includes", expand_if_available = "includes", ), ], ), ], ) fdo_instrument_feature = feature( name = "fdo_instrument", flag_sets = [ flag_set( actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ] + all_link_actions + lto_index_actions, flag_groups = [ flag_group( flags = [ "-fprofile-generate=%{fdo_instrument_path}", "-fno-data-sections", ], expand_if_available = "fdo_instrument_path", ), ], ), ], provides = ["profile"], ) cs_fdo_instrument_feature = feature( name = "cs_fdo_instrument", flag_sets = [ flag_set( actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.lto_backend, ] + all_link_actions + lto_index_actions, flag_groups = [ flag_group( flags = [ "-fcs-profile-generate=%{cs_fdo_instrument_path}", ], expand_if_available = "cs_fdo_instrument_path", ), ], ), ], provides = ["csprofile"], ) include_paths_feature = feature( name = "include_paths", enabled = True, flag_sets = [ flag_set( actions = [ ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.clif_match, ACTION_NAMES.objc_compile, ACTION_NAMES.objcpp_compile, ], flag_groups = [ flag_group( flags = ["-iquote", "%{quote_include_paths}"], iterate_over = "quote_include_paths", ), flag_group( flags = ["-I%{include_paths}"], iterate_over = "include_paths", ), flag_group( flags = ["-isystem", "%{system_include_paths}"], iterate_over = "system_include_paths", ), ], ), ], ) symbol_counts_feature = feature( name = "symbol_counts", flag_sets = [ flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [ flag_group( flags = [ "-Wl,--print-symbol-counts=%{symbol_counts_output}", ], expand_if_available = "symbol_counts_output", ), ], ), ], ) llvm_coverage_map_format_feature = feature( name = "llvm_coverage_map_format", flag_sets = [ flag_set( actions = [ ACTION_NAMES.preprocess_assemble, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.objc_compile, ACTION_NAMES.objcpp_compile, ], flag_groups = [ flag_group( flags = [ "-fprofile-instr-generate", "-fcoverage-mapping", ], ), ], ), flag_set( actions = all_link_actions + lto_index_actions + [ "objc-executable", "objc++-executable", ], flag_groups = [ flag_group(flags = ["-fprofile-instr-generate"]), ], ), ], requires = [feature_set(features = ["coverage"])], provides = ["profile"], ) strip_debug_symbols_feature = feature( name = "strip_debug_symbols", flag_sets = [ flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [ flag_group( flags = ["-Wl,-S"], expand_if_available = "strip_debug_symbols", ), ], ), ], ) build_interface_libraries_feature = feature( name = "build_interface_libraries", flag_sets = [ flag_set( actions = [ ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ACTION_NAMES.lto_index_for_dynamic_library, ACTION_NAMES.lto_index_for_nodeps_dynamic_library, ], flag_groups = [ flag_group( flags = [ "%{generate_interface_library}", "%{interface_library_builder_path}", "%{interface_library_input_path}", "%{interface_library_output_path}", ], expand_if_available = "generate_interface_library", ), ], with_features = [ with_feature_set( features = ["supports_interface_shared_libraries"], ), ], ), ], ) libraries_to_link_feature = feature( name = "libraries_to_link", flag_sets = [ flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [ flag_group( iterate_over = "libraries_to_link", flag_groups = [ flag_group( flags = ["-Wl,--start-lib"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "object_file_group", ), ), flag_group( flags = ["-Wl,-whole-archive"], expand_if_true = "libraries_to_link.is_whole_archive", ), flag_group( flags = ["%{libraries_to_link.object_files}"], iterate_over = "libraries_to_link.object_files", expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "object_file_group", ), ), flag_group( flags = ["%{libraries_to_link.name}"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "object_file", ), ), flag_group( flags = ["%{libraries_to_link.name}"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "interface_library", ), ), flag_group( flags = ["%{libraries_to_link.name}"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "static_library", ), ), flag_group( flags = ["-l%{libraries_to_link.name}"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "dynamic_library", ), ), flag_group( flags = ["-l:%{libraries_to_link.name}"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "versioned_dynamic_library", ), ), flag_group( flags = ["-Wl,-no-whole-archive"], expand_if_true = "libraries_to_link.is_whole_archive", ), flag_group( flags = ["-Wl,--end-lib"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "object_file_group", ), ), ], expand_if_available = "libraries_to_link", ), flag_group( flags = ["-Wl,@%{thinlto_param_file}"], expand_if_true = "thinlto_param_file", ), ], ), ], ) user_link_flags_feature = feature( name = "user_link_flags", flag_sets = [ flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [ flag_group( flags = ["%{user_link_flags}"], iterate_over = "user_link_flags", expand_if_available = "user_link_flags", ), ] + ([flag_group(flags = ctx.attr.link_libs)] if ctx.attr.link_libs else []), ), ], ) fdo_prefetch_hints_feature = feature( name = "fdo_prefetch_hints", flag_sets = [ flag_set( actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.lto_backend, ], flag_groups = [ flag_group( flags = [ "-Xclang-only=-mllvm", "-Xclang-only=-prefetch-hints-file=%{fdo_prefetch_hints_path}", ], expand_if_available = "fdo_prefetch_hints_path", ), ], ), ], ) linkstamps_feature = feature( name = "linkstamps", flag_sets = [ flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [ flag_group( flags = ["%{linkstamp_paths}"], iterate_over = "linkstamp_paths", expand_if_available = "linkstamp_paths", ), ], ), ], ) gcc_coverage_map_format_feature = feature( name = "gcc_coverage_map_format", flag_sets = [ flag_set( actions = [ ACTION_NAMES.preprocess_assemble, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.objc_compile, ACTION_NAMES.objcpp_compile, "objc-executable", "objc++-executable", ], flag_groups = [ flag_group( flags = ["-fprofile-arcs", "-ftest-coverage"], expand_if_available = "gcov_gcno_file", ), ], ), flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [flag_group(flags = ["--coverage"])], ), ], requires = [feature_set(features = ["coverage"])], provides = ["profile"], ) archiver_flags_feature = feature( name = "archiver_flags", flag_sets = [ flag_set( actions = [ACTION_NAMES.cpp_link_static_library], flag_groups = [ flag_group(flags = ["rcsD"]), flag_group( flags = ["%{output_execpath}"], expand_if_available = "output_execpath", ), ], ), flag_set( actions = [ACTION_NAMES.cpp_link_static_library], flag_groups = [ flag_group( iterate_over = "libraries_to_link", flag_groups = [ flag_group( flags = ["%{libraries_to_link.name}"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "object_file", ), ), flag_group( flags = ["%{libraries_to_link.object_files}"], iterate_over = "libraries_to_link.object_files", expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "object_file_group", ), ), ], expand_if_available = "libraries_to_link", ), ], ), ], ) force_pic_flags_feature = feature( name = "force_pic_flags", flag_sets = [ flag_set( actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.lto_index_for_executable, ], flag_groups = [ flag_group( flags = ["-pie"], expand_if_available = "force_pic", ), ], ), ], ) dependency_file_feature = feature( name = "dependency_file", enabled = True, flag_sets = [ flag_set( actions = [ ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.objc_compile, ACTION_NAMES.objcpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.clif_match, ], flag_groups = [ flag_group( flags = ["-MD", "-MF", "%{dependency_file}"], expand_if_available = "dependency_file", ), ], ), ], ) dynamic_library_linker_tool_path = tool_paths dynamic_library_linker_tool_feature = feature( name = "dynamic_library_linker_tool", flag_sets = [ flag_set( actions = [ ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ACTION_NAMES.lto_index_for_dynamic_library, ACTION_NAMES.lto_index_for_nodeps_dynamic_library, ], flag_groups = [ flag_group( flags = [" + cppLinkDynamicLibraryToolPath + "], expand_if_available = "generate_interface_library", ), ], with_features = [ with_feature_set( features = ["supports_interface_shared_libraries"], ), ], ), ], ) output_execpath_flags_feature = feature( name = "output_execpath_flags", flag_sets = [ flag_set( actions = all_link_actions + lto_index_actions, flag_groups = [ flag_group( flags = ["-o", "%{output_execpath}"], expand_if_available = "output_execpath", ), ], ), ], ) # Note that we also set --coverage for c++-link-nodeps-dynamic-library. The # generated code contains references to gcov symbols, and the dynamic linker # can't resolve them unless the library is linked against gcov. coverage_feature = feature( name = "coverage", provides = ["profile"], flag_sets = [ flag_set( actions = [ ACTION_NAMES.preprocess_assemble, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ], flag_groups = ([ flag_group(flags = ctx.attr.coverage_compile_flags), ] if ctx.attr.coverage_compile_flags else []), ), flag_set( actions = all_link_actions + lto_index_actions, flag_groups = ([ flag_group(flags = ctx.attr.coverage_link_flags), ] if ctx.attr.coverage_link_flags else []), ), ], ) build_id_feature = feature( name = "build-id", enabled = True, flag_sets = [ flag_set( actions = all_link_actions, flag_groups = [ flag_group( flags = ["-Wl,--build-id=md5", "-Wl,--hash-style=gnu"], ), ], ), ], ) no_canonical_prefixes_feature = feature( name = "no-canonical-prefixes", enabled = True, flag_sets = [ flag_set( actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ], flag_groups = [ flag_group( flags = [ "-no-canonical-prefixes", "-fno-canonical-system-headers", ] ), ], ), ], ) linker_bin_path_feature = feature( name = "linker-bin-path", enabled = True, flag_sets = [ flag_set( actions = all_link_actions, flag_groups = [flag_group(flags = ["-B" + ctx.attr.linker_bin_path])], ), ], ) features = [ dependency_file_feature, random_seed_feature, pic_feature, per_object_debug_info_feature, preprocessor_defines_feature, includes_feature, include_paths_feature, fdo_instrument_feature, cs_fdo_instrument_feature, cs_fdo_optimize_feature, fdo_prefetch_hints_feature, autofdo_feature, build_interface_libraries_feature, dynamic_library_linker_tool_feature, symbol_counts_feature, shared_flag_feature, linkstamps_feature, output_execpath_flags_feature, runtime_library_search_directories_feature, library_search_directories_feature, archiver_flags_feature, force_pic_flags_feature, fission_support_feature, strip_debug_symbols_feature, coverage_feature, supports_pic_feature, ] + ( [ supports_start_end_lib_feature, ] if ctx.attr.supports_start_end_lib else [] ) + [ default_compile_flags_feature, default_link_flags_feature, libraries_to_link_feature, user_link_flags_feature, static_libgcc_feature, fdo_optimize_feature, supports_dynamic_linker_feature, dbg_feature, opt_feature, user_compile_flags_feature, sysroot_feature, unfiltered_compile_flags_feature, build_id_feature, no_canonical_prefixes_feature, linker_bin_path_feature, ] return cc_common.create_cc_toolchain_config_info( ctx = ctx, features = features, action_configs = action_configs, cxx_builtin_include_directories = ctx.attr.cxx_builtin_include_directories, toolchain_identifier = ctx.attr.toolchain_identifier, host_system_name = ctx.attr.host_system_name, target_system_name = ctx.attr.target_system_name, target_cpu = ctx.attr.cpu, target_libc = ctx.attr.target_libc, compiler = ctx.attr.compiler, abi_version = ctx.attr.abi_version, abi_libc_version = ctx.attr.abi_libc_version, tool_paths = tool_paths, ) cc_toolchain_config = rule( implementation = _impl, attrs = { "cpu": attr.string(mandatory = True), "compiler": attr.string(mandatory = True), "toolchain_identifier": attr.string(mandatory = True), "host_system_name": attr.string(mandatory = True), "target_system_name": attr.string(mandatory = True), "target_libc": attr.string(mandatory = True), "abi_version": attr.string(mandatory = True), "abi_libc_version": attr.string(mandatory = True), "cxx_builtin_include_directories": attr.string_list(), "compile_flags": attr.string_list(), "dbg_compile_flags": attr.string_list(), "opt_compile_flags": attr.string_list(), "cxx_flags": attr.string_list(), "link_flags": attr.string_list(), "link_libs": attr.string_list(), "opt_link_flags": attr.string_list(), "unfiltered_compile_flags": attr.string_list(), "coverage_compile_flags": attr.string_list(), "coverage_link_flags": attr.string_list(), "supports_start_end_lib": attr.bool(), "host_compiler_path": attr.string(), "host_compiler_prefix": attr.string(), "linker_bin_path": attr.string(), }, provides = [CcToolchainConfigInfo], )
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/crosstool/cc_toolchain_config.bzl.tpl
"""cc_toolchain_config rule for configuring CUDA toolchains on Linux ONLY.""" load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "action_config", "feature", "flag_group", "flag_set", "tool", "tool_path", "variable_with_value", "with_feature_set", ) load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") def all_assembly_actions(): return [ ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ] def all_compile_actions(): return [ ACTION_NAMES.assemble, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.preprocess_assemble, ] def all_c_compile_actions(): return [ ACTION_NAMES.c_compile, ] def all_cpp_compile_actions(): return [ ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.linkstamp_compile, ] def all_preprocessed_actions(): return [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.preprocess_assemble, ] def all_link_actions(): return [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def all_executable_link_actions(): return [ ACTION_NAMES.cpp_link_executable, ] def all_shared_library_link_actions(): return [ ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def all_archive_actions(): return [ACTION_NAMES.cpp_link_static_library] def all_strip_actions(): return [ACTION_NAMES.strip] def _library_to_link(flag_prefix, value, iterate = None): return flag_group( flags = [ "{}%{{libraries_to_link.{}}}".format( flag_prefix, iterate if iterate else "name", ), ], iterate_over = ("libraries_to_link." + iterate if iterate else None), expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = value, ), ) def _surround_static_library(prefix, suffix): return [ flag_group( flags = [prefix, "%{libraries_to_link.name}", suffix], expand_if_true = "libraries_to_link.is_whole_archive", ), flag_group( flags = ["%{libraries_to_link.name}"], expand_if_false = "libraries_to_link.is_whole_archive", ), ] def _prefix_static_library(prefix): return [ flag_group( flags = ["%{libraries_to_link.name}"], expand_if_false = "libraries_to_link.is_whole_archive", ), flag_group( flags = [prefix + "%{libraries_to_link.name}"], expand_if_true = "libraries_to_link.is_whole_archive", ), ] def _static_library_to_link(alwayslink_prefix, alwayslink_suffix = None): if alwayslink_suffix: flag_groups = _surround_static_library(alwayslink_prefix, alwayslink_suffix) else: flag_groups = _prefix_static_library(alwayslink_prefix) return flag_group( flag_groups = flag_groups, expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "static_library", ), ) def _iterate_flag_group(iterate_over, flags = [], flag_groups = []): return flag_group( iterate_over = iterate_over, expand_if_available = iterate_over, flag_groups = flag_groups, flags = flags, ) def _libraries_to_link_group(flavour): if flavour != "linux": fail("Oops, we have tailored cc_toolchain_config.bzl to support Linux ONLY") else: return _iterate_flag_group( iterate_over = "libraries_to_link", flag_groups = [ flag_group( flags = ["-Wl,--start-lib"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "object_file_group", ), ), _library_to_link("", "object_file_group", "object_files"), flag_group( flags = ["-Wl,--end-lib"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "object_file_group", ), ), _library_to_link("", "object_file"), _library_to_link("", "interface_library"), _static_library_to_link("-Wl,-whole-archive", "-Wl,-no-whole-archive"), _library_to_link("-l", "dynamic_library"), _library_to_link("-l:", "versioned_dynamic_library"), ], ) def _action_configs_with_tool(path, actions): return [ action_config( action_name = name, enabled = True, tools = [tool(path = path)], ) for name in actions ] def _action_configs(assembly_path, c_compiler_path, cc_compiler_path, archiver_path, linker_path, strip_path): return _action_configs_with_tool( assembly_path, all_assembly_actions(), ) + _action_configs_with_tool( c_compiler_path, all_c_compile_actions(), ) + _action_configs_with_tool( cc_compiler_path, all_cpp_compile_actions(), ) + _action_configs_with_tool( archiver_path, all_archive_actions(), ) + _action_configs_with_tool( linker_path, all_link_actions(), ) + _action_configs_with_tool( strip_path, all_strip_actions(), ) def _tool_paths(cpu, ctx): if cpu == "local": return [ tool_path(name = "gcc", path = ctx.attr.host_compiler_path), tool_path(name = "ar", path = ctx.attr.host_compiler_prefix + ( "/ar" if cpu == "local" else "/libtool" )), tool_path(name = "compat-ld", path = ctx.attr.host_compiler_prefix + "/ld"), tool_path(name = "cpp", path = ctx.attr.host_compiler_prefix + "/cpp"), tool_path(name = "dwp", path = ctx.attr.host_compiler_prefix + "/dwp"), tool_path(name = "gcov", path = ctx.attr.host_compiler_prefix + "/gcov"), tool_path(name = "ld", path = ctx.attr.host_compiler_prefix + "/ld"), tool_path(name = "nm", path = ctx.attr.host_compiler_prefix + "/nm"), tool_path(name = "objcopy", path = ctx.attr.host_compiler_prefix + "/objcopy"), tool_path(name = "objdump", path = ctx.attr.host_compiler_prefix + "/objdump"), tool_path(name = "strip", path = ctx.attr.host_compiler_prefix + "/strip"), ] else: fail("Unreachable") def _sysroot_group(): return flag_group( flags = ["--sysroot=%{sysroot}"], expand_if_available = "sysroot", ) def _no_canonical_prefixes_group(extra_flags): return flag_group( flags = [ "-no-canonical-prefixes", ] + extra_flags, ) def _cuda_set(cuda_path, actions): if cuda_path: return [flag_set( actions = actions, flag_groups = [ flag_group( flags = ["--cuda-path=" + cuda_path], ), ], )] else: return [] def _nologo(): return flag_group(flags = ["/nologo"]) def _features(cpu, compiler, ctx): if cpu == "local": return [ feature(name = "no_legacy_features"), feature( name = "all_compile_flags", enabled = True, flag_sets = [ flag_set( actions = all_compile_actions(), flag_groups = [ flag_group( flags = ["-MD", "-MF", "%{dependency_file}"], expand_if_available = "dependency_file", ), flag_group( flags = ["-gsplit-dwarf"], expand_if_available = "per_object_debug_info_file", ), ], ), flag_set( actions = all_preprocessed_actions(), flag_groups = [ flag_group( flags = ["-frandom-seed=%{output_file}"], expand_if_available = "output_file", ), _iterate_flag_group( flags = ["-D%{preprocessor_defines}"], iterate_over = "preprocessor_defines", ), _iterate_flag_group( flags = ["-include", "%{includes}"], iterate_over = "includes", ), _iterate_flag_group( flags = ["-iquote", "%{quote_include_paths}"], iterate_over = "quote_include_paths", ), _iterate_flag_group( flags = ["-I%{include_paths}"], iterate_over = "include_paths", ), _iterate_flag_group( flags = ["-isystem", "%{system_include_paths}"], iterate_over = "system_include_paths", ), _iterate_flag_group( flags = ["-F", "%{framework_include_paths}"], iterate_over = "framework_include_paths", ), ], ), flag_set( actions = all_cpp_compile_actions(), flag_groups = [ flag_group(flags = ["-fexperimental-new-pass-manager"]), ] if compiler == "clang" else [], ), flag_set( actions = all_compile_actions(), flag_groups = [ flag_group( flags = [ "-Wno-builtin-macro-redefined", "-D__DATE__=\"redacted\"", "-D__TIMESTAMP__=\"redacted\"", "-D__TIME__=\"redacted\"", ], ), flag_group( flags = ["-fPIC"], expand_if_available = "pic", ), flag_group( flags = ["-fPIE"], expand_if_not_available = "pic", ), flag_group( flags = [ "-U_FORTIFY_SOURCE", "-D_FORTIFY_SOURCE=1", "-fstack-protector", "-Wall", ] + ctx.attr.host_compiler_warnings + [ "-fno-omit-frame-pointer", ], ), _no_canonical_prefixes_group( ctx.attr.extra_no_canonical_prefixes_flags, ), ], ), flag_set( actions = all_compile_actions(), flag_groups = [flag_group(flags = ["-DNDEBUG"])], with_features = [with_feature_set(features = ["disable-assertions"])], ), flag_set( actions = all_compile_actions(), flag_groups = [ flag_group( flags = [ "-g0", "-O2", "-ffunction-sections", "-fdata-sections", ], ), ], with_features = [with_feature_set(features = ["opt"])], ), flag_set( actions = all_compile_actions(), flag_groups = [flag_group(flags = ["-g"])], with_features = [with_feature_set(features = ["dbg"])], ), ] + _cuda_set( ctx.attr.cuda_path, all_compile_actions(), ) + [ flag_set( actions = all_compile_actions(), flag_groups = [ _iterate_flag_group( flags = ["%{user_compile_flags}"], iterate_over = "user_compile_flags", ), _sysroot_group(), flag_group( expand_if_available = "source_file", flags = ["-c", "%{source_file}"], ), flag_group( expand_if_available = "output_assembly_file", flags = ["-S"], ), flag_group( expand_if_available = "output_preprocess_file", flags = ["-E"], ), flag_group( expand_if_available = "output_file", flags = ["-o", "%{output_file}"], ), ], ), ], ), feature( name = "all_archive_flags", enabled = True, flag_sets = [ flag_set( actions = all_archive_actions(), flag_groups = [ flag_group( expand_if_available = "linker_param_file", flags = ["@%{linker_param_file}"], ), flag_group(flags = ["rcsD"]), flag_group( flags = ["%{output_execpath}"], expand_if_available = "output_execpath", ), flag_group( iterate_over = "libraries_to_link", flag_groups = [ flag_group( flags = ["%{libraries_to_link.name}"], expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "object_file", ), ), flag_group( flags = ["%{libraries_to_link.object_files}"], iterate_over = "libraries_to_link.object_files", expand_if_equal = variable_with_value( name = "libraries_to_link.type", value = "object_file_group", ), ), ], expand_if_available = "libraries_to_link", ), ], ), ], ), feature( name = "all_link_flags", enabled = True, flag_sets = [ flag_set( actions = all_shared_library_link_actions(), flag_groups = [flag_group(flags = ["-shared"])], ), flag_set( actions = all_link_actions(), flag_groups = ([ flag_group(flags = ["-Wl,-no-as-needed"]) ] if cpu == "local" else []) + ([ flag_group(flags = ["-B" + ctx.attr.linker_bin_path]) ] if ctx.attr.linker_bin_path else []) + [ flag_group( flags = ["@%{linker_param_file}"], expand_if_available = "linker_param_file", ), _iterate_flag_group( flags = ["%{linkstamp_paths}"], iterate_over = "linkstamp_paths", ), flag_group( flags = ["-o", "%{output_execpath}"], expand_if_available = "output_execpath", ), _iterate_flag_group( flags = ["-L%{library_search_directories}"], iterate_over = "library_search_directories", ), _iterate_flag_group( iterate_over = "runtime_library_search_directories", flags = [ "-Wl,-rpath,$ORIGIN/%{runtime_library_search_directories}", ] if cpu == "local" else [ "-Wl,-rpath,@loader_path/%{runtime_library_search_directories}", ], ), _libraries_to_link_group("darwin" if cpu == "darwin" else "linux"), _iterate_flag_group( flags = ["%{user_link_flags}"], iterate_over = "user_link_flags", ), flag_group( flags = ["-Wl,--gdb-index"], expand_if_available = "is_using_fission", ), flag_group( flags = ["-Wl,-S"], expand_if_available = "strip_debug_symbols", ), flag_group(flags = ["-lc++" if cpu == "darwin" else "-lstdc++"]), _no_canonical_prefixes_group( ctx.attr.extra_no_canonical_prefixes_flags, ), ], ), flag_set( actions = all_executable_link_actions(), flag_groups = [flag_group(flags = ["-pie"])], ), ] + ([ flag_set( actions = all_link_actions(), flag_groups = [flag_group(flags = [ "-Wl,-z,relro,-z,now", ])], ), ] if cpu == "local" else []) + ([ flag_set( actions = all_link_actions(), flag_groups = [ flag_group(flags = ["-Wl,--gc-sections"]), flag_group( flags = ["-Wl,--build-id=md5", "-Wl,--hash-style=gnu"], ), ], ), ] if cpu == "local" else []) + ([ flag_set( actions = all_link_actions(), flag_groups = [flag_group(flags = ["-undefined", "dynamic_lookup"])], ), ] if cpu == "darwin" else []) + _cuda_set( ctx.attr.cuda_path, all_link_actions(), ) + [ flag_set( actions = all_link_actions(), flag_groups = [ _sysroot_group(), ], ), ], ), feature(name = "disable-assertions"), feature( name = "opt", implies = ["disable-assertions"], ), feature(name = "fastbuild"), feature(name = "dbg"), feature(name = "supports_dynamic_linker", enabled = True), feature(name = "pic", enabled = True), feature(name = "supports_pic", enabled = True), feature(name = "has_configured_linker_path", enabled = True), ] else: fail("Unreachable") def _impl(ctx): cpu = ctx.attr.cpu compiler = ctx.attr.compiler if (cpu == "local"): toolchain_identifier = "local_linux" target_cpu = "local" target_libc = "local" compiler = "compiler" action_configs = _action_configs( assembly_path = ctx.attr.host_compiler_path, c_compiler_path = ctx.attr.host_compiler_path, cc_compiler_path = ctx.attr.host_compiler_path, archiver_path = ctx.attr.host_compiler_prefix + "/ar", linker_path = ctx.attr.host_compiler_path, strip_path = ctx.attr.host_compiler_prefix + "/strip", ) artifact_name_patterns = [] else: fail("Unreachable") out = ctx.actions.declare_file(ctx.label.name) ctx.actions.write(out, "Fake executable") return [ cc_common.create_cc_toolchain_config_info( ctx = ctx, features = _features(cpu, compiler, ctx), action_configs = action_configs, artifact_name_patterns = artifact_name_patterns, cxx_builtin_include_directories = ctx.attr.builtin_include_directories, toolchain_identifier = toolchain_identifier, host_system_name = "local", target_system_name = "local", target_cpu = target_cpu, target_libc = target_libc, compiler = compiler, abi_version = "local", abi_libc_version = "local", tool_paths = _tool_paths(cpu, ctx), make_variables = [], builtin_sysroot = ctx.attr.builtin_sysroot, cc_target_os = None, ), DefaultInfo( executable = out, ), ] cc_toolchain_config = rule( implementation = _impl, attrs = { "cpu": attr.string(mandatory = True, values = ["local"]), "compiler": attr.string(values = ["clang", "unknown"], default = "unknown"), "builtin_include_directories": attr.string_list(), "extra_no_canonical_prefixes_flags": attr.string_list(), "host_compiler_path": attr.string(), "host_compiler_prefix": attr.string(), "host_compiler_warnings": attr.string_list(), "host_unfiltered_compile_flags": attr.string_list(), "linker_bin_path": attr.string(), "builtin_sysroot": attr.string(), "cuda_path": attr.string(), }, provides = [CcToolchainConfigInfo], executable = True, )
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/crosstool/LICENSE
Copyright 2015 The TensorFlow Authors. All rights reserved. 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015, The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/crosstool/BUILD.rocm.tpl
# This file is expanded from a template by rocm_configure.bzl # Update rocm_configure.bzl#verify_build_defines when adding new variables. load(":hipcc_cc_toolchain_config.bzl", "cc_toolchain_config") licenses(["restricted"]) package(default_visibility = ["//visibility:public"]) toolchain( name = "toolchain-linux-x86_64", exec_compatible_with = [ "@bazel_tools//platforms:linux", "@bazel_tools//platforms:x86_64", ], target_compatible_with = [ "@bazel_tools//platforms:linux", "@bazel_tools//platforms:x86_64", ], toolchain = ":cc-compiler-local", toolchain_type = "@bazel_tools//tools/cpp:toolchain_type", ) cc_toolchain_suite( name = "toolchain", toolchains = { "local|compiler": ":cc-compiler-local", "arm": ":cc-compiler-local", "aarch64": ":cc-compiler-local", "k8": ":cc-compiler-local", }, ) cc_toolchain( name = "cc-compiler-local", all_files = ":crosstool_wrapper_driver_is_clang_for_hip", compiler_files = ":crosstool_wrapper_driver_is_clang_for_hip", ar_files = ":crosstool_wrapper_driver_is_clang_for_hip", as_files = ":crosstool_wrapper_driver_is_clang_for_hip", dwp_files = ":empty", linker_files = ":crosstool_wrapper_driver_is_clang_for_hip", objcopy_files = ":empty", strip_files = ":empty", # To support linker flags that need to go to the start of command line # we need the toolchain to support parameter files. Parameter files are # last on the command line and contain all shared libraries to link, so all # regular options will be left of them. supports_param_files = 1, toolchain_identifier = "local_linux", toolchain_config = ":cc-compiler-local-config", ) cc_toolchain_config( name = "cc-compiler-local-config", cpu = "local", compiler = "compiler", toolchain_identifier = "local_linux", host_system_name = "local", target_system_name = "local", target_libc = "local", abi_version = "local", abi_libc_version = "local", cxx_builtin_include_directories = [%{cxx_builtin_include_directories}], host_compiler_path = "%{host_compiler_path}", host_compiler_prefix = "%{host_compiler_prefix}", compile_flags = [ "-U_FORTIFY_SOURCE", "-fstack-protector", "-Wall", "-Wunused-but-set-parameter", "-Wno-free-nonheap-object", "-fno-omit-frame-pointer", ], opt_compile_flags = [ "-g0", "-O2", "-D_FORTIFY_SOURCE=1", "-DNDEBUG", "-ffunction-sections", "-fdata-sections", ], dbg_compile_flags = ["-g"], link_flags = [ "-fuse-ld=gold", "-Wl,-no-as-needed", "-Wl,-z,relro,-z,now", "-pass-exit-codes", "-lstdc++", "-lm", ], link_libs = [], opt_link_flags = [], unfiltered_compile_flags = [ "-fno-canonical-system-headers", "-Wno-builtin-macro-redefined", "-D__DATE__=\"redacted\"", "-D__TIMESTAMP__=\"redacted\"", "-D__TIME__=\"redacted\"", ] + [%{unfiltered_compile_flags}], linker_bin_path = "%{linker_bin_path}", coverage_compile_flags = ["--coverage"], coverage_link_flags = ["--coverage"], supports_start_end_lib = True, ) filegroup( name = "empty", srcs = [], ) filegroup( name = "crosstool_wrapper_driver_is_clang_for_hip", srcs = ["clang/bin/crosstool_wrapper_driver_is_clang_for_hip"], )
0
apollo_public_repos/apollo/third_party/gpus/crosstool/clang
apollo_public_repos/apollo/third_party/gpus/crosstool/clang/bin/crosstool_wrapper_driver_is_not_gcc.tpl
#!/usr/bin/env python3 # Copyright 2015 The TensorFlow Authors. 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. # ============================================================================== """Crosstool wrapper for compiling CUDA programs. SYNOPSIS: crosstool_wrapper_driver_is_not_gcc [options passed in by cc_library() or cc_binary() rule] DESCRIPTION: This script is expected to be called by the cc_library() or cc_binary() bazel rules. When the option "-x cuda" is present in the list of arguments passed to this script, it invokes the nvcc CUDA compiler. Most arguments are passed as is as a string to --compiler-options of nvcc. When "-x cuda" is not present, this wrapper invokes hybrid_driver_is_not_gcc with the input arguments as is. """ from __future__ import print_function __author__ = 'keveman@google.com (Manjunath Kudlur)' from argparse import ArgumentParser import os import subprocess import re import sys import pipes # Template values set by cuda_autoconf. CPU_COMPILER = ('%{cpu_compiler}') GCC_HOST_COMPILER_PATH = ('%{gcc_host_compiler_path}') NVCC_PATH = '%{nvcc_path}' PREFIX_DIR = os.path.dirname(GCC_HOST_COMPILER_PATH) NVCC_VERSION = '%{cuda_version}' VERBOSE = %{crosstool_verbose} NVCC_VERBOSE = %{nvcc_verbose} def Log(s): print('gpus/crosstool: {0}'.format(s)) def GetOptionValue(argv, option): """Extract the list of values for option from the argv list. Args: argv: A list of strings, possibly the argv passed to main(). option: The option whose value to extract, with the leading '-'. Returns: A list of values, either directly following the option, (eg., -opt val1 val2) or values collected from multiple occurrences of the option (eg., -opt val1 -opt val2). """ parser = ArgumentParser() parser.add_argument(option, nargs='*', action='append') option = option.lstrip('-').replace('-', '_') args, _ = parser.parse_known_args(argv) if not args or not vars(args)[option]: return [] else: return sum(vars(args)[option], []) def GetHostCompilerOptions(argv): """Collect the -isystem, -iquote, and --sysroot option values from argv. Args: argv: A list of strings, possibly the argv passed to main(). Returns: The string that can be used as the --compiler-options to nvcc. """ parser = ArgumentParser() parser.add_argument('-isystem', nargs='*', action='append') parser.add_argument('-iquote', nargs='*', action='append') parser.add_argument('--sysroot', nargs=1) parser.add_argument('-g', nargs='*', action='append') parser.add_argument('-fno-canonical-system-headers', action='store_true') parser.add_argument('-no-canonical-prefixes', action='store_true') args, _ = parser.parse_known_args(argv) opts = '' if args.isystem: opts += ' -isystem ' + ' -isystem '.join(sum(args.isystem, [])) if args.iquote: opts += ' -iquote ' + ' -iquote '.join(sum(args.iquote, [])) if args.g: opts += ' -g' + ' -g'.join(sum(args.g, [])) if args.fno_canonical_system_headers: opts += ' -fno-canonical-system-headers' if args.no_canonical_prefixes: opts += ' -no-canonical-prefixes' if args.sysroot: opts += ' --sysroot ' + args.sysroot[0] return opts def _update_options(nvcc_options): if NVCC_VERSION in ("7.0",): return nvcc_options update_options = { "relaxed-constexpr" : "expt-relaxed-constexpr" } return [ update_options[opt] if opt in update_options else opt for opt in nvcc_options ] def GetNvccOptions(argv): """Collect the -nvcc_options values from argv. Args: argv: A list of strings, possibly the argv passed to main(). Returns: The string that can be passed directly to nvcc. """ parser = ArgumentParser() parser.add_argument('-nvcc_options', nargs='*', action='append') args, _ = parser.parse_known_args(argv) if args.nvcc_options: options = _update_options(sum(args.nvcc_options, [])) return ' '.join(['--'+a for a in options]) return '' def system(cmd): """Invokes cmd with os.system(). Args: cmd: The command. Returns: The exit code if the process exited with exit() or -signal if the process was terminated by a signal. """ retv = os.system(cmd) if os.WIFEXITED(retv): return os.WEXITSTATUS(retv) else: return -os.WTERMSIG(retv) def InvokeNvcc(argv, log=False): """Call nvcc with arguments assembled from argv. Args: argv: A list of strings, possibly the argv passed to main(). log: True if logging is requested. Returns: The return value of calling system('nvcc ' + args) """ host_compiler_options = GetHostCompilerOptions(argv) nvcc_compiler_options = GetNvccOptions(argv) opt_option = GetOptionValue(argv, '-O') m_options = GetOptionValue(argv, '-m') m_options = ''.join([' -m' + m for m in m_options if m in ['32', '64']]) include_options = GetOptionValue(argv, '-I') out_file = GetOptionValue(argv, '-o') depfiles = GetOptionValue(argv, '-MF') defines = GetOptionValue(argv, '-D') defines = ''.join([' -D' + define for define in defines]) undefines = GetOptionValue(argv, '-U') undefines = ''.join([' -U' + define for define in undefines]) std_options = GetOptionValue(argv, '-std') # Supported -std flags as of CUDA 9.0. Only keep last to mimic gcc/clang. nvcc_allowed_std_options = ["c++03", "c++11", "c++14"] std_options = ''.join([' -std=' + define for define in std_options if define in nvcc_allowed_std_options][-1:]) fatbin_options = ''.join([' --fatbin-options=' + option for option in GetOptionValue(argv, '-Xcuda-fatbinary')]) # The list of source files get passed after the -c option. I don't know of # any other reliable way to just get the list of source files to be compiled. src_files = GetOptionValue(argv, '-c') # Pass -w through from host to nvcc, but don't do anything fancier with # warnings-related flags, since they're not necessarily the same across # compilers. warning_options = ' -w' if '-w' in argv else '' if len(src_files) == 0: return 1 if len(out_file) != 1: return 1 opt = (' -O2' if (len(opt_option) > 0 and int(opt_option[0]) > 0) else ' -g') includes = (' -I ' + ' -I '.join(include_options) if len(include_options) > 0 else '') # Unfortunately, there are other options that have -c prefix too. # So allowing only those look like C/C++ files. src_files = [f for f in src_files if re.search('\.cpp$|\.cc$|\.c$|\.cxx$|\.cu$|\.C$', f)] srcs = ' '.join(src_files) out = ' -o ' + out_file[0] nvccopts = '-D_FORCE_INLINES ' if VERBOSE or NVCC_VERBOSE: nvccopts += '-v ' for capability in GetOptionValue(argv, "--cuda-gpu-arch"): capability = capability[len('sm_'):] nvccopts += r'-gencode=arch=compute_%s,\"code=sm_%s\" ' % (capability, capability) for capability in GetOptionValue(argv, '--cuda-include-ptx'): capability = capability[len('sm_'):] nvccopts += r'-gencode=arch=compute_%s,\"code=compute_%s\" ' % (capability, capability) nvccopts += nvcc_compiler_options nvccopts += undefines nvccopts += defines nvccopts += std_options nvccopts += m_options nvccopts += warning_options nvccopts += fatbin_options if depfiles: # Generate the dependency file depfile = depfiles[0] cmd = (NVCC_PATH + ' ' + nvccopts + ' --compiler-options "' + host_compiler_options + '"' + ' --compiler-bindir=' + GCC_HOST_COMPILER_PATH + ' -I .' + ' -x cu ' + opt + includes + ' ' + srcs + ' -M -o ' + depfile) if log: Log(cmd) if VERBOSE or NVCC_VERBOSE: print(' NVCC=') print(cmd) exit_status = system(cmd) if exit_status != 0: return exit_status cmd = (NVCC_PATH + ' ' + nvccopts + ' --compiler-options "' + host_compiler_options + ' -fPIC"' + ' --compiler-bindir=' + GCC_HOST_COMPILER_PATH + ' -I .' + ' -x cu ' + opt + includes + ' -c ' + srcs + out) # TODO(zhengxq): for some reason, 'gcc' needs this help to find 'as'. # Need to investigate and fix. cmd = 'PATH=' + PREFIX_DIR + ':$PATH ' + cmd if log: Log(cmd) if VERBOSE or NVCC_VERBOSE: print(' NVCC=') print(cmd) return system(cmd) def main(): parser = ArgumentParser() parser.add_argument('-x', nargs=1) parser.add_argument('--cuda_log', action='store_true') args, leftover = parser.parse_known_args(sys.argv[1:]) if args.x and args.x[0] == 'cuda': if args.cuda_log: Log('-x cuda') leftover = [pipes.quote(s) for s in leftover] if args.cuda_log: Log('using nvcc') return InvokeNvcc(leftover, log=args.cuda_log) # Strip our flags before passing through to the CPU compiler for files which # are not -x cuda. We can't just pass 'leftover' because it also strips -x. # We not only want to pass -x to the CPU compiler, but also keep it in its # relative location in the argv list (the compiler is actually sensitive to # this). cpu_compiler_flags = [flag for flag in sys.argv[1:] if not flag.startswith(('--cuda_log'))] if VERBOSE: print(' GCC=') print(' '.join([CPU_COMPILER] + cpu_compiler_flags)) return subprocess.call([CPU_COMPILER] + cpu_compiler_flags) if __name__ == '__main__': sys.exit(main())
0
apollo_public_repos/apollo/third_party/gpus/crosstool/clang
apollo_public_repos/apollo/third_party/gpus/crosstool/clang/bin/crosstool_wrapper_driver_is_clang_for_hip.tpl
#!/usr/bin/env python """Crosstool wrapper for compiling ROCm programs. SYNOPSIS: crosstool_wrapper_driver_is_clang_for_hip [options passed in by cc_library() or cc_binary() rule] DESCRIPTION: This script is expected to be called by the cc_library() or cc_binary() bazel rules. When the option "-x hip" is present in the list of arguments passed to this script, it invokes the hipcc compiler. Most arguments are passed as is as a string to --compiler-options of hipcc. When "-x hip" is not present, this wrapper invokes gcc with the input arguments as is. """ from argparse import ArgumentParser import os import subprocess import re import sys import pipes import base64 # Template values set by rocm_configure.bzl. CPU_COMPILER = ('%{cpu_compiler}') HIPCC_PATH = '%{hipcc_path}' HIPCC_ENV = '%{hipcc_env}' HIP_RUNTIME_PATH = '%{hip_runtime_path}' HIP_RUNTIME_LIBRARY = '%{hip_runtime_library}' ROCR_RUNTIME_PATH = '%{rocr_runtime_path}' ROCR_RUNTIME_LIBRARY = '%{rocr_runtime_library}' VERBOSE = %{crosstool_verbose} def Log(s): print('gpus/crosstool: {0}'.format(s)) def GetOptionValue(argv, option): """Extract the list of values for option from the argv list. Args: argv: A list of strings, possibly the argv passed to main(). option: The option whose value to extract, with the leading '-'. Returns: A list of values, either directly following the option, (eg., -opt val1 val2) or values collected from multiple occurrences of the option (eg., -opt val1 -opt val2). """ parser = ArgumentParser() parser.add_argument(option, nargs='*', action='append') option = option.lstrip('-').replace('-', '_') args, _ = parser.parse_known_args(argv) if not args or not vars(args)[option]: return [] else: return sum(vars(args)[option], []) def GetHostCompilerOptions(argv): """Collect the -isystem, -iquote, and --sysroot option values from argv. Args: argv: A list of strings, possibly the argv passed to main(). Returns: The string that can be used as the --compiler-options to hipcc. """ parser = ArgumentParser() parser.add_argument('-isystem', nargs='*', action='append') parser.add_argument('-iquote', nargs='*', action='append') parser.add_argument('--sysroot', nargs=1) parser.add_argument('-g', nargs='*', action='append') parser.add_argument('-fno-canonical-system-headers', action='store_true') args, _ = parser.parse_known_args(argv) opts = '' if args.isystem: opts += ' -isystem ' + ' -isystem '.join(sum(args.isystem, [])) if args.iquote: opts += ' -iquote ' + ' -iquote '.join(sum(args.iquote, [])) if args.g: opts += ' -g' + ' -g'.join(sum(args.g, [])) if args.sysroot: opts += ' --sysroot ' + args.sysroot[0] return opts def system(cmd): """Invokes cmd with os.system(). Args: cmd: The command. Returns: The exit code if the process exited with exit() or -signal if the process was terminated by a signal. """ retv = os.system(cmd) if os.WIFEXITED(retv): return os.WEXITSTATUS(retv) else: return -os.WTERMSIG(retv) def InvokeHipcc(argv, log=False): """Call hipcc with arguments assembled from argv. Args: argv: A list of strings, possibly the argv passed to main(). log: True if logging is requested. Returns: The return value of calling os.system('hipcc ' + args) """ host_compiler_options = GetHostCompilerOptions(argv) opt_option = GetOptionValue(argv, '-O') m_options = GetOptionValue(argv, '-m') m_options = ''.join([' -m' + m for m in m_options if m in ['32', '64']]) include_options = GetOptionValue(argv, '-I') out_file = GetOptionValue(argv, '-o') depfiles = GetOptionValue(argv, '-MF') defines = GetOptionValue(argv, '-D') defines = ''.join([' -D' + define for define in defines]) undefines = GetOptionValue(argv, '-U') undefines = ''.join([' -U' + define for define in undefines]) std_options = GetOptionValue(argv, '-std') hipcc_allowed_std_options = ["c++11", "c++14"] std_options = ''.join([' -std=' + define for define in std_options if define in hipcc_allowed_std_options]) # The list of source files get passed after the -c option. src_files = GetOptionValue(argv, '-c') if len(src_files) == 0: return 1 if len(out_file) != 1: return 1 opt = (' -O2' if (len(opt_option) > 0 and int(opt_option[0]) > 0) else ' -g') includes = (' -I ' + ' -I '.join(include_options) if len(include_options) > 0 else '') # Unfortunately, there are other options that have -c prefix too. # So allowing only those look like C/C++ files. src_files = [f for f in src_files if re.search('\.cpp$|\.cc$|\.c$|\.cxx$|\.C$|\.cu$', f)] srcs = ' '.join(src_files) out = ' -o ' + out_file[0] # We need to make sure that the hip header is included in the sources before # any standard math header like <complex>. Otherwise, we get a build error. # Also we need to retain warnings about uninitialised shared variables as # 'warning only', even if the '-Werror' option is specified. hipccopts = '--include=hip/hip_runtime.h' if VERBOSE: hipccopts += ' -v' for offload in GetOptionValue(argv, '--offload-arch'): hipccopts += ''.join([' --offload-arch=' + offload]) # Use '-fno-gpu-rdc' by default for early GPU kernel finalization. # This flag will trigger GPU kernels to be generated at compile time instead # of link time. This allows the default host compiler (gcc) to be used as the # linker for TensorFlow on the ROCm platform. hipccopts += ' -fno-gpu-rdc' hipccopts += undefines hipccopts += defines hipccopts += std_options hipccopts += m_options hipccopts_override = ' -Xclang -Wno-deprecated-declarations' hipccopts_override += ' -fcolor-diagnostics' if depfiles: # Generate the dependency file depfile = depfiles[0] cmd = (HIPCC_PATH + ' ' + hipccopts + host_compiler_options + hipccopts_override + ' -I .' + includes + ' ' + srcs + ' -M -o ' + depfile) cmd = HIPCC_ENV.replace(';', ' ') + ' ' + cmd if log: Log(cmd) if VERBOSE: print(' HIPCC=' + HIPCC_ENV) print(cmd) exit_status = os.system(cmd) if exit_status != 0: return exit_status cmd = (HIPCC_PATH + ' ' + hipccopts + host_compiler_options + hipccopts_override + ' -fPIC' + ' -I .' + opt + includes + ' -c ' + srcs + out) cmd = HIPCC_ENV.replace(';', ' ') + ' ' + cmd if log: Log(cmd) if VERBOSE: print(' HIPCC=' + HIPCC_ENV) print(cmd) return system(cmd) def main(): # Ignore PWD env var os.environ['PWD']='' parser = ArgumentParser(fromfile_prefix_chars='@') parser.add_argument('-x', nargs=1) parser.add_argument('--rocm_log', action='store_true') parser.add_argument('-pass-exit-codes', action='store_true') args, leftover = parser.parse_known_args(sys.argv[1:]) if VERBOSE: print('PWD=' + os.getcwd()) if args.x and args.x[0] == 'hip': # Compilation of GPU objects if args.rocm_log: Log('-x hip') leftover = [pipes.quote(s) for s in leftover] if args.rocm_log: Log('using hipcc') return InvokeHipcc(leftover, log=args.rocm_log) elif args.pass_exit_codes: # Link with hipcc compiler invoked with '-fno-gpu-rdc' by default. # Host compiler can be used as a linker, # but HIP runtime libraries should be specified. gpu_linker_flags = [flag for flag in sys.argv[1:] if not flag.startswith(('--rocm_log'))] gpu_linker_flags.append('-L' + ROCR_RUNTIME_PATH) gpu_linker_flags.append('-Wl,-rpath=' + ROCR_RUNTIME_PATH) gpu_linker_flags.append('-l' + ROCR_RUNTIME_LIBRARY) gpu_linker_flags.append('-L' + HIP_RUNTIME_PATH) gpu_linker_flags.append('-Wl,-rpath=' + HIP_RUNTIME_PATH) gpu_linker_flags.append('-l' + HIP_RUNTIME_LIBRARY) gpu_linker_flags.append("-lrt") gpu_linker_flags.append("-lstdc++") if VERBOSE: print(' LD=') print(' '.join([CPU_COMPILER] + gpu_linker_flags)) return subprocess.call([CPU_COMPILER] + gpu_linker_flags) else: # Compilation of host objects # Strip flags before passing through to the CPU compiler for files which # are not '-x hip'. We can't just pass 'leftover' because it also strips -x. # We not only want to pass -x to the CPU compiler but also to keep it in its # relative location in the argv list (the compiler is sensitive to this). cpu_compiler_flags = [flag for flag in sys.argv[1:] if not flag.startswith(('--rocm_log'))] # SE codes need to be built with gcc, but need this macro defined. # From ROCm HIP's hip_common.h: # Auto enable __HIP_PLATFORM_AMD__ if compiling on AMD platform # Other compiler (GCC,ICC,etc) need to set one of these macros explicitly cpu_compiler_flags.append("-D__HIP_PLATFORM_AMD__") cpu_compiler_flags.append("-Wno-deprecated-declarations") if VERBOSE: print(' GCC=') print(' '.join([CPU_COMPILER] + cpu_compiler_flags)) return subprocess.call([CPU_COMPILER] + cpu_compiler_flags) if __name__ == '__main__': sys.exit(main())
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/cuda/BUILD.tpl
load(":build_defs.bzl", "cuda_header_library") load("@bazel_skylib//:bzl_library.bzl", "bzl_library") licenses(["restricted"]) # MPL2, portions GPL v3, LGPL v3, BSD-like package(default_visibility = ["//visibility:public"]) config_setting( name = "using_nvcc", values = { "define": "using_cuda_nvcc=true", }, ) config_setting( name = "using_clang", values = { "define": "using_cuda_clang=true", }, ) # Equivalent to using_clang && -c opt. config_setting( name = "using_clang_opt", values = { "define": "using_cuda_clang=true", "compilation_mode": "opt", }, ) cuda_header_library( name = "cuda_headers", hdrs = [ "cuda/cuda_config.h", ":cuda-include" ], include_prefix = "third_party/gpus", includes = [ ".", # required to include cuda/cuda/cuda_config.h as cuda/config.h "cuda/include", ], ) cc_library( name = "cudart_static", srcs = ["cuda/lib/%{cudart_static_lib}"], linkopts = [ "-ldl", "-lpthread", %{cudart_static_linkopt} ], ) cc_library( name = "cuda_driver", srcs = ["cuda/lib/%{cuda_driver_lib}"], ) cc_library( name = "cudart", srcs = ["cuda/lib/%{cudart_lib}"], data = ["cuda/lib/%{cudart_lib}"], linkstatic = 1, ) cuda_header_library( name = "cublas_headers", hdrs = [":cublas-include"], include_prefix = "third_party/gpus/cuda/include", strip_include_prefix = "cublas/include", deps = [":cuda_headers"], includes = ["cublas/include"], ) cuda_header_library( name = "cusolver_headers", hdrs = [":cusolver-include"], include_prefix = "third_party/gpus/cuda/include", strip_include_prefix = "cusolver/include", deps = [":cuda_headers"], includes = ["cusolver/include"], ) cuda_header_library( name = "cufft_headers", hdrs = [":cufft-include"], include_prefix = "third_party/gpus/cuda/include", strip_include_prefix = "cufft/include", deps = [":cuda_headers"], includes = ["cufft/include"], ) cuda_header_library( name = "cusparse_headers", hdrs = [":cusparse-include"], include_prefix = "third_party/gpus/cuda/include", strip_include_prefix = "cusparse/include", deps = [":cuda_headers"], includes = ["cusparse/include"], ) cuda_header_library( name = "curand_headers", hdrs = [":curand-include"], include_prefix = "third_party/gpus/cuda/include", strip_include_prefix = "curand/include", deps = [":cuda_headers"], includes = ["curand/include"], ) cc_library( name = "cublas", srcs = ["cuda/lib/%{cublas_lib}"], data = ["cuda/lib/%{cublas_lib}"], linkstatic = 1, ) cc_library( name = "cublasLt", srcs = ["cuda/lib/%{cublasLt_lib}"], data = ["cuda/lib/%{cublasLt_lib}"], linkstatic = 1, ) cc_library( name = "cusolver", srcs = ["cuda/lib/%{cusolver_lib}"], data = ["cuda/lib/%{cusolver_lib}"], linkopts = ["-lgomp"], linkstatic = 1, ) cc_library( name = "cudnn", srcs = ["cuda/lib/%{cudnn_lib}"], data = ["cuda/lib/%{cudnn_lib}"], linkstatic = 1, ) cc_library( name = "cudnn_header", hdrs = [":cudnn-include"], include_prefix = "third_party/gpus/cudnn", strip_include_prefix = "cudnn/include", deps = [":cuda_headers"], ) cc_library( name = "cufft", srcs = ["cuda/lib/%{cufft_lib}"], data = ["cuda/lib/%{cufft_lib}"], linkstatic = 1, ) cc_library( name = "curand", srcs = ["cuda/lib/%{curand_lib}"], data = ["cuda/lib/%{curand_lib}"], linkstatic = 1, ) cc_library( name = "cuda", deps = [ ":cublas", ":cublasLt", ":cuda_headers", ":cudart", ":cudnn", ":cufft", ":curand", ], ) alias( name = "cub_headers", actual = "%{cub_actual}" ) cuda_header_library( name = "cupti_headers", hdrs = [":cuda-extras"], include_prefix="third_party/gpus", includes = ["cuda/extras/CUPTI/include/"], deps = [":cuda_headers"], ) cc_library( name = "cupti_dsos", data = ["cuda/lib/%{cupti_lib}"], ) cc_library( name = "cusparse", srcs = ["cuda/lib/%{cusparse_lib}"], data = ["cuda/lib/%{cusparse_lib}"], linkopts = ["-lgomp"], linkstatic = 1, ) cc_library( name = "libdevice_root", data = [":cuda-nvvm"], ) filegroup( name = "cuda_root", srcs = [ "cuda/bin/fatbinary", "cuda/bin/bin2c", ], ) bzl_library( name = "build_defs_bzl", srcs = ["build_defs.bzl"], deps = [ "@bazel_skylib//lib:selects", ], ) py_library( name = "cuda_config_py", srcs = ["cuda/cuda_config.py"] ) %{copy_rules}
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/cuda/LICENSE
Copyright 2015 The TensorFlow Authors. All rights reserved. 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015, The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/cuda/build_defs.bzl.tpl
# Macros for building CUDA code. load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") def cuda_extra_copts(): return %{cuda_extra_copts} def cuda_is_configured(): """Returns true if CUDA was enabled during the configure process.""" return %{cuda_is_configured} def cuda_gpu_architectures(): """Returns a list of supported GPU architectures.""" return %{cuda_gpu_architectures} def if_cuda_is_configured(x): """Tests if the CUDA was enabled during the configure process. Unlike if_cuda(), this does not require that we are building with --config=cuda. Used to allow non-CUDA code to depend on CUDA libraries. """ if cuda_is_configured(): return select({"//conditions:default": x}) return select({"//conditions:default": []}) def cuda_header_library( name, hdrs, include_prefix = None, strip_include_prefix = None, deps = [], **kwargs): """Generates a cc_library containing both virtual and system include paths. Generates both a header-only target with virtual includes plus the full target without virtual includes. This works around the fact that bazel can't mix 'includes' and 'include_prefix' in the same target.""" cc_library( name = name + "_virtual", hdrs = hdrs, include_prefix = include_prefix, strip_include_prefix = strip_include_prefix, deps = deps, visibility = ["//visibility:private"], ) cc_library( name = name, textual_hdrs = hdrs, deps = deps + [":%s_virtual" % name], **kwargs )
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/cuda/cuda_config.h.tpl
/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ #ifndef CUDA_CUDA_CONFIG_H_ #define CUDA_CUDA_CONFIG_H_ #define TF_CUDA_VERSION "%{cuda_version}" #define TF_CUDART_VERSION "%{cudart_version}" #define TF_CUBLAS_VERSION "%{cublas_version}" #define TF_CUSOLVER_VERSION "%{cusolver_version}" #define TF_CURAND_VERSION "%{curand_version}" #define TF_CUFFT_VERSION "%{cufft_version}" #define TF_CUSPARSE_VERSION "%{cusparse_version}" #define TF_CUDNN_VERSION "%{cudnn_version}" #define TF_CUDA_TOOLKIT_PATH "%{cuda_toolkit_path}" #endif // CUDA_CUDA_CONFIG_H_
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/cuda/cuda_config.py.tpl
# Lint as: python3 # Copyright 2019 The TensorFlow Authors. 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. # ============================================================================== config = %{cuda_config}
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/rocm/rocm_config.py.tpl
config = %{rocm_config}
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/rocm/BUILD.tpl
load("@bazel_skylib//:bzl_library.bzl", "bzl_library") licenses(["restricted"]) # MPL2, portions GPL v3, LGPL v3, BSD-like package(default_visibility = ["//visibility:public"]) config_setting( name = "using_hipcc", values = { "define": "using_rocm_hipcc=true", }, ) # Equivalent to using_clang && -c opt config_setting( name = "using_clang_opt", values = { "define": "using_hip_clang=true", "compilation_mode": "opt", }, ) cc_library( name = "rocm_headers", hdrs = [ "rocm/rocm_config.h", %{rocm_headers} ], includes = [ ".", "rocm/include", ], visibility = ["//visibility:public"], ) cc_library( name = "hip", srcs = ["rocm/lib/%{hip_lib}"], data = ["rocm/lib/%{hip_lib}"], includes = [ ".", "rocm/include", ], linkstatic = 1, visibility = ["//visibility:public"], ) cc_library( name = "miopen", srcs = ["rocm/lib/%{miopen_lib}"], data = ["rocm/lib/%{miopen_lib}"], includes = [ ".", "rocm/include", ], deps = [ ":rocblas", ], linkstatic = 1, visibility = ["//visibility:public"], ) cc_library( name = "migraphx_lib", srcs = ["rocm/lib/%{migraphx_lib}"], data = ["rocm/lib/%{migraphx_lib}"], includes = [ ".", "rocm/include", ], linkstatic = 1, visibility = ["//visibility:public"], ) cc_library( name = "migraphx_c_lib", srcs = ["rocm/lib/%{migraphx_c_lib}"], data = ["rocm/lib/%{migraphx_c_lib}"], includes = [ ".", "rocm/include", ], linkstatic = 1, visibility = ["//visibility:public"], ) cc_library( name = "migraphx_tf_lib", srcs = ["rocm/lib/%{migraphx_tf_lib}"], data = ["rocm/lib/%{migraphx_tf_lib}"], includes = [ ".", "rocm/include", ], linkstatic = 1, visibility = ["//visibility:public"], ) cc_library( name = "migraphx_device_lib", srcs = ["rocm/lib/%{migraphx_device_lib}"], data = ["rocm/lib/%{migraphx_device_lib}"], includes = [ ".", "rocm/include", ], linkstatic = 1, visibility = ["//visibility:public"], ) cc_library( name = "migraphx_gpu_lib", srcs = ["rocm/lib/%{migraphx_gpu_lib}"], data = ["rocm/lib/%{migraphx_gpu_lib}"], includes = [ ".", "rocm/include", ], linkstatic = 1, visibility = ["//visibility:public"], ) cc_library( name = "migraphx_ref_lib", srcs = ["rocm/lib/%{migraphx_ref_lib}"], data = ["rocm/lib/%{migraphx_ref_lib}"], includes = [ ".", "rocm/include", ], linkstatic = 1, visibility = ["//visibility:public"], ) cc_library( name = "migraphx_lib_onnx", srcs = ["rocm/lib/%{migraphx_onnx_lib}"], data = ["rocm/lib/%{migraphx_onnx_lib}"], includes = [ ".", "rocm/include", ], linkstatic = 1, visibility = ["//visibility:public"], ) cc_library( name = "migraphx", visibility = ["//visibility:public"], deps = [ ":migraphx_lib", ":migraphx_c_lib", ":migraphx_tf_lib", ":migraphx_device_lib", ":migraphx_gpu_lib", ":migraphx_ref_lib", ":migraphx_lib_onnx", ":miopen", ], ) cc_library( name = "rocm", visibility = ["//visibility:public"], deps = [ ":rocm_headers", ":hip", ":hipblas", ":miopen", ":migraphx", ], ) cc_library( name = "hipblas", srcs = ["rocm/lib/%{hipblas_lib}"], data = ["rocm/lib/%{hipblas_lib}"], ) cc_library( name = "rocblas", srcs = ["rocm/lib/%{rocblas_lib}"], data = ["rocm/lib/%{rocblas_lib}"], ) cc_library( name = "rpp", includes = [ ".", "rocm/include", ], linkopts = [ "-L/opt/rocm/rpp/lib", "-lamd_rpp", ], defines = [ "GPU_SUPPORT", "RPP_BACKEND_HIP", ], ) bzl_library( name = "build_defs_bzl", srcs = ["build_defs.bzl"], deps = [ "@bazel_skylib//lib:selects", ], ) filegroup( name = "rocm_root", srcs = [ "rocm/bin/clang-offload-bundler", ], ) py_library( name = "rocm_config_py", srcs = ["rocm/rocm_config.py"] ) %{copy_rules}
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/rocm/build_defs.bzl.tpl
# Macros for building ROCm code. def rocm_extra_copts(): return %{rocm_extra_copts} def rocm_header_library( name, hdrs, include_prefix = None, strip_include_prefix = None, deps = [], **kwargs): """Generates a cc_library containing both virtual and system include paths. Generates both a header-only target with virtual includes plus the full target without virtual includes. This works around the fact that bazel can't mix 'includes' and 'include_prefix' in the same target.""" native.cc_library( name = name + "_virtual", hdrs = hdrs, include_prefix = include_prefix, strip_include_prefix = strip_include_prefix, deps = deps, visibility = ["//visibility:private"], ) native.cc_library( name = name, textual_hdrs = hdrs, deps = deps + [":%s_virtual" % name], **kwargs )
0
apollo_public_repos/apollo/third_party/gpus
apollo_public_repos/apollo/third_party/gpus/rocm/rocm_config.h.tpl
#ifndef ROCM_CONFIG_H_ #define ROCM_CONFIG_H_ #define TF_ROCM_AMDGPU_TARGETS "%{rocm_amdgpu_targets}" #define TF_ROCM_TOOLKIT_PATH "%{rocm_toolkit_path}" #define TF_ROCM_VERSION "%{rocm_version_number}" #define TF_HIP_VERSION "%{hipruntime_version_number}" #define TF_HIPBLAS_VERSION "%{hipblas_version_number}" #define TF_ROCBLAS_VERSION "%{rocblas_version_number}" #define TF_MIOPEN_VERSION "%{miopen_version_number}" #define TF_MIGRAPHX_VERSION "%{migraphx_version_number}" #endif // ROCM_CONFIG_H_
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/sqlite3/cyberfile.xml
<package format="2"> <name>3rd-sqlite3</name> <version>local</version> <description> Apollo packaged sqlite3 Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/sqlite3</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/sqlite3/3rd-sqlite3.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "sqlite3", includes = [ "include", ], linkopts = [ "-lsqlite3", ], linkstatic = False, strip_include_prefix = "include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/sqlite3/workspace.bzl
"""Loads the sqlite3 library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) # apt-get -y install libsqlite3-dev def repo(): # sqlite3 native.new_local_repository( name = "sqlite3", build_file = clean_dep("//third_party/sqlite3:sqlite3.BUILD"), path = "/usr/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/sqlite3/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-sqlite3", data = [ ":cyberfile.xml", ":3rd-sqlite3.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-sqlite3/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/sqlite3/sqlite3.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "sqlite3", includes = [ ".", ], linkopts = [ "-lsqlite3", ], linkstatic = False, )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/paddleinference/init.bzl
"""Loads the centerpoint_infer_op library""" load("//third_party/paddleinference:workspace.bzl", "repo") def init(): repo()
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/paddleinference/cyberfile.xml
<package format="2"> <name>3rd-paddleinference</name> <version>local</version> <description> Apollo packaged paddleinference. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-wrapper</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/paddleinference</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/paddleinference/workspace.bzl
"""Loads the paddlelite library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def clean_dep(dep): return str(Label(dep)) def repo(): http_archive( name = "paddleinference", sha256 = "d79ae353d0181035eb6c750d1e9e8cf50148e3c8648dd1fa084e50af64380b1c", strip_prefix = "paddleinference", urls = [ "https://apollo-system.bj.bcebos.com/archive/v8.0_bev/paddleinferencev-1.0.0.tar.gz", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/paddleinference/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install_lib", data = glob([ "lib*", ]), data_dest = "3rd-paddleinference/lib", ) install( name = "install", data = [ ":cyberfile.xml", ], data_dest = "3rd-paddleinference", deps = ["install_lib"], ) install_src_files( name = "install_src", dest = "3rd-paddleinference/src", filter = "*", src_dir = ["."], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tinyxml2/3rd-tinyxml2.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "tinyxml2", includes = [ "include", ], linkopts = [ "-ltinyxml2", ], visibility = ["//visibility:public"], strip_include_prefix = "include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tinyxml2/cyberfile.xml
<package format="2"> <name>3rd-tinyxml2</name> <version>local</version> <description> Apollo packaged tinyxml2 Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/tinyxml2</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tinyxml2/tinyxml2.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "tinyxml2", includes = [ ".", ], linkopts = [ "-ltinyxml2", ], visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tinyxml2/workspace.bzl
"""Loads the tinyxml2 library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): # tinyxml2 native.new_local_repository( name = "tinyxml2", build_file = clean_dep("//third_party/tinyxml2:tinyxml2.BUILD"), path = "/usr/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tinyxml2/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-tinyxml2", data = [ ":cyberfile.xml", ":3rd-tinyxml2.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-tinyxml2/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/glew/3rd-glew.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) cc_library( name = "glew", includes = ["include"], linkopts = [ "-lGLEW", ], strip_include_prefix = "include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/glew/cyberfile.xml
<package format="2"> <name>3rd-glew</name> <version>local</version> <description> Apollo packaged glew Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/glew</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/glew/glew.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) cc_library( name = "glew", includes = ["."], linkopts = [ "-lGLEW", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/glew/workspace.bzl
"""Loads the glew library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): # gflags native.new_local_repository( name = "glew", build_file = clean_dep("//third_party/glew:glew.BUILD"), path = "/usr/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/glew/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-glew", data = [ ":cyberfile.xml", ":3rd-glew.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-glew/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/portaudio/portaudio.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) cc_library( name = "portaudio", includes = ["."], hdrs = ["portaudio.h"], linkopts = [ "-lrt", "-lasound", "-ljack", "-lpthread", "-lportaudio", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/portaudio/cyberfile.xml
<package format="2"> <name>3rd-portaudio</name> <version>local</version> <description> Apollo packaged portaudio Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/portaudio</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/portaudio/workspace.bzl
"""Loads the Portaudio library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): native.new_local_repository( name = "portaudio", build_file = clean_dep("//third_party/portaudio:portaudio.BUILD"), path = "/usr/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/portaudio/3rd-portaudio.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) cc_library( name = "portaudio", hdrs = glob(["include/**/*"]), strip_include_prefix = "include", linkopts = [ "-lrt", "-lasound", "-ljack", "-lpthread", "-lportaudio", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/portaudio/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-portaudio", data = [ ":cyberfile.xml", ":3rd-portaudio.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-portaudio/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/can_card_library/3rd-can-card-library.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "hermes_can", hdrs = [ "include/bcan.h", ], srcs = glob(["lib/libbcan.so"]), strip_include_prefix = "include", visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/can_card_library/cyberfile.xml
<package format="2"> <name>3rd-can-card-library</name> <version>local</version> <description> Apollo packaged cancard Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>module</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/can_card_library</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/can_card_library/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-can-card-library", data = [ ":cyberfile.xml", ":3rd-can-card-library.BUILD" ], ) install_src_files( name = "install_src", deps = [ "//third_party/can_card_library/hermes_can:lib", "//third_party/can_card_library/hermes_can:headers", ":src", ] ) install_src_files( name = "src", src_dir = ["."], dest = "3rd-can-card-library/src", filter = "*", )
0
apollo_public_repos/apollo/third_party/can_card_library
apollo_public_repos/apollo/third_party/can_card_library/hermes_can/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "hermes_can", srcs = select( { "@platforms//cpu:x86_64": [ "lib_x86_64/libbcan.so", ], "@platforms//cpu:aarch64": [ "lib_aarch64/libbcan.so", ], }, no_match_error = "Please Build with a Linux aarch64 or x86_64 platform", ), hdrs = [ "include/bcan.h", ], alwayslink = True, include_prefix = "hermes_can", ) install_src_files( name = "lib", src_dir = select( { "@platforms//cpu:x86_64": [ "lib_x86_64", ], "@platforms//cpu:aarch64": [ "lib_aarch64", ], }, no_match_error = "Please Build with a Linux aarch64 or x86_64 platform", ), dest = "3rd-can-card-library/lib", filter = "*.so", ) install_src_files( name = "headers", src_dir = ["include"], dest = "3rd-can-card-library/include", filter = "*", )
0
apollo_public_repos/apollo/third_party/can_card_library/hermes_can
apollo_public_repos/apollo/third_party/can_card_library/hermes_can/include/bcan.h
/************************************************************************ * * Copyright (c) 2016 Baidu.com, Inc. All Rights Reserved * ************************************************************************/ /** * @file bcan.h * * Baidu ADV (Autonomous Driving Vehicle) bcan library definitions. **/ #ifndef ADU_PLAT_SW_LIB_BCAN_BCAN_H #define ADU_PLAT_SW_LIB_BCAN_BCAN_H #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #include <sys/ioctl.h> /* bcan_msg_t and bcan_err_code definitions. */ #include "linux/bcan_defs.h" #ifdef __cplusplus extern "C" { #endif #define BCAN_MAX_TX_MSG 256 #define BCAN_MAX_RX_MSG 256 // Channel states #define BCAN_DEV_UNINIT -1 #define BCAN_DEV_OPEN (1 << 0) #define BCAN_DEV_CLOSE (1 << 1) #define BCAN_DEV_BAUD_SET (1 << 2) #define BCAN_DEV_NORMAL (1 << 3) #define BCAN_DEV_LOOPBACK (1 << 4) #define BCAN_DEV_CONFIG (1 << 5) #define BCAN_DEV_START (1 << 6) #define BCAN_DEV_STOP (1 << 7) #define BCAN_DEV_ACTIVE (1 << 8) #define BCAN_DEV_RECVD (1 << 9) typedef uint64_t bcan_hdl_t; enum bcan_baudrate_val { BCAN_BAUDRATE_1M, BCAN_BAUDRATE_500K, BCAN_BAUDRATE_250K, BCAN_BAUDRATE_150K, BCAN_BAUDRATE_NUM }; /* Returns bcan library version. */ const char *bcan_get_libversion(void); /* Returns detailed bcan library build info. */ const char *bcan_bld_info(void); /* Returns brief bcan library build info. */ const char *bcan_bld_info_short(void); /* Returns error message corresponding to the given error code. */ const char *bcan_get_err_msg(int err_code); int bcan_open(uint32_t dev_index, uint32_t flags, uint64_t tx_to, uint64_t rx_to, bcan_hdl_t *hdl); int bcan_close(bcan_hdl_t hdl); int bcan_start(bcan_hdl_t hdl); int bcan_stop(bcan_hdl_t hdl); int bcan_set_loopback(bcan_hdl_t hdl); int bcan_unset_loopback(bcan_hdl_t hdl); int bcan_set_baudrate(bcan_hdl_t hdl, uint32_t rate); int bcan_get_baudrate(bcan_hdl_t hdl, uint32_t *rate); int bcan_recv(bcan_hdl_t hdl, bcan_msg_t *buf, uint32_t num_msg); int bcan_send(bcan_hdl_t hdl, bcan_msg_t *buf, uint32_t num_msg); int bcan_send_hi_pri(bcan_hdl_t hdl, bcan_msg_t *buf); int bcan_get_status(bcan_hdl_t hdl); int bcan_get_err_counter(bcan_hdl_t hdl, uint8_t *rx_err, uint8_t *tx_err); /* The following APIs are not implemented yet. { */ int bcan_id_add(bcan_hdl_t hdl, uint32_t id_start, uint32_t id_end); int bcan_id_add_all(bcan_hdl_t hdl); int bcan_id_remove(bcan_hdl_t hdl, uint32_t id_start, uint32_t id_end); int bcan_id_remove_all(bcan_hdl_t hdl); /* } Not implemented. */ #ifdef __cplusplus } #endif #endif /* ADU_PLAT_SW_LIB_BCAN_BCAN_LIB_H */
0
apollo_public_repos/apollo/third_party/can_card_library/hermes_can
apollo_public_repos/apollo/third_party/can_card_library/hermes_can/include/bcan_lib.h
#ifndef _BCAN_LIB_H_ #define _BCAN_LIB_H_ #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #include <sys/ioctl.h> #include "linux/zynq_api.h" #ifdef DEBUG #define BLOG_DBG0(s...) syslog(LOG_DEBUG, s); #else #define BLOG_DBG0(s...) do{}while(0); #endif #define BLOG_ERR(s...) syslog(LOG_ERR, s); typedef uint64_t bcan_hdl_t; #define BCAN_MAX_TX_MSG 256 #define BCAN_MAX_RX_MSG 256 typedef struct bcan_ihdl { int dev_index; int dev_state; int fd; uint32_t baudrate; uint32_t tx_to; uint32_t rx_to; } bcan_ihdl_t; // Channel states #define BCAN_DEV_UNINIT -1 #define BCAN_DEV_OPEN (1 << 0) #define BCAN_DEV_CLOSE (1 << 1) #define BCAN_DEV_BAUD_SET (1 << 2) #define BCAN_DEV_NORMAL (1 << 3) #define BCAN_DEV_LOOPBACK (1 << 4) #define BCAN_DEV_CONFIG (1 << 5) #define BCAN_DEV_START (1 << 6) #define BCAN_DEV_STOP (1 << 7) #define BCAN_DEV_ACTIVE (1 << 8) #define BCAN_DEV_RECVD (1 << 9) #endif /* _BCAN_LIB_H_ */
0
apollo_public_repos/apollo/third_party/can_card_library
apollo_public_repos/apollo/third_party/can_card_library/esd_can/README.md
## ESD CAN Library In the first release of Apollo software, ESD PCIe CAN is supported out of the box -- please refer to *Apollo 1.0 Hardware and System Installation Guide* for more information. However, you MUST obtain ESD's CAN library software from ESD Electronics to compile and use it in Apollo software stack. 1. After/when you purchase CAN card from ESD Electronics, please contact support@esd.eu to obtain the supporting software package for Linux. The CAN card to use with the IPC is ESD CAN-PCIe/402. For more information about the CAN-PCIe/402, see the [ESD CAN-PCIe/402 Product Page](https://esd.eu/en/products/can-pcie402) 2. After unpacking the software package, please find and copy the following files to the specific sub-directories (under this directory): * Copy ntcan.h to include/ * Copy 64-bit libntcan.so.4.0.1 to lib/ * Do the following to add the necessary symbolic links: cd ./lib/; ln -s libntcan.so.4.0.1 libntcan.so.4; ln -s libntcan.so.4.0.1 libntcan.so.4.0
0
apollo_public_repos/apollo/third_party/can_card_library
apollo_public_repos/apollo/third_party/can_card_library/esd_can/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools/platform:build_defs.bzl", "if_esd_can") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "esd_can", srcs = if_esd_can(["lib/libntcan.so.4"]), hdrs = if_esd_can(["include/ntcan.h"]), include_prefix = "esd_can", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/atlas/cyberfile.xml
<package format="2"> <name>3rd-atlas</name> <version>local</version> <description> Apollo packaged atlas Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/atlas</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/atlas/atlas.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "atlas", includes = [ ".", ], linkopts = [ "-latlas", ], linkstatic = False, ) cc_library( name = "blas", includes = [ ".", ], linkopts = [ "-lblas", ], linkstatic = False, ) cc_library( name = "cblas", includes = [ ".", ], linkopts = [ "-lcblas", ], linkstatic = False, ) cc_library( name = "lapack", includes = [ ".", ], linkopts = [ "-llapack", ], linkstatic = False, )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/atlas/3rd-atlas.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "atlas", includes = [ "include", ], linkopts = [ "-latlas", ], linkstatic = False, strip_include_prefix = "include", ) cc_library( name = "blas", includes = [ "include", ], linkopts = [ "-lblas", ], linkstatic = False, strip_include_prefix = "include", ) cc_library( name = "cblas", includes = [ "include", ], linkopts = [ "-lcblas", ], linkstatic = False, strip_include_prefix = "include", ) cc_library( name = "lapack", includes = [ "include", ], linkopts = [ "-llapack", ], linkstatic = False, strip_include_prefix = "include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/atlas/workspace.bzl
"""Loads the atlas library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) # Installed via atlas-dev def repo(): # atlas native.new_local_repository( name = "atlas", build_file = clean_dep("//third_party/atlas:atlas.BUILD"), path = "/usr/include", # /usr/include/$(uname -m)-linux-gnu )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/atlas/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-atlas", data = [ ":cyberfile.xml", ":3rd-atlas.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-atlas/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/openh264/cyberfile.xml
<package format="2"> <name>3rd-openh264</name> <version>local</version> <description> Apollo packaged openh264 Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/openh264</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/openh264/openh264.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "openh264", includes = [ ".", ], linkopts = [ # "-L/usr/local/lib", "-L/opt/apollo/sysroot/lib", "-lopenh264", ], linkstatic = False, )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/openh264/workspace.bzl
"""Loads the openh264 library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): native.new_local_repository( name = "openh264", build_file = clean_dep("//third_party/openh264:openh264.BUILD"), # path = "/usr/local/include", path = "/opt/apollo/sysroot/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/openh264/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-openh264", data = [ ":cyberfile.xml", ":3rd-openh264.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-openh264/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/openh264/3rd-openh264.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "openh264", includes = [ "include", ], linkopts = [ "-lopenh264", ], linkstatic = False, strip_include_prefix = "include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/civetweb/civetweb.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_binary") licenses(["notice"]) exports_files(["LICENSE.md"]) cc_library( name = "civetweb", srcs = [ "src/civetweb.c", ], #hdrs = glob([ # "include/*.h", # "src/*.inl", # #"src/md5.inl", #]), copts = [ "-DUSE_WEBSOCKET", ], includes = [ "include", "src", ], linkopts = [ "-lpthread", "-ldl", ], deps = [ "h_headers", "inl_headers" ], visibility = ["//visibility:public"], alwayslink = True, ) cc_library( name = "h_headers", hdrs = glob([ "include/*.h", ]), strip_include_prefix = "include", ) cc_library( name = "inl_headers", hdrs = glob([ "src/*.inl", ]), strip_include_prefix = "src", ) cc_binary( name = "libcivetweb++.so", srcs = [ "src/CivetServer.cpp", "include/CivetServer.h", ], visibility = ["//visibility:public"], deps = [ ":civetweb", ], linkshared = True, linkstatic = True, ) # The C++ wrapper for civetweb. cc_library( name = "civetweb++", srcs = [ "libcivetweb++.so", ], #hdrs = glob([ # "include/*.h", #]), includes = [ "include", ], deps = [ "h_headers", ], visibility = ["//visibility:public"], ) filegroup( name = "civetweb_hdrs", srcs = glob([ "include/*.h", ]), visibility = ["//visibility:public"], ) filegroup( name = "civetweb_libs", srcs = [ ":libcivetweb++.so", ], visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/civetweb/init.bzl
"""Loads the civetweb library""" load("//third_party/civetweb:workspace.bzl", "repo") def init(): repo()
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/civetweb/cyberfile.xml
<package format="2"> <name>3rd-civetweb</name> <version>local</version> <description> Apollo packaged civetweb Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-wrapper</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/civetweb</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/civetweb/workspace.bzl
"""Loads the civetweb library""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): http_archive( name = "civetweb", build_file = clean_dep("//third_party/civetweb:civetweb.BUILD"), sha256 = "de7d5e7a2d9551d325898c71e41d437d5f7b51e754b242af897f7be96e713a42", strip_prefix = "civetweb-1.11", urls = [ "https://apollo-system.cdn.bcebos.com/archive/6.0/v1.11.tar.gz", "https://github.com/civetweb/civetweb/archive/v1.11.tar.gz", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/civetweb/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-civetweb", library_dest = "3rd-civetweb/lib", data = [ ":cyberfile.xml", ], deps = [ ":install_libs", ":install_hdrs", ], ) install( name = "install_libs", data_dest = "3rd-civetweb/lib", data = [ "@civetweb//:civetweb_libs", ], data_strip_prefix = [ "third_party/civetweb", ], ) install( name = "install_hdrs", data_dest = "3rd-civetweb/include", data = [ "@civetweb//:civetweb_hdrs", ], data_strip_prefix = [ "third_party/civetweb", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-civetweb/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/uuid/uuid.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "uuid", includes = [ ".", ], linkopts = [ "-luuid", ], linkstatic = False, )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/uuid/3rd-uuid.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "uuid", includes = [ "include", ], linkopts = [ "-luuid", ], linkstatic = False, strip_include_prefix = "include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/uuid/cyberfile.xml
<package format="2"> <name>3rd-uuid</name> <version>local</version> <description> Apollo packaged uuid Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/uuid</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/uuid/workspace.bzl
"""Loads the uuid library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) # Installed via uuid-dev def repo(): # uuid native.new_local_repository( name = "uuid", build_file = clean_dep("//third_party/uuid:uuid.BUILD"), path = "/usr/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/uuid/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-uuid", data = [ ":cyberfile.xml", ":3rd-uuid.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-uuid/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/rtklib/cyberfile.xml
<package format="2"> <name>3rd-rtklib</name> <version>local</version> <description> Apollo packaged cancard Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>module</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/rtklib</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/rtklib/rtklib.h
/********************************************************************************* * The RTKLIB software package is distributed under the following BSD 2-clause * license (http://opensource.org/licenses/BSD-2-Clause) and additional two * exclusive clauses. Users are permitted to develop, produce or sell their own * non-commercial or commercial products utilizing, linking or including RTKLIB *as * long as they comply with the license. * * Copyright (c) 2007-2013, T. Takasu, 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. * * - The software package includes some companion executive binaries or shared * libraries necessary to execute APs on Windows. These licenses succeed to *the original ones of these software. * * 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 HOLDER 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. ***********************************************************************************/ /*------------------------------------------------------------------------------ * rtklib.h : rtklib constants, types and function prototypes * * Copyright (C) 2007-2015 by T.TAKASU, All rights reserved. * * options : -DENAGLO enable GLONASS * -DENAGAL enable Galileo * -DENAQZS enable QZSS * -DENACMP enable BeiDou * -DNFREQ=n set number of obs codes/frequencies * -DNEXOBS=n set number of extended obs codes * -DMAXOBS=n set max number of obs data in an epoch * -DEXTLEX enable QZSS LEX extension * * version : $Revision: 1.1 $ $Date: 2008/07/17 21:48:06 $ * history : 2007/01/13 1.0 rtklib ver.1.0.0 * 2007/03/20 1.1 rtklib ver.1.1.0 * 2008/07/15 1.2 rtklib ver.2.1.0 * 2008/10/19 1.3 rtklib ver.2.1.1 * 2009/01/31 1.4 rtklib ver.2.2.0 * 2009/04/30 1.5 rtklib ver.2.2.1 * 2009/07/30 1.6 rtklib ver.2.2.2 * 2009/12/25 1.7 rtklib ver.2.3.0 * 2010/07/29 1.8 rtklib ver.2.4.0 * 2011/05/27 1.9 rtklib ver.2.4.1 * 2013/03/28 1.10 rtklib ver.2.4.2 *-----------------------------------------------------------------------------*/ /** * file: rtklib.h * version: rtklib ver.2.4.2 * Copy from * https://github.com/tomojitakasu/RTKLIB/tree/76b9c97257f304aedad38b5a6bbbac444724aab3/src/rtklib.h */ #pragma once #include <ctype.h> #include <math.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #ifdef WIN32 #include <windows.h> #include <winsock2.h> #else #include <pthread.h> #endif #ifdef __cplusplus extern "C" { #endif /* constants -----------------------------------------------------------------*/ // #define TRACE #define ENAGLO #define ENACMP #define VER_RTKLIB "2.4.2" /* library version */ #define PATCH_LEVEL "p11" /* patch level */ #define COPYRIGHT_RTKLIB \ "Copyright (C) 2007-2015 by T.Takasu\nAll rights reserved." #define PI 3.1415926535897932 /* pi */ #define D2R (PI / 180.0) /* deg to rad */ #define R2D (180.0 / PI) /* rad to deg */ #define CLIGHT 299792458.0 /* speed of light (m/s) */ #define SC2RAD 3.1415926535898 /* semi-circle to radian (IS-GPS) */ #define AU 149597870691.0 /* 1 AU (m) */ #define AS2R (D2R / 3600.0) /* arc sec to radian */ #define OMGE 7.2921151467E-5 /* earth angular velocity (IS-GPS) (rad/s) */ #define RE_WGS84 6378137.0 /* earth semimajor axis (WGS84) (m) */ #define FE_WGS84 (1.0 / 298.257223563) /* earth flattening (WGS84) */ #define HION 350000.0 /* ionosphere height (m) */ #define MAXFREQ 7 /* max NFREQ */ #define FREQ1 1.57542E9 /* L1/E1 frequency (Hz) */ #define FREQ2 1.22760E9 /* L2 frequency (Hz) */ #define FREQ5 1.17645E9 /* L5/E5a frequency (Hz) */ #define FREQ6 1.27875E9 /* E6/LEX frequency (Hz) */ #define FREQ7 1.20714E9 /* E5b frequency (Hz) */ #define FREQ8 1.191795E9 /* E5a+b frequency (Hz) */ #define FREQ1_GLO 1.60200E9 /* GLONASS G1 base frequency (Hz) */ #define DFRQ1_GLO 0.56250E6 /* GLONASS G1 bias frequency (Hz/n) */ #define FREQ2_GLO 1.24600E9 /* GLONASS G2 base frequency (Hz) */ #define DFRQ2_GLO 0.43750E6 /* GLONASS G2 bias frequency (Hz/n) */ #define FREQ3_GLO 1.202025E9 /* GLONASS G3 frequency (Hz) */ #define FREQ1_CMP 1.561098E9 /* BeiDou B1 frequency (Hz) */ #define FREQ2_CMP 1.20714E9 /* BeiDou B2 frequency (Hz) */ #define FREQ3_CMP 1.26852E9 /* BeiDou B3 frequency (Hz) */ #define EFACT_GPS 1.0 /* error factor: GPS */ #define EFACT_GLO 1.5 /* error factor: GLONASS */ #define EFACT_GAL 1.0 /* error factor: Galileo */ #define EFACT_QZS 1.0 /* error factor: QZSS */ #define EFACT_CMP 1.0 /* error factor: BeiDou */ #define EFACT_SBS 3.0 /* error factor: SBAS */ #define SYS_NONE 0x00 /* navigation system: none */ #define SYS_GPS 0x01 /* navigation system: GPS */ #define SYS_SBS 0x02 /* navigation system: SBAS */ #define SYS_GLO 0x04 /* navigation system: GLONASS */ #define SYS_GAL 0x08 /* navigation system: Galileo */ #define SYS_QZS 0x10 /* navigation system: QZSS */ #define SYS_CMP 0x20 /* navigation system: BeiDou */ #define SYS_LEO 0x40 /* navigation system: LEO */ #define SYS_ALL 0xFF /* navigation system: all */ #define TSYS_GPS 0 /* time system: GPS time */ #define TSYS_UTC 1 /* time system: UTC */ #define TSYS_GLO 2 /* time system: GLONASS time */ #define TSYS_GAL 3 /* time system: Galileo time */ #define TSYS_QZS 4 /* time system: QZSS time */ #define TSYS_CMP 5 /* time system: BeiDou time */ #ifndef NFREQ #define NFREQ 3 /* number of carrier frequencies */ #endif #define NFREQGLO 2 /* number of carrier frequencies of GLONASS */ #ifndef NEXOBS #define NEXOBS 0 /* number of extended obs codes */ #endif #define MINPRNGPS 1 /* min satellite PRN number of GPS */ #define MAXPRNGPS 32 /* max satellite PRN number of GPS */ #define NSATGPS (MAXPRNGPS - MINPRNGPS + 1) /* number of GPS satellites */ #define NSYSGPS 1 #ifdef ENAGLO #define MINPRNGLO 1 /* min satellite slot number of GLONASS */ #define MAXPRNGLO 24 /* max satellite slot number of GLONASS */ #define NSATGLO (MAXPRNGLO - MINPRNGLO + 1) /* number of GLONASS satellites */ #define NSYSGLO 1 #else #define MINPRNGLO 0 #define MAXPRNGLO 0 #define NSATGLO 0 #define NSYSGLO 0 #endif #ifdef ENAGAL #define MINPRNGAL 1 /* min satellite PRN number of Galileo */ #define MAXPRNGAL 27 /* max satellite PRN number of Galileo */ #define NSATGAL (MAXPRNGAL - MINPRNGAL + 1) /* number of Galileo satellites */ #define NSYSGAL 1 #else #define MINPRNGAL 0 #define MAXPRNGAL 0 #define NSATGAL 0 #define NSYSGAL 0 #endif #ifdef ENAQZS #define MINPRNQZS 193 /* min satellite PRN number of QZSS */ #define MAXPRNQZS 199 /* max satellite PRN number of QZSS */ #define MINPRNQZS_S 183 /* min satellite PRN number of QZSS SAIF */ #define MAXPRNQZS_S 189 /* max satellite PRN number of QZSS SAIF */ #define NSATQZS (MAXPRNQZS - MINPRNQZS + 1) /* number of QZSS satellites */ #define NSYSQZS 1 #else #define MINPRNQZS 0 #define MAXPRNQZS 0 #define MINPRNQZS_S 0 #define MAXPRNQZS_S 0 #define NSATQZS 0 #define NSYSQZS 0 #endif #ifdef ENACMP #define MINPRNCMP 1 /* min satellite sat number of BeiDou */ #define MAXPRNCMP 35 /* max satellite sat number of BeiDou */ #define NSATCMP (MAXPRNCMP - MINPRNCMP + 1) /* number of BeiDou satellites */ #define NSYSCMP 1 #else #define MINPRNCMP 0 #define MAXPRNCMP 0 #define NSATCMP 0 #define NSYSCMP 0 #endif #ifdef ENALEO #define MINPRNLEO 1 /* min satellite sat number of LEO */ #define MAXPRNLEO 10 /* max satellite sat number of LEO */ #define NSATLEO (MAXPRNLEO - MINPRNLEO + 1) /* number of LEO satellites */ #define NSYSLEO 1 #else #define MINPRNLEO 0 #define MAXPRNLEO 0 #define NSATLEO 0 #define NSYSLEO 0 #endif #define NSYS \ (NSYSGPS + NSYSGLO + NSYSGAL + NSYSQZS + NSYSCMP + \ NSYSLEO) /* number of systems */ #define MINPRNSBS 120 /* min satellite PRN number of SBAS */ #define MAXPRNSBS 142 /* max satellite PRN number of SBAS */ #define NSATSBS (MAXPRNSBS - MINPRNSBS + 1) /* number of SBAS satellites */ #define MAXSAT \ (NSATGPS + NSATGLO + NSATGAL + NSATQZS + NSATCMP + NSATSBS + NSATLEO) /* max satellite number (1 to MAXSAT) */ #ifndef MAXOBS #define MAXOBS 64 /* max number of obs in an epoch */ #endif #define MAXRCV 64 /* max receiver number (1 to MAXRCV) */ #define MAXOBSTYPE 64 /* max number of obs type in RINEX */ #define DTTOL 0.005 /* tolerance of time difference (s) */ #define MAXDTOE 7200.0 /* max time difference to GPS Toe (s) */ #define MAXDTOE_QZS 7200.0 /* max time difference to QZSS Toe (s) */ #define MAXDTOE_GAL 10800.0 /* max time difference to Galileo Toe (s) */ #define MAXDTOE_CMP 21600.0 /* max time difference to BeiDou Toe (s) */ #define MAXDTOE_GLO 1800.0 /* max time difference to GLONASS Toe (s) */ #define MAXDTOE_SBS 360.0 /* max time difference to SBAS Toe (s) */ #define MAXDTOE_S 86400.0 /* max time difference to ephem toe (s) for other */ #define MAXGDOP 300.0 /* max GDOP */ #define INT_SWAP_TRAC 86400.0 /* swap interval of trace file (s) */ #define INT_SWAP_STAT 86400.0 /* swap interval of solution status file (s) */ #define MAXEXFILE 1024 /* max number of expanded files */ #define MAXSBSAGEF 30.0 /* max age of SBAS fast correction (s) */ #define MAXSBSAGEL 1800.0 /* max age of SBAS long term corr (s) */ #define MAXSBSURA 8 /* max URA of SBAS satellite */ #define MAXBAND 10 /* max SBAS band of IGP */ #define MAXNIGP 201 /* max number of IGP in SBAS band */ #define MAXNGEO 4 /* max number of GEO satellites */ #define MAXCOMMENT 10 /* max number of RINEX comments */ #define MAXSTRPATH 1024 /* max length of stream path */ #define MAXSTRMSG 1024 /* max length of stream message */ #define MAXSTRRTK 8 /* max number of stream in RTK server */ #define MAXSBSMSG 32 /* max number of SBAS msg in RTK server */ #define MAXSOLMSG 4096 /* max length of solution message */ #define MAXRAWLEN 4096 /* max length of receiver raw message */ #define MAXERRMSG 4096 /* max length of error/warning message */ #define MAXANT 64 /* max length of station name/antenna type */ #define MAXSOLBUF 256 /* max number of solution buffer */ #define MAXOBSBUF 128 /* max number of observation data buffer */ #define MAXNRPOS 16 /* max number of reference positions */ #define MAXLEAPS 64 /* max number of leap seconds table */ #define RNX2VER 2.10 /* RINEX ver.2 default output version */ #define RNX3VER 3.00 /* RINEX ver.3 default output version */ #define OBSTYPE_PR 0x01 /* observation type: pseudorange */ #define OBSTYPE_CP 0x02 /* observation type: carrier-phase */ #define OBSTYPE_DOP 0x04 /* observation type: doppler-freq */ #define OBSTYPE_SNR 0x08 /* observation type: SNR */ #define OBSTYPE_ALL 0xFF /* observation type: all */ #define FREQTYPE_L1 0x01 /* frequency type: L1/E1 */ #define FREQTYPE_L2 0x02 /* frequency type: L2/B1 */ #define FREQTYPE_L5 0x04 /* frequency type: L5/E5a/L3 */ #define FREQTYPE_L6 0x08 /* frequency type: E6/LEX/B3 */ #define FREQTYPE_L7 0x10 /* frequency type: E5b/B2 */ #define FREQTYPE_L8 0x20 /* frequency type: E5(a+b) */ #define FREQTYPE_ALL 0xFF /* frequency type: all */ #define CODE_NONE 0 /* obs code: none or unknown */ #define CODE_L1C 1 /* obs code: L1C/A,G1C/A,E1C (GPS,GLO,GAL,QZS,SBS) */ #define CODE_L1P 2 /* obs code: L1P,G1P (GPS,GLO) */ #define CODE_L1W 3 /* obs code: L1 Z-track (GPS) */ #define CODE_L1Y 4 /* obs code: L1Y (GPS) */ #define CODE_L1M 5 /* obs code: L1M (GPS) */ #define CODE_L1N 6 /* obs code: L1codeless (GPS) */ #define CODE_L1S 7 /* obs code: L1C(D) (GPS,QZS) */ #define CODE_L1L 8 /* obs code: L1C(P) (GPS,QZS) */ #define CODE_L1E 9 /* obs code: L1-SAIF (QZS) */ #define CODE_L1A 10 /* obs code: E1A (GAL) */ #define CODE_L1B 11 /* obs code: E1B (GAL) */ #define CODE_L1X 12 /* obs code: E1B+C,L1C(D+P) (GAL,QZS) */ #define CODE_L1Z 13 /* obs code: E1A+B+C,L1SAIF (GAL,QZS) */ #define CODE_L2C 14 /* obs code: L2C/A,G1C/A (GPS,GLO) */ #define CODE_L2D 15 /* obs code: L2 L1C/A-(P2-P1) (GPS) */ #define CODE_L2S 16 /* obs code: L2C(M) (GPS,QZS) */ #define CODE_L2L 17 /* obs code: L2C(L) (GPS,QZS) */ #define CODE_L2X 18 /* obs code: L2C(M+L),B1I+Q (GPS,QZS,CMP) */ #define CODE_L2P 19 /* obs code: L2P,G2P (GPS,GLO) */ #define CODE_L2W 20 /* obs code: L2 Z-track (GPS) */ #define CODE_L2Y 21 /* obs code: L2Y (GPS) */ #define CODE_L2M 22 /* obs code: L2M (GPS) */ #define CODE_L2N 23 /* obs code: L2codeless (GPS) */ #define CODE_L5I 24 /* obs code: L5/E5aI (GPS,GAL,QZS,SBS) */ #define CODE_L5Q 25 /* obs code: L5/E5aQ (GPS,GAL,QZS,SBS) */ #define CODE_L5X 26 /* obs code: L5/E5aI+Q (GPS,GAL,QZS,SBS) */ #define CODE_L7I 27 /* obs code: E5bI,B2I (GAL,CMP) */ #define CODE_L7Q 28 /* obs code: E5bQ,B2Q (GAL,CMP) */ #define CODE_L7X 29 /* obs code: E5bI+Q,B2I+Q (GAL,CMP) */ #define CODE_L6A 30 /* obs code: E6A (GAL) */ #define CODE_L6B 31 /* obs code: E6B (GAL) */ #define CODE_L6C 32 /* obs code: E6C (GAL) */ #define CODE_L6X 33 /* obs code: E6B+C,LEXS+L,B3I+Q (GAL,QZS,CMP) */ #define CODE_L6Z 34 /* obs code: E6A+B+C (GAL) */ #define CODE_L6S 35 /* obs code: LEXS (QZS) */ #define CODE_L6L 36 /* obs code: LEXL (QZS) */ #define CODE_L8I 37 /* obs code: E5(a+b)I (GAL) */ #define CODE_L8Q 38 /* obs code: E5(a+b)Q (GAL) */ #define CODE_L8X 39 /* obs code: E5(a+b)I+Q (GAL) */ #define CODE_L2I 40 /* obs code: B1I (CMP) */ #define CODE_L2Q 41 /* obs code: B1Q (CMP) */ #define CODE_L6I 42 /* obs code: B3I (CMP) */ #define CODE_L6Q 43 /* obs code: B3Q (CMP) */ #define CODE_L3I 44 /* obs code: G3I (GLO) */ #define CODE_L3Q 45 /* obs code: G3Q (GLO) */ #define CODE_L3X 46 /* obs code: G3I+Q (GLO) */ #define CODE_L1I 47 /* obs code: B1I (BDS) */ #define CODE_L1Q 48 /* obs code: B1Q (BDS) */ #define MAXCODE 48 /* max number of obs code */ #define PMODE_SINGLE 0 /* positioning mode: single */ #define PMODE_DGPS 1 /* positioning mode: DGPS/DGNSS */ #define PMODE_KINEMA 2 /* positioning mode: kinematic */ #define PMODE_STATIC 3 /* positioning mode: static */ #define PMODE_MOVEB 4 /* positioning mode: moving-base */ #define PMODE_FIXED 5 /* positioning mode: fixed */ #define PMODE_PPP_KINEMA 6 /* positioning mode: PPP-kinemaric */ #define PMODE_PPP_STATIC 7 /* positioning mode: PPP-static */ #define PMODE_PPP_FIXED 8 /* positioning mode: PPP-fixed */ #define SOLF_LLH 0 /* solution format: lat/lon/height */ #define SOLF_XYZ 1 /* solution format: x/y/z-ecef */ #define SOLF_ENU 2 /* solution format: e/n/u-baseline */ #define SOLF_NMEA 3 /* solution format: NMEA-183 */ #define SOLF_GSIF 4 /* solution format: GSI-F1/2/3 */ #define SOLQ_NONE 0 /* solution status: no solution */ #define SOLQ_FIX 1 /* solution status: fix */ #define SOLQ_FLOAT 2 /* solution status: float */ #define SOLQ_SBAS 3 /* solution status: SBAS */ #define SOLQ_DGPS 4 /* solution status: DGPS/DGNSS */ #define SOLQ_SINGLE 5 /* solution status: single */ #define SOLQ_PPP 6 /* solution status: PPP */ #define SOLQ_DR 7 /* solution status: dead reconing */ #define MAXSOLQ 7 /* max number of solution status */ #define TIMES_GPST 0 /* time system: gps time */ #define TIMES_UTC 1 /* time system: utc */ #define TIMES_JST 2 /* time system: jst */ #define IONOOPT_OFF 0 /* ionosphere option: correction off */ #define IONOOPT_BRDC 1 /* ionosphere option: broadcast model */ #define IONOOPT_SBAS 2 /* ionosphere option: SBAS model */ #define IONOOPT_IFLC 3 /* ionosphere option: L1/L2 or L1/L5 iono-free LC */ #define IONOOPT_EST 4 /* ionosphere option: estimation */ #define IONOOPT_TEC 5 /* ionosphere option: IONEX TEC model */ #define IONOOPT_QZS 6 /* ionosphere option: QZSS broadcast model */ #define IONOOPT_LEX 7 /* ionosphere option: QZSS LEX ionospehre */ #define IONOOPT_STEC 8 /* ionosphere option: SLANT TEC model */ #define TROPOPT_OFF 0 /* troposphere option: correction off */ #define TROPOPT_SAAS 1 /* troposphere option: Saastamoinen model */ #define TROPOPT_SBAS 2 /* troposphere option: SBAS model */ #define TROPOPT_EST 3 /* troposphere option: ZTD estimation */ #define TROPOPT_ESTG 4 /* troposphere option: ZTD+grad estimation */ #define TROPOPT_COR 5 /* troposphere option: ZTD correction */ #define TROPOPT_CORG 6 /* troposphere option: ZTD+grad correction */ #define EPHOPT_BRDC 0 /* ephemeris option: broadcast ephemeris */ #define EPHOPT_PREC 1 /* ephemeris option: precise ephemeris */ #define EPHOPT_SBAS 2 /* ephemeris option: broadcast + SBAS */ #define EPHOPT_SSRAPC 3 /* ephemeris option: broadcast + SSR_APC */ #define EPHOPT_SSRCOM 4 /* ephemeris option: broadcast + SSR_COM */ #define EPHOPT_LEX 5 /* ephemeris option: QZSS LEX ephemeris */ #define ARMODE_OFF 0 /* AR mode: off */ #define ARMODE_CONT 1 /* AR mode: continuous */ #define ARMODE_INST 2 /* AR mode: instantaneous */ #define ARMODE_FIXHOLD 3 /* AR mode: fix and hold */ #define ARMODE_PPPAR 4 /* AR mode: PPP-AR */ #define ARMODE_PPPAR_ILS 5 /* AR mode: PPP-AR ILS */ #define ARMODE_WLNL 6 /* AR mode: wide lane/narrow lane */ #define ARMODE_TCAR 7 /* AR mode: triple carrier ar */ #define SBSOPT_LCORR 1 /* SBAS option: long term correction */ #define SBSOPT_FCORR 2 /* SBAS option: fast correction */ #define SBSOPT_ICORR 4 /* SBAS option: ionosphere correction */ #define SBSOPT_RANGE 8 /* SBAS option: ranging */ #define STR_NONE 0 /* stream type: none */ #define STR_SERIAL 1 /* stream type: serial */ #define STR_FILE 2 /* stream type: file */ #define STR_TCPSVR 3 /* stream type: TCP server */ #define STR_TCPCLI 4 /* stream type: TCP client */ #define STR_UDP 5 /* stream type: UDP stream */ #define STR_NTRIPSVR 6 /* stream type: NTRIP server */ #define STR_NTRIPCLI 7 /* stream type: NTRIP client */ #define STR_FTP 8 /* stream type: ftp */ #define STR_HTTP 9 /* stream type: http */ #define STRFMT_RTCM2 0 /* stream format: RTCM 2 */ #define STRFMT_RTCM3 1 /* stream format: RTCM 3 */ #define STRFMT_OEM4 2 /* stream format: NovAtel OEMV/4 */ #define STRFMT_OEM3 3 /* stream format: NovAtel OEM3 */ #define STRFMT_UBX 4 /* stream format: u-blox LEA-*T */ #define STRFMT_SS2 5 /* stream format: NovAtel Superstar II */ #define STRFMT_CRES 6 /* stream format: Hemisphere */ #define STRFMT_STQ 7 /* stream format: SkyTraq S1315F */ #define STRFMT_GW10 8 /* stream format: Furuno GW10 */ #define STRFMT_JAVAD 9 /* stream format: JAVAD GRIL/GREIS */ #define STRFMT_NVS 10 /* stream format: NVS NVC08C */ #define STRFMT_BINEX 11 /* stream format: BINEX */ #define STRFMT_RT17 12 /* stream format: Trimble RT17 */ #define STRFMT_LEXR 13 /* stream format: Furuno LPY-10000 */ #define STRFMT_SEPT 14 /* stream format: Septentrio */ #define STRFMT_RINEX 15 /* stream format: RINEX */ #define STRFMT_SP3 16 /* stream format: SP3 */ #define STRFMT_RNXCLK 17 /* stream format: RINEX CLK */ #define STRFMT_SBAS 18 /* stream format: SBAS messages */ #define STRFMT_NMEA 19 /* stream format: NMEA 0183 */ #ifndef EXTLEX #define MAXRCVFMT 12 /* max number of receiver format */ #else #define MAXRCVFMT 13 #endif #define STR_MODE_R 0x1 /* stream mode: read */ #define STR_MODE_W 0x2 /* stream mode: write */ #define STR_MODE_RW 0x3 /* stream mode: read/write */ #define GEOID_EMBEDDED 0 /* geoid model: embedded geoid */ #define GEOID_EGM96_M150 1 /* geoid model: EGM96 15x15" */ #define GEOID_EGM2008_M25 2 /* geoid model: EGM2008 2.5x2.5" */ #define GEOID_EGM2008_M10 3 /* geoid model: EGM2008 1.0x1.0" */ #define GEOID_GSI2000_M15 4 /* geoid model: GSI geoid 2000 1.0x1.5" */ #define GEOID_RAF09 5 /* geoid model: IGN RAF09 for France 1.5"x2" */ #define COMMENTH "%" /* comment line indicator for solution */ #define MSG_DISCONN "$_DISCONNECT\r\n" /* disconnect message */ #define DLOPT_FORCE 0x01 /* download option: force download existing */ #define DLOPT_KEEPCMP 0x02 /* download option: keep compressed file */ #define DLOPT_HOLDERR 0x04 /* download option: hold on error file */ #define DLOPT_HOLDLST 0x08 /* download option: hold on listing file */ #define P2_5 0.03125 /* 2^-5 */ #define P2_6 0.015625 /* 2^-6 */ #define P2_11 4.882812500000000E-04 /* 2^-11 */ #define P2_15 3.051757812500000E-05 /* 2^-15 */ #define P2_17 7.629394531250000E-06 /* 2^-17 */ #define P2_19 1.907348632812500E-06 /* 2^-19 */ #define P2_20 9.536743164062500E-07 /* 2^-20 */ #define P2_21 4.768371582031250E-07 /* 2^-21 */ #define P2_23 1.192092895507810E-07 /* 2^-23 */ #define P2_24 5.960464477539063E-08 /* 2^-24 */ #define P2_27 7.450580596923828E-09 /* 2^-27 */ #define P2_29 1.862645149230957E-09 /* 2^-29 */ #define P2_30 9.313225746154785E-10 /* 2^-30 */ #define P2_31 4.656612873077393E-10 /* 2^-31 */ #define P2_32 2.328306436538696E-10 /* 2^-32 */ #define P2_33 1.164153218269348E-10 /* 2^-33 */ #define P2_35 2.910383045673370E-11 /* 2^-35 */ #define P2_38 3.637978807091710E-12 /* 2^-38 */ #define P2_39 1.818989403545856E-12 /* 2^-39 */ #define P2_40 9.094947017729280E-13 /* 2^-40 */ #define P2_43 1.136868377216160E-13 /* 2^-43 */ #define P2_48 3.552713678800501E-15 /* 2^-48 */ #define P2_50 8.881784197001252E-16 /* 2^-50 */ #define P2_55 2.775557561562891E-17 /* 2^-55 */ #ifdef WIN32 #define thread_t HANDLE #define lock_t CRITICAL_SECTION #define initlock(f) InitializeCriticalSection(f) #define lock(f) EnterCriticalSection(f) #define unlock(f) LeaveCriticalSection(f) #define FILEPATHSEP '\\' #else #define thread_t pthread_t #define lock_t pthread_mutex_t #define initlock(f) pthread_mutex_init(f, NULL) #define lock(f) pthread_mutex_lock(f) #define unlock(f) pthread_mutex_unlock(f) #define FILEPATHSEP '/' #endif /* type definitions ----------------------------------------------------------*/ typedef struct { /* time struct */ time_t time; /* time (s) expressed by standard time_t */ double sec; /* fraction of second under 1 s */ } gtime_t; typedef struct { /* observation data record */ gtime_t time; /* receiver sampling time (GPST) */ unsigned char sat, rcv; /* satellite/receiver number */ unsigned char SNR[NFREQ + NEXOBS]; /* signal strength (0.25 dBHz) */ unsigned char LLI[NFREQ + NEXOBS]; /* loss of lock indicator */ unsigned char code[NFREQ + NEXOBS]; /* code indicator (CODE_???) */ double L[NFREQ + NEXOBS]; /* observation data carrier-phase (cycle) */ double P[NFREQ + NEXOBS]; /* observation data pseudorange (m) */ float D[NFREQ + NEXOBS]; /* observation data doppler frequency (Hz) */ } obsd_t; typedef struct { /* observation data */ int n, nmax; /* number of obervation data/allocated */ obsd_t* data; /* observation data records */ } obs_t; typedef struct { /* earth rotation parameter data type */ double mjd; /* mjd (days) */ double xp, yp; /* pole offset (rad) */ double xpr, ypr; /* pole offset rate (rad/day) */ double ut1_utc; /* ut1-utc (s) */ double lod; /* length of day (s/day) */ } erpd_t; typedef struct { /* earth rotation parameter type */ int n, nmax; /* number and max number of data */ erpd_t* data; /* earth rotation parameter data */ } erp_t; typedef struct { /* antenna parameter type */ int sat; /* satellite number (0:receiver) */ char type[MAXANT]; /* antenna type */ char code[MAXANT]; /* serial number or satellite code */ gtime_t ts, te; /* valid time start and end */ double off[NFREQ][3]; /* phase center offset e/n/u or x/y/z (m) */ double var[NFREQ][19]; /* phase center variation (m) */ /* el=90,85,...,0 or nadir=0,1,2,3,... (deg) */ } pcv_t; typedef struct { /* antenna parameters type */ int n, nmax; /* number of data/allocated */ pcv_t* pcv; /* antenna parameters data */ } pcvs_t; typedef struct { /* almanac type */ int sat; /* satellite number */ int svh; /* sv health (0:ok) */ int svconf; /* as and sv config */ int week; /* GPS/QZS: gps week, GAL: galileo week */ gtime_t toa; /* Toa */ /* SV orbit parameters */ double A, e, i0, OMG0, omg, M0, OMGd; double toas; /* Toa (s) in week */ double f0, f1; /* SV clock parameters (af0,af1) */ } alm_t; typedef struct { /* GPS/QZS/GAL broadcast ephemeris type */ int sat; /* satellite number */ int iode, iodc; /* IODE,IODC */ int sva; /* SV accuracy (URA index) */ int svh; /* SV health (0:ok) */ int week; /* GPS/QZS: gps week, GAL: galileo week */ int code; /* GPS/QZS: code on L2, GAL/CMP: data sources */ int flag; /* GPS/QZS: L2 P data flag, CMP: nav type */ gtime_t toe, toc, ttr; /* Toe,Toc,T_trans */ /* SV orbit parameters */ double A, e, i0, OMG0, omg, M0, deln, OMGd, idot; double crc, crs, cuc, cus, cic, cis; double toes; /* Toe (s) in week */ double fit; /* fit interval (h) */ double f0, f1, f2; /* SV clock parameters (af0,af1,af2) */ double tgd[4]; /* group delay parameters */ /* GPS/QZS:tgd[0]=TGD */ /* GAL :tgd[0]=BGD E5a/E1,tgd[1]=BGD E5b/E1 */ /* CMP :tgd[0]=BGD1,tgd[1]=BGD2 */ double Adot, ndot; /* Adot,ndot for CNAV */ double tocs; /* Toc (s) in week */ } eph_t; typedef struct { /* GLONASS broadcast ephemeris type */ int sat; /* satellite number */ int iode; /* IODE (0-6 bit of tb field) */ int frq; /* satellite frequency number */ int svh, sva, age; /* satellite health, accuracy, age of operation */ gtime_t toe; /* epoch of epherides (gpst) */ gtime_t tof; /* message frame time (gpst) */ double pos[3]; /* satellite position (ecef) (m) */ double vel[3]; /* satellite velocity (ecef) (m/s) */ double acc[3]; /* satellite acceleration (ecef) (m/s^2) */ double taun, gamn; /* SV clock bias (s)/relative freq bias */ double dtaun; /* delay between L1 and L2 (s) */ } geph_t; typedef struct { /* precise ephemeris type */ gtime_t time; /* time (GPST) */ int index; /* ephemeris index for multiple files */ double pos[MAXSAT][4]; /* satellite position/clock (ecef) (m|s) */ float std[MAXSAT][4]; /* satellite position/clock std (m|s) */ double vel[MAXSAT][4]; /* satellite velocity/clk-rate (m/s|s/s) */ float vst[MAXSAT][4]; /* satellite velocity/clk-rate std (m/s|s/s) */ float cov[MAXSAT][3]; /* satellite position covariance (m^2) */ float vco[MAXSAT][3]; /* satellite velocity covariance (m^2) */ } peph_t; typedef struct { /* precise clock type */ gtime_t time; /* time (GPST) */ int index; /* clock index for multiple files */ double clk[MAXSAT][1]; /* satellite clock (s) */ float std[MAXSAT][1]; /* satellite clock std (s) */ } pclk_t; typedef struct { /* SBAS ephemeris type */ int sat; /* satellite number */ gtime_t t0; /* reference epoch time (GPST) */ gtime_t tof; /* time of message frame (GPST) */ int sva; /* SV accuracy (URA index) */ int svh; /* SV health (0:ok) */ double pos[3]; /* satellite position (m) (ecef) */ double vel[3]; /* satellite velocity (m/s) (ecef) */ double acc[3]; /* satellite acceleration (m/s^2) (ecef) */ double af0, af1; /* satellite clock-offset/drift (s,s/s) */ } seph_t; typedef struct { /* norad two line element data type */ char name[32]; /* common name */ char alias[32]; /* alias name */ char satno[16]; /* satellilte catalog number */ char satclass; /* classification */ char desig[16]; /* international designator */ gtime_t epoch; /* element set epoch (UTC) */ double ndot; /* 1st derivative of mean motion */ double nddot; /* 2st derivative of mean motion */ double bstar; /* B* drag term */ int etype; /* element set type */ int eleno; /* element number */ double inc; /* orbit inclination (deg) */ double OMG; /* right ascension of ascending node (deg) */ double ecc; /* eccentricity */ double omg; /* argument of perigee (deg) */ double M; /* mean anomaly (deg) */ double n; /* mean motion (rev/day) */ int rev; /* revolution number at epoch */ } tled_t; typedef struct { /* norad two line element type */ int n, nmax; /* number/max number of two line element data */ tled_t* data; /* norad two line element data */ } tle_t; typedef struct { /* TEC grid type */ gtime_t time; /* epoch time (GPST) */ int ndata[3]; /* TEC grid data size {nlat,nlon,nhgt} */ double rb; /* earth radius (km) */ double lats[3]; /* latitude start/interval (deg) */ double lons[3]; /* longitude start/interval (deg) */ double hgts[3]; /* heights start/interval (km) */ double* data; /* TEC grid data (tecu) */ float* rms; /* RMS values (tecu) */ } tec_t; typedef struct { /* stec data type */ gtime_t time; /* time (GPST) */ unsigned char sat; /* satellite number */ unsigned char slip; /* slip flag */ float iono; /* L1 ionosphere delay (m) */ float rate; /* L1 ionosphere rate (m/s) */ float rms; /* rms value (m) */ } stecd_t; typedef struct { /* stec grid type */ double pos[2]; /* latitude/longitude (deg) */ int index[MAXSAT]; /* search index */ int n, nmax; /* number of data */ stecd_t* data; /* stec data */ } stec_t; typedef struct { /* zwd data type */ gtime_t time; /* time (GPST) */ float zwd; /* zenith wet delay (m) */ float rms; /* rms value (m) */ } zwdd_t; typedef struct { /* zwd grid type */ float pos[2]; /* latitude,longitude (rad) */ int n, nmax; /* number of data */ zwdd_t* data; /* zwd data */ } zwd_t; typedef struct { /* SBAS message type */ int week, tow; /* receiption time */ int prn; /* SBAS satellite PRN number */ unsigned char msg[29]; /* SBAS message (226bit) padded by 0 */ } sbsmsg_t; typedef struct { /* SBAS messages type */ int n, nmax; /* number of SBAS messages/allocated */ sbsmsg_t* msgs; /* SBAS messages */ } sbs_t; typedef struct { /* SBAS fast correction type */ gtime_t t0; /* time of applicability (TOF) */ double prc; /* pseudorange correction (PRC) (m) */ double rrc; /* range-rate correction (RRC) (m/s) */ double dt; /* range-rate correction delta-time (s) */ int iodf; /* IODF (issue of date fast corr) */ short udre; /* UDRE+1 */ short ai; /* degradation factor indicator */ } sbsfcorr_t; typedef struct { /* SBAS long term satellite error correction type */ gtime_t t0; /* correction time */ int iode; /* IODE (issue of date ephemeris) */ double dpos[3]; /* delta position (m) (ecef) */ double dvel[3]; /* delta velocity (m/s) (ecef) */ double daf0, daf1; /* delta clock-offset/drift (s,s/s) */ } sbslcorr_t; typedef struct { /* SBAS satellite correction type */ int sat; /* satellite number */ sbsfcorr_t fcorr; /* fast correction */ sbslcorr_t lcorr; /* long term correction */ } sbssatp_t; typedef struct { /* SBAS satellite corrections type */ int iodp; /* IODP (issue of date mask) */ int nsat; /* number of satellites */ int tlat; /* system latency (s) */ sbssatp_t sat[MAXSAT]; /* satellite correction */ } sbssat_t; typedef struct { /* SBAS ionospheric correction type */ gtime_t t0; /* correction time */ short lat, lon; /* latitude/longitude (deg) */ short give; /* GIVI+1 */ float delay; /* vertical delay estimate (m) */ } sbsigp_t; typedef struct { /* IGP band type */ short x; /* longitude/latitude (deg) */ const short* y; /* latitudes/longitudes (deg) */ unsigned char bits; /* IGP mask start bit */ unsigned char bite; /* IGP mask end bit */ } sbsigpband_t; typedef struct { /* SBAS ionospheric corrections type */ int iodi; /* IODI (issue of date ionos corr) */ int nigp; /* number of igps */ sbsigp_t igp[MAXNIGP]; /* ionospheric correction */ } sbsion_t; typedef struct { /* DGPS/GNSS correction type */ gtime_t t0; /* correction time */ double prc; /* pseudorange correction (PRC) (m) */ double rrc; /* range rate correction (RRC) (m/s) */ int iod; /* issue of data (IOD) */ double udre; /* UDRE */ } dgps_t; typedef struct { /* SSR correction type */ gtime_t t0[5]; /* epoch time (GPST) {eph,clk,hrclk,ura,bias} */ double udi[5]; /* SSR update interval (s) */ int iod[5]; /* iod ssr {eph,clk,hrclk,ura,bias} */ int iode; /* issue of data */ int iodcrc; /* issue of data crc for beidou/sbas */ int ura; /* URA indicator */ int refd; /* sat ref datum (0:ITRF,1:regional) */ double deph[3]; /* delta orbit {radial,along,cross} (m) */ double ddeph[3]; /* dot delta orbit {radial,along,cross} (m/s) */ double dclk[3]; /* delta clock {c0,c1,c2} (m,m/s,m/s^2) */ double hrclk; /* high-rate clock corection (m) */ float cbias[MAXCODE]; /* code biases (m) */ unsigned char update; /* update flag (0:no update,1:update) */ } ssr_t; typedef struct { /* QZSS LEX message type */ int prn; /* satellite PRN number */ int type; /* message type */ int alert; /* alert flag */ unsigned char stat; /* signal tracking status */ unsigned char snr; /* signal C/N0 (0.25 dBHz) */ unsigned int ttt; /* tracking time (ms) */ unsigned char msg[212]; /* LEX message data part 1695 bits */ } lexmsg_t; typedef struct { /* QZSS LEX messages type */ int n, nmax; /* number of LEX messages and allocated */ lexmsg_t* msgs; /* LEX messages */ } lex_t; typedef struct { /* QZSS LEX ephemeris type */ gtime_t toe; /* epoch time (GPST) */ gtime_t tof; /* message frame time (GPST) */ int sat; /* satellite number */ unsigned char health; /* signal health (L1,L2,L1C,L5,LEX) */ unsigned char ura; /* URA index */ double pos[3]; /* satellite position (m) */ double vel[3]; /* satellite velocity (m/s) */ double acc[3]; /* satellite acceleration (m/s2) */ double jerk[3]; /* satellite jerk (m/s3) */ double af0, af1; /* satellite clock bias and drift (s,s/s) */ double tgd; /* TGD */ double isc[8]; /* ISC */ } lexeph_t; typedef struct { /* QZSS LEX ionosphere correction type */ gtime_t t0; /* epoch time (GPST) */ double tspan; /* valid time span (s) */ double pos0[2]; /* reference position {lat,lon} (rad) */ double coef[3][2]; /* coefficients lat x lon (3 x 2) */ } lexion_t; typedef struct { /* navigation data type */ int n, nmax; /* number of broadcast ephemeris */ int ng, ngmax; /* number of glonass ephemeris */ int ns, nsmax; /* number of sbas ephemeris */ int ne, nemax; /* number of precise ephemeris */ int nc, ncmax; /* number of precise clock */ int na, namax; /* number of almanac data */ int nt, ntmax; /* number of tec grid data */ int nn, nnmax; /* number of stec grid data */ eph_t* eph; /* GPS/QZS/GAL ephemeris */ geph_t* geph; /* GLONASS ephemeris */ seph_t* seph; /* SBAS ephemeris */ peph_t* peph; /* precise ephemeris */ pclk_t* pclk; /* precise clock */ alm_t* alm; /* almanac data */ tec_t* tec; /* tec grid data */ stec_t* stec; /* stec grid data */ erp_t erp; /* earth rotation parameters */ double utc_gps[4]; /* GPS delta-UTC parameters {A0,A1,T,W} */ double utc_glo[4]; /* GLONASS UTC GPS time parameters */ double utc_gal[4]; /* Galileo UTC GPS time parameters */ double utc_qzs[4]; /* QZS UTC GPS time parameters */ double utc_cmp[4]; /* BeiDou UTC parameters */ double utc_sbs[4]; /* SBAS UTC parameters */ double ion_gps[8]; /* GPS iono model parameters {a0,a1,a2,a3,b0,b1,b2,b3} */ double ion_gal[4]; /* Galileo iono model parameters {ai0,ai1,ai2,0} */ double ion_qzs[8]; /* QZSS iono model parameters {a0,a1,a2,a3,b0,b1,b2,b3} */ double ion_cmp[8]; /* BeiDou iono model parameters {a0,a1,a2,a3,b0,b1,b2,b3} */ int leaps; /* leap seconds (s) */ double lam[MAXSAT][NFREQ]; /* carrier wave lengths (m) */ double cbias[MAXSAT][3]; /* code bias (0:p1-p2,1:p1-c1,2:p2-c2) (m) */ double wlbias[MAXSAT]; /* wide-lane bias (cycle) */ double glo_cpbias[4]; /* glonass code-phase bias {1C,1P,2C,2P} (m) */ char glo_fcn[MAXPRNGLO + 1]; /* glonass frequency channel number + 8 */ pcv_t pcvs[MAXSAT]; /* satellite antenna pcv */ sbssat_t sbssat; /* SBAS satellite corrections */ sbsion_t sbsion[MAXBAND + 1]; /* SBAS ionosphere corrections */ dgps_t dgps[MAXSAT]; /* DGPS corrections */ ssr_t ssr[MAXSAT]; /* SSR corrections */ lexeph_t lexeph[MAXSAT]; /* LEX ephemeris */ lexion_t lexion; /* LEX ionosphere correction */ } nav_t; typedef struct { /* station parameter type */ char name[MAXANT]; /* marker name */ char marker[MAXANT]; /* marker number */ char antdes[MAXANT]; /* antenna descriptor */ char antsno[MAXANT]; /* antenna serial number */ char rectype[MAXANT]; /* receiver type descriptor */ char recver[MAXANT]; /* receiver firmware version */ char recsno[MAXANT]; /* receiver serial number */ int antsetup; /* antenna setup id */ int itrf; /* ITRF realization year */ int deltype; /* antenna delta type (0:enu,1:xyz) */ double pos[3]; /* station position (ecef) (m) */ double del[3]; /* antenna position delta (e/n/u or x/y/z) (m) */ double hgt; /* antenna height (m) */ } sta_t; typedef struct { /* solution type */ gtime_t time; /* time (GPST) */ double rr[6]; /* position/velocity (m|m/s) */ /* {x,y,z,vx,vy,vz} or {e,n,u,ve,vn,vu} */ float qr[6]; /* position variance/covariance (m^2) */ /* {c_xx,c_yy,c_zz,c_xy,c_yz,c_zx} or */ /* {c_ee,c_nn,c_uu,c_en,c_nu,c_ue} */ double dtr[6]; /* receiver clock bias to time systems (s) */ unsigned char type; /* type (0:xyz-ecef,1:enu-baseline) */ unsigned char stat; /* solution status (SOLQ_???) */ unsigned char ns; /* number of valid satellites */ float age; /* age of differential (s) */ float ratio; /* AR ratio factor for valiation */ } sol_t; typedef struct { /* solution buffer type */ int n, nmax; /* number of solution/max number of buffer */ int cyclic; /* cyclic buffer flag */ int start, end; /* start/end index */ gtime_t time; /* current solution time */ sol_t* data; /* solution data */ double rb[3]; /* reference position {x,y,z} (ecef) (m) */ unsigned char buff[MAXSOLMSG + 1]; /* message buffer */ int nb; /* number of byte in message buffer */ } solbuf_t; typedef struct { /* solution status type */ gtime_t time; /* time (GPST) */ unsigned char sat; /* satellite number */ unsigned char frq; /* frequency (1:L1,2:L2,...) */ float az, el; /* azimuth/elevation angle (rad) */ float resp; /* pseudorange residual (m) */ float resc; /* carrier-phase residual (m) */ unsigned char flag; /* flags: (vsat<<5)+(slip<<3)+fix */ unsigned char snr; /* signal strength (0.25 dBHz) */ unsigned short lock; /* lock counter */ unsigned short outc; /* outage counter */ unsigned short slipc; /* slip counter */ unsigned short rejc; /* reject counter */ } solstat_t; typedef struct { /* solution status buffer type */ int n, nmax; /* number of solution/max number of buffer */ solstat_t* data; /* solution status data */ } solstatbuf_t; typedef struct { /* RTCM control struct type */ int staid; /* station id */ int stah; /* station health */ int seqno; /* sequence number for rtcm 2 or iods msm */ int outtype; /* output message type */ gtime_t time; /* message time */ gtime_t time_s; /* message start time */ obs_t obs; /* observation data (uncorrected) */ nav_t nav; /* satellite ephemerides */ sta_t sta; /* station parameters */ dgps_t* dgps; /* output of dgps corrections */ ssr_t ssr[MAXSAT]; /* output of ssr corrections */ char msg[128]; /* special message */ char msgtype[256]; /* last message type */ char msmtype[6][128]; /* msm signal types */ int obsflag; /* obs data complete flag (1:ok,0:not complete) */ int ephsat; /* update satellite of ephemeris */ double cp[MAXSAT][NFREQ + NEXOBS]; /* carrier-phase measurement */ unsigned char lock[MAXSAT][NFREQ + NEXOBS]; /* lock time */ unsigned char loss[MAXSAT][NFREQ + NEXOBS]; /* loss of lock count */ gtime_t lltime[MAXSAT][NFREQ + NEXOBS]; /* last lock time */ int nbyte; /* number of bytes in message buffer */ int nbit; /* number of bits in word buffer */ int len; /* message length (bytes) */ unsigned char buff[1200]; /* message buffer */ unsigned int word; /* word buffer for rtcm 2 */ unsigned int nmsg2[100]; /* message count of RTCM 2 (1-99:1-99,0:other) */ unsigned int nmsg3[300]; /* message count of RTCM 3 (1-299:1001-1299,0:ohter) */ char opt[256]; /* RTCM dependent options */ int message_type; } rtcm_t; typedef struct { /* rinex control struct type */ gtime_t time; /* message time */ double ver; /* rinex version */ char type; /* rinex file type ('O','N',...) */ int sys; /* navigation system */ int tsys; /* time system */ char tobs[6][MAXOBSTYPE][4]; /* rinex obs types */ obs_t obs; /* observation data */ nav_t nav; /* navigation data */ sta_t sta; /* station info */ int ephsat; /* ephemeris satellite number */ char opt[256]; /* rinex dependent options */ } rnxctr_t; typedef struct { /* download url type */ char type[32]; /* data type */ char path[1024]; /* url path */ char dir[1024]; /* local directory */ double tint; /* time interval (s) */ } url_t; typedef struct { /* option type */ char* name; /* option name */ int format; /* option format (0:int,1:double,2:string,3:enum) */ void* var; /* pointer to option variable */ char* comment; /* option comment/enum labels/unit */ } opt_t; typedef struct { /* extended receiver error model */ int ena[4]; /* model enabled */ double cerr[4][NFREQ * 2]; /* code errors (m) */ double perr[4][NFREQ * 2]; /* carrier-phase errors (m) */ double gpsglob[NFREQ]; /* gps-glonass h/w bias (m) */ double gloicb[NFREQ]; /* glonass interchannel bias (m/fn) */ } exterr_t; typedef struct { /* SNR mask type */ int ena[2]; /* enable flag {rover,base} */ double mask[NFREQ][9]; /* mask (dBHz) at 5,10,...85 deg */ } snrmask_t; typedef struct { /* processing options type */ int mode; /* positioning mode (PMODE_???) */ int soltype; /* solution type (0:forward,1:backward,2:combined) */ int nf; /* number of frequencies (1:L1,2:L1+L2,3:L1+L2+L5) */ int navsys; /* navigation system */ double elmin; /* elevation mask angle (rad) */ snrmask_t snrmask; /* SNR mask */ int sateph; /* satellite ephemeris/clock (EPHOPT_???) */ int modear; /* AR mode (0:off,1:continuous,2:instantaneous,3:fix and hold,4:ppp-ar) */ int glomodear; /* GLONASS AR mode (0:off,1:on,2:auto cal,3:ext cal) */ int bdsmodear; /* BeiDou AR mode (0:off,1:on) */ int maxout; /* obs outage count to reset bias */ int minlock; /* min lock count to fix ambiguity */ int minfix; /* min fix count to hold ambiguity */ int ionoopt; /* ionosphere option (IONOOPT_???) */ int tropopt; /* troposphere option (TROPOPT_???) */ int dynamics; /* dynamics model (0:none,1:velociy,2:accel) */ int tidecorr; /* earth tide correction (0:off,1:solid,2:solid+otl+pole) */ int niter; /* number of filter iteration */ int codesmooth; /* code smoothing window size (0:none) */ int intpref; /* interpolate reference obs (for post mission) */ int sbascorr; /* SBAS correction options */ int sbassatsel; /* SBAS satellite selection (0:all) */ int rovpos; /* rover position for fixed mode */ int refpos; /* base position for relative mode */ /* (0:pos in prcopt, 1:average of single pos, */ /* 2:read from file, 3:rinex header, 4:rtcm pos) */ double eratio[NFREQ]; /* code/phase error ratio */ double err[5]; /* measurement error factor */ /* [0]:reserved */ /* [1-3]:error factor a/b/c of phase (m) */ /* [4]:doppler frequency (hz) */ double std[3]; /* initial-state std [0]bias,[1]iono [2]trop */ double prn[5]; /* process-noise std [0]bias,[1]iono [2]trop [3]acch [4]accv */ double sclkstab; /* satellite clock stability (sec/sec) */ double thresar[4]; /* AR validation threshold */ double elmaskar; /* elevation mask of AR for rising satellite (deg) */ double elmaskhold; /* elevation mask to hold ambiguity (deg) */ double thresslip; /* slip threshold of geometry-free phase (m) */ double maxtdiff; /* max difference of time (sec) */ double maxinno; /* reject threshold of innovation (m) */ double maxgdop; /* reject threshold of gdop */ double baseline[2]; /* baseline length constraint {const,sigma} (m) */ double ru[3]; /* rover position for fixed mode {x,y,z} (ecef) (m) */ double rb[3]; /* base position for relative mode {x,y,z} (ecef) (m) */ char anttype[2][MAXANT]; /* antenna types {rover,base} */ double antdel[2][3]; /* antenna delta {{rov_e,rov_n,rov_u},{ref_e,ref_n,ref_u}} */ pcv_t pcvr[2]; /* receiver antenna parameters {rov,base} */ unsigned char exsats[MAXSAT]; /* excluded satellites (1:excluded,2:included) */ char rnxopt[2][256]; /* rinex options {rover,base} */ int posopt[6]; /* positioning options */ int syncsol; /* solution sync mode (0:off,1:on) */ double odisp[2][6 * 11]; /* ocean tide loading parameters {rov,base} */ exterr_t exterr; /* extended receiver error model */ } prcopt_t; typedef struct { /* solution options type */ int posf; /* solution format (SOLF_???) */ int times; /* time system (TIMES_???) */ int timef; /* time format (0:sssss.s,1:yyyy/mm/dd hh:mm:ss.s) */ int timeu; /* time digits under decimal point */ int degf; /* latitude/longitude format (0:ddd.ddd,1:ddd mm ss) */ int outhead; /* output header (0:no,1:yes) */ int outopt; /* output processing options (0:no,1:yes) */ int datum; /* datum (0:WGS84,1:Tokyo) */ int height; /* height (0:ellipsoidal,1:geodetic) */ int geoid; /* geoid model (0:EGM96,1:JGD2000) */ int solstatic; /* solution of static mode (0:all,1:single) */ int sstat; /* solution statistics level (0:off,1:states,2:residuals) */ int trace; /* debug trace level (0:off,1-5:debug) */ double nmeaintv[2]; /* nmea output interval (s) (<0:no,0:all) */ /* nmeaintv[0]:gprmc,gpgga,nmeaintv[1]:gpgsv */ char sep[64]; /* field separator */ char prog[64]; /* program name */ } solopt_t; typedef struct { /* file options type */ char satantp[MAXSTRPATH]; /* satellite antenna parameters file */ char rcvantp[MAXSTRPATH]; /* receiver antenna parameters file */ char stapos[MAXSTRPATH]; /* station positions file */ char geoid[MAXSTRPATH]; /* external geoid data file */ char iono[MAXSTRPATH]; /* ionosphere data file */ char dcb[MAXSTRPATH]; /* dcb data file */ char eop[MAXSTRPATH]; /* eop data file */ char blq[MAXSTRPATH]; /* ocean tide loading blq file */ char tempdir[MAXSTRPATH]; /* ftp/http temporaly directory */ char geexe[MAXSTRPATH]; /* google earth exec file */ char solstat[MAXSTRPATH]; /* solution statistics file */ char trace[MAXSTRPATH]; /* debug trace file */ } filopt_t; typedef struct { /* RINEX options type */ gtime_t ts, te; /* time start/end */ double tint; /* time interval (s) */ double tunit; /* time unit for multiple-session (s) */ double rnxver; /* RINEX version */ int navsys; /* navigation system */ int obstype; /* observation type */ int freqtype; /* frequency type */ char mask[6][64]; /* code mask {GPS,GLO,GAL,QZS,SBS,CMP} */ char staid[32]; /* station id for rinex file name */ char prog[32]; /* program */ char runby[32]; /* run-by */ char marker[64]; /* marker name */ char markerno[32]; /* marker number */ char markertype[32]; /* marker type (ver.3) */ char name[2][32]; /* observer/agency */ char rec[3][32]; /* receiver #/type/vers */ char ant[3][32]; /* antenna #/type */ double apppos[3]; /* approx position x/y/z */ double antdel[3]; /* antenna delta h/e/n */ char comment[MAXCOMMENT][64]; /* comments */ char rcvopt[256]; /* receiver dependent options */ unsigned char exsats[MAXSAT]; /* excluded satellites */ int scanobs; /* scan obs types */ int outiono; /* output iono correction */ int outtime; /* output time system correction */ int outleaps; /* output leap seconds */ int autopos; /* auto approx position */ gtime_t tstart; /* first obs time */ gtime_t tend; /* last obs time */ gtime_t trtcm; /* approx log start time for rtcm */ char tobs[6][MAXOBSTYPE][4]; /* obs types {GPS,GLO,GAL,QZS,SBS,CMP} */ int nobs[6]; /* number of obs types {GPS,GLO,GAL,QZS,SBS,CMP} */ } rnxopt_t; typedef struct { /* satellite status type */ unsigned char sys; /* navigation system */ unsigned char vs; /* valid satellite flag single */ double azel[2]; /* azimuth/elevation angles {az,el} (rad) */ double resp[NFREQ]; /* residuals of pseudorange (m) */ double resc[NFREQ]; /* residuals of carrier-phase (m) */ unsigned char vsat[NFREQ]; /* valid satellite flag */ unsigned char snr[NFREQ]; /* signal strength (0.25 dBHz) */ unsigned char fix[NFREQ]; /* ambiguity fix flag (1:fix,2:float,3:hold) */ unsigned char slip[NFREQ]; /* cycle-slip flag */ unsigned int lock[NFREQ]; /* lock counter of phase */ unsigned int outc[NFREQ]; /* obs outage counter of phase */ unsigned int slipc[NFREQ]; /* cycle-slip counter */ unsigned int rejc[NFREQ]; /* reject counter */ double gf; /* geometry-free phase L1-L2 (m) */ double gf2; /* geometry-free phase L1-L5 (m) */ double phw; /* phase windup (cycle) */ gtime_t pt[2][NFREQ]; /* previous carrier-phase time */ double ph[2][NFREQ]; /* previous carrier-phase observable (cycle) */ } ssat_t; typedef struct { /* ambiguity control type */ gtime_t epoch[4]; /* last epoch */ int fixcnt; /* fix counter */ char flags[MAXSAT]; /* fix flags */ double n[4]; /* number of epochs */ double LC[4]; /* linear combination average */ double LCv[4]; /* linear combination variance */ } ambc_t; typedef struct { /* RTK control/result type */ sol_t sol; /* RTK solution */ double rb[6]; /* base position/velocity (ecef) (m|m/s) */ int nx, na; /* number of float states/fixed states */ double tt; /* time difference between current and previous (s) */ double *x, *P; /* float states and their covariance */ double *xa, *Pa; /* fixed states and their covariance */ int nfix; /* number of continuous fixes of ambiguity */ ambc_t ambc[MAXSAT]; /* ambibuity control */ ssat_t ssat[MAXSAT]; /* satellite status */ int neb; /* bytes in error message buffer */ char errbuf[MAXERRMSG]; /* error message buffer */ prcopt_t opt; /* processing options */ } rtk_t; typedef struct { /* receiver raw data control type */ gtime_t time; /* message time */ gtime_t tobs; /* observation data time */ obs_t obs; /* observation data */ obs_t obuf; /* observation data buffer */ nav_t nav; /* satellite ephemerides */ sta_t sta; /* station parameters */ int ephsat; /* sat number of update ephemeris (0:no satellite) */ sbsmsg_t sbsmsg; /* SBAS message */ char msgtype[256]; /* last message type */ unsigned char subfrm[MAXSAT][380]; /* subframe buffer */ lexmsg_t lexmsg; /* LEX message */ double lockt[MAXSAT][NFREQ + NEXOBS]; /* lock time (s) */ double icpp[MAXSAT], off[MAXSAT], icpc; /* carrier params for ss2 */ double prCA[MAXSAT], dpCA[MAXSAT]; /* L1/CA pseudrange/doppler for javad */ unsigned char halfc[MAXSAT][NFREQ + NEXOBS]; /* half-cycle add flag */ char freqn[MAXOBS]; /* frequency number for javad */ int nbyte; /* number of bytes in message buffer */ int len; /* message length (bytes) */ int iod; /* issue of data */ int tod; /* time of day (ms) */ int tbase; /* time base (0:gpst,1:utc(usno),2:glonass,3:utc(su) */ int flag; /* general purpose flag */ int outtype; /* output message type */ unsigned char buff[MAXRAWLEN]; /* message buffer */ char opt[256]; /* receiver dependent options */ double receive_time; /* RT17: Reiceve time of week for week rollover detection */ unsigned int plen; /* RT17: Total size of packet to be read */ unsigned int pbyte; /* RT17: How many packet bytes have been read so far */ unsigned int page; /* RT17: Last page number */ unsigned int reply; /* RT17: Current reply number */ int week; /* RT17: week number */ unsigned char pbuff[255 + 4 + 2]; /* RT17: Packet buffer */ } raw_t; typedef struct { /* stream type */ int type; /* type (STR_???) */ int mode; /* mode (STR_MODE_?) */ int state; /* state (-1:error,0:close,1:open) */ unsigned int inb, inr; /* input bytes/rate */ unsigned int outb, outr; /* output bytes/rate */ unsigned int tick, tact; /* tick/active tick */ unsigned int inbt, outbt; /* input/output bytes at tick */ lock_t lock; /* lock flag */ void* port; /* type dependent port control struct */ char path[MAXSTRPATH]; /* stream path */ char msg[MAXSTRMSG]; /* stream message */ } stream_t; typedef struct { /* stream converter type */ int itype, otype; /* input and output stream type */ int nmsg; /* number of output messages */ int msgs[32]; /* output message types */ double tint[32]; /* output message intervals (s) */ unsigned int tick[32]; /* cycle tick of output message */ int ephsat[32]; /* satellites of output ephemeris */ int stasel; /* station info selection (0:remote,1:local) */ rtcm_t rtcm; /* rtcm input data buffer */ raw_t raw; /* raw input data buffer */ rtcm_t out; /* rtcm output data buffer */ } strconv_t; typedef struct { /* stream server type */ int state; /* server state (0:stop,1:running) */ int cycle; /* server cycle (ms) */ int buffsize; /* input/monitor buffer size (bytes) */ int nmeacycle; /* NMEA request cycle (ms) (0:no) */ int nstr; /* number of streams (1 input + (nstr-1) outputs */ int npb; /* data length in peek buffer (bytes) */ double nmeapos[3]; /* NMEA request position (ecef) (m) */ unsigned char* buff; /* input buffers */ unsigned char* pbuf; /* peek buffer */ unsigned int tick; /* start tick */ stream_t stream[16]; /* input/output streams */ strconv_t* conv[16]; /* stream converter */ thread_t thread; /* server thread */ lock_t lock; /* lock flag */ } strsvr_t; typedef struct { /* RTK server type */ int state; /* server state (0:stop,1:running) */ int cycle; /* processing cycle (ms) */ int nmeacycle; /* NMEA request cycle (ms) (0:no req) */ int nmeareq; /* NMEA request (0:no,1:nmeapos,2:single sol) */ double nmeapos[3]; /* NMEA request position (ecef) (m) */ int buffsize; /* input buffer size (bytes) */ int format[3]; /* input format {rov,base,corr} */ solopt_t solopt[2]; /* output solution options {sol1,sol2} */ int navsel; /* ephemeris select (0:all,1:rover,2:base,3:corr) */ int nsbs; /* number of sbas message */ int nsol; /* number of solution buffer */ rtk_t rtk; /* RTK control/result struct */ int nb[3]; /* bytes in input buffers {rov,base} */ int nsb[2]; /* bytes in soulution buffers */ int npb[3]; /* bytes in input peek buffers */ unsigned char* buff[3]; /* input buffers {rov,base,corr} */ unsigned char* sbuf[2]; /* output buffers {sol1,sol2} */ unsigned char* pbuf[3]; /* peek buffers {rov,base,corr} */ sol_t solbuf[MAXSOLBUF]; /* solution buffer */ unsigned int nmsg[3][10]; /* input message counts */ raw_t raw[3]; /* receiver raw control {rov,base,corr} */ rtcm_t rtcm[3]; /* RTCM control {rov,base,corr} */ gtime_t ftime[3]; /* download time {rov,base,corr} */ char files[3][MAXSTRPATH]; /* download paths {rov,base,corr} */ obs_t obs[3][MAXOBSBUF]; /* observation data {rov,base,corr} */ nav_t nav; /* navigation data */ sbsmsg_t sbsmsg[MAXSBSMSG]; /* SBAS message buffer */ stream_t stream[8]; /* streams {rov,base,corr,sol1,sol2,logr,logb,logc} */ stream_t* moni; /* monitor stream */ unsigned int tick; /* start tick */ thread_t thread; /* server thread */ int cputime; /* CPU time (ms) for a processing cycle */ int prcout; /* missing observation data count */ lock_t lock; /* lock flag */ } rtksvr_t; /* global variables ----------------------------------------------------------*/ extern const double chisqr[]; /* chi-sqr(n) table (alpha=0.001) */ extern const double lam_carr[]; /* carrier wave length (m) {L1,L2,...} */ extern const prcopt_t prcopt_default; /* default positioning options */ extern const solopt_t solopt_default; /* default solution output options */ extern const sbsigpband_t igpband1[][8]; /* SBAS IGP band 0-8 */ extern const sbsigpband_t igpband2[][5]; /* SBAS IGP band 9-10 */ extern const char* formatstrs[]; /* stream format strings */ extern opt_t sysopts[]; /* system options table */ /* satellites, systems, codes functions --------------------------------------*/ extern int satno(int sys, int prn); extern int satsys(int sat, int* prn); extern int satid2no(const char* id); extern void satno2id(int sat, char* id); extern unsigned char obs2code(const char* obs, int* freq); extern char* code2obs(unsigned char code, int* freq); extern int satexclude(int sat, int svh, const prcopt_t* opt); extern int testsnr(int base, int freq, double el, double snr, const snrmask_t* mask); extern void setcodepri(int sys, int freq, const char* pri); extern int getcodepri(int sys, unsigned char code, const char* opt); /* matrix and vector functions -----------------------------------------------*/ extern double* mat(int n, int m); extern int* imat(int n, int m); extern double* zeros(int n, int m); extern double* eye(int n); extern double dot(const double* a, const double* b, int n); extern double norm(const double* a, int n); extern void cross3(const double* a, const double* b, double* c); extern int normv3(const double* a, double* b); extern void matcpy(double* A, const double* B, int n, int m); extern void matmul(const char* tr, int n, int k, int m, double alpha, const double* A, const double* B, double beta, double* C); extern int matinv(double* A, int n); extern int solve(const char* tr, const double* A, const double* Y, int n, int m, double* X); extern int lsq(const double* A, const double* y, int n, int m, double* x, double* Q); extern int filter(double* x, double* P, const double* H, const double* v, const double* R, int n, int m); extern int smoother(const double* xf, const double* Qf, const double* xb, const double* Qb, int n, double* xs, double* Qs); extern void matprint(const double* A, int n, int m, int p, int q); extern void matfprint(const double* A, int n, int m, int p, int q, FILE* fp); /* time and string functions -------------------------------------------------*/ extern double str2num(const char* s, int i, int n); extern int str2time(const char* s, int i, int n, gtime_t* t); extern void time2str(gtime_t t, char* str, int n); extern gtime_t epoch2time(const double* ep); extern void time2epoch(gtime_t t, double* ep); extern gtime_t gpst2time(int week, double sec); extern double time2gpst(gtime_t t, int* week); extern gtime_t gst2time(int week, double sec); extern double time2gst(gtime_t t, int* week); extern gtime_t bdt2time(int week, double sec); extern double time2bdt(gtime_t t, int* week); extern char* time_str(gtime_t t, int n); extern gtime_t timeadd(gtime_t t, double sec); extern double timediff(gtime_t t1, gtime_t t2); extern gtime_t gpst2utc(gtime_t t); extern gtime_t utc2gpst(gtime_t t); extern gtime_t gpst2bdt(gtime_t t); extern gtime_t bdt2gpst(gtime_t t); extern gtime_t timeget(void); extern void timeset(gtime_t t); extern double time2doy(gtime_t t); extern double utc2gmst(gtime_t t, double ut1_utc); extern int read_leaps(const char* file); extern int adjgpsweek(int week); extern unsigned int tickget(void); extern void sleepms(int ms); extern int reppath(const char* path, char* rpath, gtime_t time, const char* rov, const char* base); extern int reppaths(const char* path, char* rpaths[], int nmax, gtime_t ts, gtime_t te, const char* rov, const char* base); /* coordinates transformation ------------------------------------------------*/ extern void ecef2pos(const double* r, double* pos); extern void pos2ecef(const double* pos, double* r); extern void ecef2enu(const double* pos, const double* r, double* e); extern void enu2ecef(const double* pos, const double* e, double* r); extern void covenu(const double* pos, const double* P, double* Q); extern void covecef(const double* pos, const double* Q, double* P); extern void xyz2enu(const double* pos, double* E); extern void eci2ecef(gtime_t tutc, const double* erpv, double* U, double* gmst); extern void deg2dms(double deg, double* dms); extern double dms2deg(const double* dms); /* input and output functions ------------------------------------------------*/ extern void readpos(const char* file, const char* rcv, double* pos); extern int sortobs(obs_t* obs); extern void uniqnav(nav_t* nav); extern int screent(gtime_t time, gtime_t ts, gtime_t te, double tint); extern int readnav(const char* file, nav_t* nav); extern int savenav(const char* file, const nav_t* nav); extern void freeobs(obs_t* obs); extern void freenav(nav_t* nav, int opt); extern int readblq(const char* file, const char* sta, double* odisp); extern int readerp(const char* file, erp_t* erp); extern int geterp(const erp_t* erp, gtime_t time, double* val); /* debug trace functions -----------------------------------------------------*/ extern void traceopen(const char* file); extern void traceclose(void); extern void tracelevel(int level); extern void trace(int level, const char* format, ...); extern void tracet(int level, const char* format, ...); extern void tracemat(int level, const double* A, int n, int m, int p, int q); extern void traceobs(int level, const obsd_t* obs, int n); extern void tracenav(int level, const nav_t* nav); extern void tracegnav(int level, const nav_t* nav); extern void tracehnav(int level, const nav_t* nav); extern void tracepeph(int level, const nav_t* nav); extern void tracepclk(int level, const nav_t* nav); extern void traceb(int level, const unsigned char* p, int n); /* platform dependent functions ----------------------------------------------*/ extern int execcmd(const char* cmd); extern int expath(const char* path, char* paths[], int nmax); extern void createdir(const char* path); /* positioning models --------------------------------------------------------*/ extern double satwavelen(int sat, int frq, const nav_t* nav); extern double satazel(const double* pos, const double* e, double* azel); extern double geodist(const double* rs, const double* rr, double* e); extern void dops(int ns, const double* azel, double elmin, double* dop); extern void csmooth(obs_t* obs, int ns); /* atmosphere models ---------------------------------------------------------*/ extern double ionmodel(gtime_t t, const double* ion, const double* pos, const double* azel); extern double ionmapf(const double* pos, const double* azel); extern double ionppp(const double* pos, const double* azel, double re, double hion, double* pppos); extern double tropmodel(gtime_t time, const double* pos, const double* azel, double humi); extern double tropmapf(gtime_t time, const double* pos, const double* azel, double* mapfw); extern int iontec(gtime_t time, const nav_t* nav, const double* pos, const double* azel, int opt, double* delay, double* var); extern void readtec(const char* file, nav_t* nav, int opt); extern int ionocorr(gtime_t time, const nav_t* nav, int sat, const double* pos, const double* azel, int ionoopt, double* ion, double* var); extern int tropcorr(gtime_t time, const nav_t* nav, const double* pos, const double* azel, int tropopt, double* trp, double* var); extern void stec_read(const char* file, nav_t* nav); extern int stec_grid(const nav_t* nav, const double* pos, int nmax, int* index, double* dist); extern int stec_data(stec_t* stec, gtime_t time, int sat, double* iono, double* rate, double* rms, int* slip); extern int stec_ion(gtime_t time, const nav_t* nav, int sat, const double* pos, const double* azel, double* iono, double* rate, double* var, int* brk); extern void stec_free(nav_t* nav); /* antenna models ------------------------------------------------------------*/ extern int readpcv(const char* file, pcvs_t* pcvs); extern pcv_t* searchpcv(int sat, const char* type, gtime_t time, const pcvs_t* pcvs); extern void antmodel(const pcv_t* pcv, const double* del, const double* azel, int opt, double* dant); extern void antmodel_s(const pcv_t* pcv, double nadir, double* dant); /* earth tide models ---------------------------------------------------------*/ extern void sunmoonpos(gtime_t tutc, const double* erpv, double* rsun, double* rmoon, double* gmst); extern void tidedisp(gtime_t tutc, const double* rr, int opt, const erp_t* erp, const double* odisp, double* dr); /* geiod models --------------------------------------------------------------*/ extern int opengeoid(int model, const char* file); extern void closegeoid(void); extern double geoidh(const double* pos); /* datum transformation ------------------------------------------------------*/ extern int loaddatump(const char* file); extern int tokyo2jgd(double* pos); extern int jgd2tokyo(double* pos); /* rinex functions -----------------------------------------------------------*/ extern int readrnx(const char* file, int rcv, const char* opt, obs_t* obs, nav_t* nav, sta_t* sta); extern int readrnxt(const char* file, int rcv, gtime_t ts, gtime_t te, double tint, const char* opt, obs_t* obs, nav_t* nav, sta_t* sta); extern int readrnxc(const char* file, nav_t* nav); extern int outrnxobsh(FILE* fp, const rnxopt_t* opt, const nav_t* nav); extern int outrnxobsb(FILE* fp, const rnxopt_t* opt, const obsd_t* obs, int n, int epflag); extern int outrnxnavh(FILE* fp, const rnxopt_t* opt, const nav_t* nav); extern int outrnxgnavh(FILE* fp, const rnxopt_t* opt, const nav_t* nav); extern int outrnxhnavh(FILE* fp, const rnxopt_t* opt, const nav_t* nav); extern int outrnxlnavh(FILE* fp, const rnxopt_t* opt, const nav_t* nav); extern int outrnxqnavh(FILE* fp, const rnxopt_t* opt, const nav_t* nav); extern int outrnxcnavh(FILE* fp, const rnxopt_t* opt, const nav_t* nav); extern int outrnxnavb(FILE* fp, const rnxopt_t* opt, const eph_t* eph); extern int outrnxgnavb(FILE* fp, const rnxopt_t* opt, const geph_t* geph); extern int outrnxhnavb(FILE* fp, const rnxopt_t* opt, const seph_t* seph); extern int uncompress(const char* file, char* uncfile); extern int convrnx(int format, rnxopt_t* opt, const char* file, char** ofile); extern int init_rnxctr(rnxctr_t* rnx); extern void free_rnxctr(rnxctr_t* rnx); extern int open_rnxctr(rnxctr_t* rnx, FILE* fp); extern int input_rnxctr(rnxctr_t* rnx, FILE* fp); /* ephemeris and clock functions ---------------------------------------------*/ extern double eph2clk(gtime_t time, const eph_t* eph); extern double geph2clk(gtime_t time, const geph_t* geph); extern double seph2clk(gtime_t time, const seph_t* seph); extern void eph2pos(gtime_t time, const eph_t* eph, double* rs, double* dts, double* var); extern void geph2pos(gtime_t time, const geph_t* geph, double* rs, double* dts, double* var); extern void seph2pos(gtime_t time, const seph_t* seph, double* rs, double* dts, double* var); extern int peph2pos(gtime_t time, int sat, const nav_t* nav, int opt, double* rs, double* dts, double* var); extern void satantoff(gtime_t time, const double* rs, int sat, const nav_t* nav, double* dant); extern int satpos(gtime_t time, gtime_t teph, int sat, int ephopt, const nav_t* nav, double* rs, double* dts, double* var, int* svh); extern void satposs(gtime_t time, const obsd_t* obs, int n, const nav_t* nav, int sateph, double* rs, double* dts, double* var, int* svh); extern void readsp3(const char* file, nav_t* nav, int opt); extern int readsap(const char* file, gtime_t time, nav_t* nav); extern int readdcb(const char* file, nav_t* nav); extern void alm2pos(gtime_t time, const alm_t* alm, double* rs, double* dts); extern int tle_read(const char* file, tle_t* tle); extern int tle_name_read(const char* file, tle_t* tle); extern int tle_pos(gtime_t time, const char* name, const char* satno, const char* desig, const tle_t* tle, const erp_t* erp, double* rs); /* receiver raw data functions -----------------------------------------------*/ extern unsigned int getbitu(const unsigned char* buff, int pos, int len); extern int getbits(const unsigned char* buff, int pos, int len); extern void setbitu(unsigned char* buff, int pos, int len, unsigned int data); extern void setbits(unsigned char* buff, int pos, int len, int data); extern unsigned int crc32(const unsigned char* buff, int len); extern unsigned int crc24q(const unsigned char* buff, int len); extern unsigned short crc16(const unsigned char* buff, int len); extern int decode_word(unsigned int word, unsigned char* data); extern int decode_frame(const unsigned char* buff, eph_t* eph, alm_t* alm, double* ion, double* utc, int* leaps); extern int test_glostr(const unsigned char* buff); extern int decode_glostr(const unsigned char* buff, geph_t* geph); extern int decode_bds_d1(const unsigned char* buff, eph_t* eph); extern int decode_bds_d2(const unsigned char* buff, eph_t* eph); extern int init_raw(raw_t* raw); extern void free_raw(raw_t* raw); extern int input_raw(raw_t* raw, int format, unsigned char data); extern int input_rawf(raw_t* raw, int format, FILE* fp); extern int input_oem4(raw_t* raw, unsigned char data); extern int input_oem3(raw_t* raw, unsigned char data); extern int input_ubx(raw_t* raw, unsigned char data); extern int input_ss2(raw_t* raw, unsigned char data); extern int input_cres(raw_t* raw, unsigned char data); extern int input_stq(raw_t* raw, unsigned char data); extern int input_gw10(raw_t* raw, unsigned char data); extern int input_javad(raw_t* raw, unsigned char data); extern int input_nvs(raw_t* raw, unsigned char data); extern int input_bnx(raw_t* raw, unsigned char data); extern int input_rt17(raw_t* raw, unsigned char data); extern int input_lexr(raw_t* raw, unsigned char data); extern int input_oem4f(raw_t* raw, FILE* fp); extern int input_oem3f(raw_t* raw, FILE* fp); extern int input_ubxf(raw_t* raw, FILE* fp); extern int input_ss2f(raw_t* raw, FILE* fp); extern int input_cresf(raw_t* raw, FILE* fp); extern int input_stqf(raw_t* raw, FILE* fp); extern int input_gw10f(raw_t* raw, FILE* fp); extern int input_javadf(raw_t* raw, FILE* fp); extern int input_nvsf(raw_t* raw, FILE* fp); extern int input_bnxf(raw_t* raw, FILE* fp); extern int input_rt17f(raw_t* raw, FILE* fp); extern int input_lexrf(raw_t* raw, FILE* fp); extern int gen_ubx(const char* msg, unsigned char* buff); extern int gen_stq(const char* msg, unsigned char* buff); extern int gen_nvs(const char* msg, unsigned char* buff); extern int gen_lexr(const char* msg, unsigned char* buff); /* rtcm functions ------------------------------------------------------------*/ extern int init_rtcm(rtcm_t* rtcm); extern void free_rtcm(rtcm_t* rtcm); extern int input_rtcm2(rtcm_t* rtcm, unsigned char data); extern int input_rtcm3(rtcm_t* rtcm, unsigned char data); extern int input_rtcm2f(rtcm_t* rtcm, FILE* fp); extern int input_rtcm3f(rtcm_t* rtcm, FILE* fp); extern int gen_rtcm2(rtcm_t* rtcm, int type, int sync); extern int gen_rtcm3(rtcm_t* rtcm, int type, int sync); /* solution functions --------------------------------------------------------*/ extern void initsolbuf(solbuf_t* solbuf, int cyclic, int nmax); extern void freesolbuf(solbuf_t* solbuf); extern void freesolstatbuf(solstatbuf_t* solstatbuf); extern sol_t* getsol(solbuf_t* solbuf, int index); extern int addsol(solbuf_t* solbuf, const sol_t* sol); extern int readsol(char* files[], int nfile, solbuf_t* sol); extern int readsolt(char* files[], int nfile, gtime_t ts, gtime_t te, double tint, int qflag, solbuf_t* sol); extern int readsolstat(char* files[], int nfile, solstatbuf_t* statbuf); extern int readsolstatt(char* files[], int nfile, gtime_t ts, gtime_t te, double tint, solstatbuf_t* statbuf); extern int inputsol(unsigned char data, gtime_t ts, gtime_t te, double tint, int qflag, const solopt_t* opt, solbuf_t* solbuf); extern int outprcopts(unsigned char* buff, const prcopt_t* opt); extern int outsolheads(unsigned char* buff, const solopt_t* opt); extern int outsols(unsigned char* buff, const sol_t* sol, const double* rb, const solopt_t* opt); extern int outsolexs(unsigned char* buff, const sol_t* sol, const ssat_t* ssat, const solopt_t* opt); extern void outprcopt(FILE* fp, const prcopt_t* opt); extern void outsolhead(FILE* fp, const solopt_t* opt); extern void outsol(FILE* fp, const sol_t* sol, const double* rb, const solopt_t* opt); extern void outsolex(FILE* fp, const sol_t* sol, const ssat_t* ssat, const solopt_t* opt); extern int outnmea_rmc(unsigned char* buff, const sol_t* sol); extern int outnmea_gga(unsigned char* buff, const sol_t* sol); extern int outnmea_gsa(unsigned char* buff, const sol_t* sol, const ssat_t* ssat); extern int outnmea_gsv(unsigned char* buff, const sol_t* sol, const ssat_t* ssat); /* google earth kml converter ------------------------------------------------*/ extern int convkml(const char* infile, const char* outfile, gtime_t ts, gtime_t te, double tint, int qflg, double* offset, int tcolor, int pcolor, int outalt, int outtime); /* sbas functions ------------------------------------------------------------*/ extern int sbsreadmsg(const char* file, int sel, sbs_t* sbs); extern int sbsreadmsgt(const char* file, int sel, gtime_t ts, gtime_t te, sbs_t* sbs); extern void sbsoutmsg(FILE* fp, sbsmsg_t* sbsmsg); extern int sbsdecodemsg(gtime_t time, int prn, const unsigned int* words, sbsmsg_t* sbsmsg); extern int sbsupdatecorr(const sbsmsg_t* msg, nav_t* nav); extern int sbssatcorr(gtime_t time, int sat, const nav_t* nav, double* rs, double* dts, double* var); extern int sbsioncorr(gtime_t time, const nav_t* nav, const double* pos, const double* azel, double* delay, double* var); extern double sbstropcorr(gtime_t time, const double* pos, const double* azel, double* var); /* options functions ---------------------------------------------------------*/ extern opt_t* searchopt(const char* name, const opt_t* opts); extern int str2opt(opt_t* opt, const char* str); extern int opt2str(const opt_t* opt, char* str); extern int opt2buf(const opt_t* opt, char* buff); extern int loadopts(const char* file, opt_t* opts); extern int saveopts(const char* file, const char* mode, const char* comment, const opt_t* opts); extern void resetsysopts(void); extern void getsysopts(prcopt_t* popt, solopt_t* sopt, filopt_t* fopt); extern void setsysopts(const prcopt_t* popt, const solopt_t* sopt, const filopt_t* fopt); /* stream data input and output functions ------------------------------------*/ extern void strinitcom(void); extern void strinit(stream_t* stream); extern void strlock(stream_t* stream); extern void strunlock(stream_t* stream); extern int stropen(stream_t* stream, int type, int mode, const char* path); extern void strclose(stream_t* stream); extern int strread(stream_t* stream, unsigned char* buff, int n); extern int strwrite(stream_t* stream, unsigned char* buff, int n); extern void strsync(stream_t* stream1, stream_t* stream2); extern int strstat(stream_t* stream, char* msg); extern void strsum(stream_t* stream, int* inb, int* inr, int* outb, int* outr); extern void strsetopt(const int* opt); extern gtime_t strgettime(stream_t* stream); extern void strsendnmea(stream_t* stream, const double* pos); extern void strsendcmd(stream_t* stream, const char* cmd); extern void strsettimeout(stream_t* stream, int toinact, int tirecon); extern void strsetdir(const char* dir); extern void strsetproxy(const char* addr); /* integer ambiguity resolution ----------------------------------------------*/ extern int lambda(int n, int m, const double* a, const double* Q, double* F, double* s); /* standard positioning ------------------------------------------------------*/ extern int pntpos(const obsd_t* obs, int n, const nav_t* nav, const prcopt_t* opt, sol_t* sol, double* azel, ssat_t* ssat, char* msg); /* precise positioning -------------------------------------------------------*/ extern void rtkinit(rtk_t* rtk, const prcopt_t* opt); extern void rtkfree(rtk_t* rtk); extern int rtkpos(rtk_t* rtk, const obsd_t* obs, int nobs, const nav_t* nav); extern int rtkopenstat(const char* file, int level); extern void rtkclosestat(void); /* precise point positioning -------------------------------------------------*/ extern void pppos(rtk_t* rtk, const obsd_t* obs, int n, const nav_t* nav); extern int pppamb(rtk_t* rtk, const obsd_t* obs, int n, const nav_t* nav, const double* azel); extern int pppnx(const prcopt_t* opt); extern void pppoutsolstat(rtk_t* rtk, int level, FILE* fp); extern void windupcorr(gtime_t time, const double* rs, const double* rr, double* phw); /* post-processing positioning -----------------------------------------------*/ extern int postpos(gtime_t ts, gtime_t te, double ti, double tu, const prcopt_t* popt, const solopt_t* sopt, const filopt_t* fopt, char** infile, int n, char* outfile, const char* rov, const char* base); /* stream server functions ---------------------------------------------------*/ extern void strsvrinit(strsvr_t* svr, int nout); extern int strsvrstart(strsvr_t* svr, int* opts, int* strs, char** paths, strconv_t** conv, const char* cmd, const double* nmeapos); extern void strsvrstop(strsvr_t* svr, const char* cmd); extern void strsvrstat(strsvr_t* svr, int* stat, int* byte, int* bps, char* msg); extern strconv_t* strconvnew(int itype, int otype, const char* msgs, int staid, int stasel, const char* opt); extern void strconvfree(strconv_t* conv); /* rtk server functions ------------------------------------------------------*/ extern int rtksvrinit(rtksvr_t* svr); extern void rtksvrfree(rtksvr_t* svr); extern int rtksvrstart(rtksvr_t* svr, int cycle, int buffsize, int* strs, char** paths, int* formats, int navsel, char** cmds, char** rcvopts, int nmeacycle, int nmeareq, const double* nmeapos, prcopt_t* prcopt, solopt_t* solopt, stream_t* moni); extern void rtksvrstop(rtksvr_t* svr, char** cmds); extern int rtksvropenstr(rtksvr_t* svr, int index, int str, const char* path, const solopt_t* solopt); extern void rtksvrclosestr(rtksvr_t* svr, int index); extern void rtksvrlock(rtksvr_t* svr); extern void rtksvrunlock(rtksvr_t* svr); extern int rtksvrostat(rtksvr_t* svr, int type, gtime_t* time, int* sat, double* az, double* el, int** snr, int* vsat); extern void rtksvrsstat(rtksvr_t* svr, int* sstat, char* msg); /* downloader functions ------------------------------------------------------*/ extern int dl_readurls(const char* file, char** types, int ntype, url_t* urls, int nmax); extern int dl_readstas(const char* file, char** stas, int nmax); extern int dl_exec(gtime_t ts, gtime_t te, double ti, int seqnos, int seqnoe, const url_t* urls, int nurl, char** stas, int nsta, const char* dir, const char* usr, const char* pwd, const char* proxy, int opts, char* msg, FILE* fp); extern void dl_test(gtime_t ts, gtime_t te, double ti, const url_t* urls, int nurl, char** stas, int nsta, const char* dir, int ncol, int datefmt, FILE* fp); /* application defined functions ---------------------------------------------*/ extern int showmsg(char* format, ...); extern void settspan(gtime_t ts, gtime_t te); extern void settime(gtime_t time); /* qzss lex functions --------------------------------------------------------*/ extern int lexupdatecorr(const lexmsg_t* msg, nav_t* nav, gtime_t* tof); extern int lexreadmsg(const char* file, int sel, lex_t* lex); extern void lexoutmsg(FILE* fp, const lexmsg_t* msg); extern int lexconvbin(int type, int format, const char* infile, const char* outfile); extern int lexeph2pos(gtime_t time, int sat, const nav_t* nav, double* rs, double* dts, double* var); extern int lexioncorr(gtime_t time, const nav_t* nav, const double* pos, const double* azel, double* delay, double* var); #ifdef __cplusplus } #endif
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/rtklib/novatel.c
/********************************************************************************* * The RTKLIB software package is distributed under the following BSD 2-clause * license (http://opensource.org/licenses/BSD-2-Clause) and additional two * exclusive clauses. Users are permitted to develop, produce or sell their own * non-commercial or commercial products utilizing, linking or including RTKLIB *as long as they comply with the license. * * Copyright (c) 2007-2013, T. Takasu, 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. * * - The software package includes some companion executive binaries or shared * libraries necessary to execute APs on Windows. These licenses succeed to *the original ones of these software. * * 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 HOLDER 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. ***********************************************************************************/ /*------------------------------------------------------------------------------ * notvatel.c : NovAtel OEM6/OEM5/OEM4/OEM3 receiver functions * * Copyright (C) 2007-2014 by T.TAKASU, All rights reserved. * * reference : * [1] NovAtel, OM-20000094 Rev6 OEMV Family Firmware Reference Manual, 2008 * [2] NovAtel, OM-20000053 Rev2 MiLLennium GPSCard Software Versions 4.503 * and 4.52 Command Descriptions Manual, 2001 * [3] NovAtel, OM-20000129 Rev2 OEM6 Family Firmware Reference Manual, 2011 * [4] NovAtel, OM-20000127 Rev1 OEMStar Firmware Reference Manual, 2009 * [5] NovAtel, OM-20000129 Rev6 OEM6 Family Firmware Reference Manual, 2014 * * version : $Revision: 1.2 $ $Date: 2008/07/14 00:05:05 $ * history : 2007/10/08 1.0 new * 2008/05/09 1.1 fix bug lli flag outage * 2008/06/16 1.2 separate common functions to rcvcmn.c * 2009/04/01 1.3 add prn number check for raw obs data * 2009/04/10 1.4 refactored * add oem3, oem4 rangeb support * 2009/06/06 1.5 fix bug on numerical exception with illegal snr * support oem3 regd message * 2009/12/09 1.6 support oem4 gloephemerisb message * invalid if parity unknown in GLONASS range * fix bug of dopper polarity inversion for oem3 regd * 2010/04/29 1.7 add tod field in geph_t * 2011/05/27 1.8 support RAWALM for oem4/v * add almanac decoding * add -EPHALL option * fix problem on ARM compiler * 2012/05/02 1.9 support OEM6,L5,QZSS * 2012/10/18 1.10 change obs codes * support Galileo * support rawsbasframeb,galephemerisb,galalmanacb, * galclockb,galionob * 2012/11/08 1.11 support galfnavrawpageb, galinavrawword * 2012/11/19 1.12 fix bug on decodeing rangeb * 2013/02/23 1.13 fix memory access violation problem on arm * 2013/03/28 1.14 fix invalid phase if glonass wavelen unavailable * 2013/06/02 1.15 fix bug on reading galephemrisb,galalmanacb, * galclockb,galionob * fix bug on decoding rawwaasframeb for qzss-saif * 2014/05/24 1.16 support beidou * 2014/07/01 1.17 fix problem on decoding of bdsephemerisb * fix bug on beidou tracking codes * 2014/10/20 1.11 fix bug on receiver option -GL*,-RL*,-EL* *-----------------------------------------------------------------------------*/ /** * file: novatel.c * version: rtklib ver.2.4.2 * Copy from * https://github.com/tomojitakasu/RTKLIB/tree/76b9c97257f304aedad38b5a6bbbac444724aab3/src/rcv/novatel.c */ #include <stdio.h> #include "rtklib.h" /* static const char rcsid[] = "$Id: novatel.c,v 1.2 2008/07/14 00:05:05 TTAKA Exp $"; */ #define OEM4SYNC1 0xAA /* oem4 message start sync code 1 */ #define OEM4SYNC2 0x44 /* oem4 message start sync code 2 */ #define OEM4SYNC3 0x12 /* oem4 message start sync code 3 */ #define OEM3SYNC1 0xAA /* oem3 message start sync code 1 */ #define OEM3SYNC2 0x44 /* oem3 message start sync code 2 */ #define OEM3SYNC3 0x11 /* oem3 message start sync code 3 */ #define OEM4HLEN 28 /* oem4 message header length (bytes) */ #define OEM3HLEN 12 /* oem3 message header length (bytes) */ #define ID_ALMANAC 73 /* message id: oem4 decoded almanac */ #define ID_GLOALMANAC 718 /* message id: oem4 glonass decoded almanac */ #define ID_GLOEPHEMERIS 723 /* message id: oem4 glonass ephemeris */ #define ID_IONUTC 8 /* message id: oem4 iono and utc data */ #define ID_RANGE 43 /* message id: oem4 range measurement */ #define ID_RANGECMP 140 /* message id: oem4 range compressed */ #define ID_RAWALM 74 /* message id: oem4 raw almanac */ #define ID_RAWEPHEM 41 /* message id: oem4 raw ephemeris */ #define ID_RAWWAASFRAME 287 /* message id: oem4 raw waas frame */ #define ID_QZSSIONUTC 1347 /* message id: oem6 qzss ion/utc parameters */ #define ID_QZSSRAWEPHEM 1330 /* message id: oem6 qzss raw ephemeris */ #define ID_QZSSRAWSUBFRAME 1331 /* message id: oem6 qzss raw subframe */ #define ID_RAWSBASFRAME 973 /* message id: oem6 raw sbas frame */ #define ID_GALEPHEMERIS 1122 /* message id: oem6 decoded galileo ephemeris */ #define ID_GALALMANAC 1120 /* message id: oem6 decoded galileo almanac */ #define ID_GALCLOCK 1121 /* message id: oem6 galileo clockinformation */ #define ID_GALIONO \ 1127 /* message id: oem6 decoded galileo iono corrections \ */ #define ID_GALFNAVRAWPAGE \ 1413 /* message id: oem6 raw galileo f/nav paga data */ #define ID_GALINAVRAWWORD \ 1414 /* message id: oem6 raw galileo i/nav word data */ #define ID_RAWCNAVFRAME 1066 /* message id: oem6 raw cnav frame data */ #define ID_BDSEPHEMERIS 1696 /* message id: oem6 decoded bds ephemeris */ #define ID_ALMB 18 /* message id: oem3 decoded almanac */ #define ID_IONB 16 /* message id: oem3 iono parameters */ #define ID_UTCB 17 /* message id: oem3 utc parameters */ #define ID_FRMB 54 /* message id: oem3 framed raw navigation data */ #define ID_RALB 15 /* message id: oem3 raw almanac */ #define ID_RASB 66 /* message id: oem3 raw almanac set */ #define ID_REPB 14 /* message id: oem3 raw ephemeris */ #define ID_RGEB 32 /* message id: oem3 range measurement */ #define ID_RGED 65 /* message id: oem3 range compressed */ #define WL1 0.1902936727984 #define WL2 0.2442102134246 #define MAXVAL 8388608.0 #define OFF_FRQNO -7 /* F/W ver.3.620 */ /* get fields (little-endian) ------------------------------------------------*/ #define U1(p) (*((unsigned char*)(p))) #define I1(p) (*((char*)(p))) static unsigned short U2(unsigned char* p) { unsigned short u = 0; memcpy(&u, p, 2); return u; } static unsigned int U4(unsigned char* p) { unsigned int u = 0; memcpy(&u, p, 4); return u; } static int I4(unsigned char* p) { int i = 0; memcpy(&i, p, 4); return i; } static float R4(unsigned char* p) { float r = 0.0; memcpy(&r, p, 4); return r; } static double R8(unsigned char* p) { double r = 0.0; memcpy(&r, p, 8); return r; } /* extend sign ---------------------------------------------------------------*/ static int exsign(unsigned int v, int bits) { return (int)(v & (1 << (bits - 1)) ? v | (~0u << bits) : v); } /* checksum ------------------------------------------------------------------*/ static unsigned char chksum(const unsigned char* buff, int len) { unsigned char sum = 0; int i = 0; for (i = 0; i < len; ++i) { sum ^= buff[i]; } return sum; } /* adjust weekly rollover of gps time ----------------------------------------*/ static gtime_t adjweek(gtime_t time, double tow) { double tow_p = 0.0; int week = 0; tow_p = time2gpst(time, &week); if (tow < tow_p - 302400.0) { tow += 604800.0; } else if (tow > tow_p + 302400.0) { tow -= 604800.0; } return gpst2time(week, tow); } /* get observation data index ------------------------------------------------*/ static int obsindex(obs_t* obs, gtime_t time, int sat) { int i = 0; int j = 0; if (obs->n >= MAXOBS) { return -1; } for (i = 0; i < obs->n; ++i) { if (obs->data[i].sat == sat) { return i; } } obs->data[i].time = time; obs->data[i].sat = sat; for (j = 0; j < NFREQ + NEXOBS; ++j) { obs->data[i].L[j] = obs->data[i].P[j] = 0.0; obs->data[i].D[j] = 0.0; obs->data[i].SNR[j] = obs->data[i].LLI[j] = 0; obs->data[i].code[j] = CODE_NONE; } obs->n++; return i; } /* ura value (m) to ura index ------------------------------------------------*/ static int uraindex(double value) { static const double ura_eph[] = {2.4, 3.4, 4.85, 6.85, 9.65, 13.65, 24.0, 48.0, 96.0, 192.0, 384.0, 768.0, 1536.0, 3072.0, 6144.0, 0.0}; int i = 0; for (i = 0; i < 15; ++i) { if (ura_eph[i] >= value) { break; } } return i; } /* decode oem4 tracking status ------------------------------------------------- * deocode oem4 tracking status * args : unsigned int stat I tracking status field * int *sys O system (SYS_???) * int *code O signal code (CODE_L??) * int *track O tracking state * (oem4/5) * 0=L1 idle 8=L2 idle * 1=L1 sky search 9=L2 p-code align * 2=L1 wide freq pull-in 10=L2 search * 3=L1 narrow freq pull-in 11=L2 pll * 4=L1 pll 12=L2 steering * 5=L1 reacq * 6=L1 steering * 7=L1 fll * (oem6) * 0=idle 7=freq-lock loop * 2=wide freq band pull-in 9=channel alignment * 3=narrow freq band pull-in 10=code search * 4=phase lock loop 11=aided phase lock loop * int *plock O phase-lock flag (0=not locked, 1=locked) * int *clock O code-lock flag (0=not locked, 1=locked) * int *parity O parity known flag (0=not known, 1=known) * int *halfc O phase measurement (0=half-cycle not added, * 1=added) * return : signal frequency (0:L1,1:L2,2:L5,3:L6,4:L7,5:L8,-1:error) * notes : refer [1][3] *-----------------------------------------------------------------------------*/ static int decode_trackstat(unsigned int stat, int* sys, int* code, int* track, int* plock, int* clock, int* parity, int* halfc) { int satsys = 0; int sigtype = 0; int freq = 0; *track = stat & 0x1F; *plock = (stat >> 10) & 1; *parity = (stat >> 11) & 1; *clock = (stat >> 12) & 1; satsys = (stat >> 16) & 7; *halfc = (stat >> 28) & 1; sigtype = (stat >> 21) & 0x1F; switch (satsys) { case 0: *sys = SYS_GPS; break; case 1: *sys = SYS_GLO; break; case 2: *sys = SYS_SBS; break; case 3: *sys = SYS_GAL; break; /* OEM6 */ case 4: *sys = SYS_CMP; break; /* OEM6 F/W 6.400 */ case 5: *sys = SYS_QZS; break; /* OEM6 */ default: trace(2, "oem4 unknown system: sys=%d\n", satsys); return -1; } if (*sys == SYS_GPS || *sys == SYS_QZS) { switch (sigtype) { case 0: freq = 0; *code = CODE_L1C; break; /* L1C/A */ case 5: freq = 0; *code = CODE_L1P; break; /* L1P */ case 9: freq = 1; *code = CODE_L2D; break; /* L2Pcodeless */ case 14: freq = 2; *code = CODE_L5Q; break; /* L5Q (OEM6) */ case 17: freq = 1; *code = CODE_L2X; break; /* L2C(M+L) */ default: freq = -1; break; } } else if (*sys == SYS_GLO) { switch (sigtype) { case 0: freq = 0; *code = CODE_L1C; break; /* L1C/A */ case 1: freq = 1; *code = CODE_L2C; break; /* L2C/A (OEM6) */ case 5: freq = 1; *code = CODE_L2P; break; /* L2P */ default: freq = -1; break; } } else if (*sys == SYS_GAL) { switch (sigtype) { case 1: freq = 0; *code = CODE_L1B; break; /* E1B (OEM6) */ case 2: freq = 0; *code = CODE_L1C; break; /* E1C (OEM6) */ case 12: freq = 2; *code = CODE_L5Q; break; /* E5aQ (OEM6) */ case 17: freq = 4; *code = CODE_L7Q; break; /* E5bQ (OEM6) */ case 20: freq = 5; *code = CODE_L8Q; break; /* AltBOCQ (OEM6) */ default: freq = -1; break; } } else if (*sys == SYS_CMP) { switch (sigtype) { case 0: freq = 0; *code = CODE_L1I; break; /* B1 with D1 (OEM6) */ case 1: freq = 1; *code = CODE_L7I; break; /* B2 with D1 (OEM6) */ case 4: freq = 0; *code = CODE_L1I; break; /* B1 with D2 (OEM6) */ case 5: freq = 1; *code = CODE_L7I; break; /* B2 with D2 (OEM6) */ default: freq = -1; break; } } else if (*sys == SYS_SBS) { switch (sigtype) { case 0: freq = 0; *code = CODE_L1C; break; /* L1C/A */ case 6: freq = 2; *code = CODE_L5I; break; /* L5I (OEM6) */ default: freq = -1; break; } } if (freq < 0) { trace(2, "oem4 signal type error: sys=%d sigtype=%d\n", *sys, sigtype); return -1; } return freq; } /* check code priority and return obs position -------------------------------*/ static int checkpri(const char* opt, int sys, int code, int freq) { int nex = NEXOBS; /* number of extended obs data */ if (sys == SYS_GPS) { if (strstr(opt, "-GL1P") && freq == 0) { return code == CODE_L1P ? 0 : -1; } if (strstr(opt, "-GL2X") && freq == 1) { return code == CODE_L2X ? 1 : -1; } if (code == CODE_L1P) { return nex < 1 ? -1 : NFREQ; } if (code == CODE_L2X) { return nex < 2 ? -1 : NFREQ + 1; } } else if (sys == SYS_GLO) { if (strstr(opt, "-RL2C") && freq == 1) { return code == CODE_L2C ? 1 : -1; } if (code == CODE_L2C) { return nex < 1 ? -1 : NFREQ; } } else if (sys == SYS_GAL) { if (strstr(opt, "-EL1B") && freq == 0) { return code == CODE_L1B ? 0 : -1; } if (code == CODE_L1B) { return nex < 1 ? -1 : NFREQ; } if (code == CODE_L7Q) { return nex < 2 ? -1 : NFREQ + 1; } if (code == CODE_L8Q) { return nex < 3 ? -1 : NFREQ + 2; } } return freq < NFREQ ? freq : -1; } /* decode rangecmpb ----------------------------------------------------------*/ static int decode_rangecmpb(raw_t* raw) { double psr = 0.0; double adr = 0.0; double adr_rolls = 0.0; double lockt = 0.0; double tt = 0.0; double dop = 0.0; double snr = 0.0; double wavelen = 0.0; int i = 0; int index = 0; int nobs = 0; int prn = 0; int sat = 0; int sys = 0; int code = 0; int freq = 0; int pos = 0; int track = 0; int plock = 0; int clock = 0; int parity = 0; int halfc = 0; int lli = 0; char* msg = NULL; unsigned char* p = raw->buff + OEM4HLEN; trace(3, "decode_rangecmpb: len=%d\n", raw->len); nobs = U4(p); if (raw->outtype) { msg = raw->msgtype + strlen(raw->msgtype); sprintf(msg, " nobs=%2d", nobs); } if (raw->len < OEM4HLEN + 4 + nobs * 24) { trace(2, "oem4 rangecmpb length error: len=%d nobs=%d\n", raw->len, nobs); return -1; } for (i = 0, p += 4; i < nobs; ++i, p += 24) { /* decode tracking status */ if ((freq = decode_trackstat(U4(p), &sys, &code, &track, &plock, &clock, &parity, &halfc)) < 0) { continue; } /* obs position */ if ((pos = checkpri(raw->opt, sys, code, freq)) < 0) { continue; } prn = U1(p + 17); if (sys == SYS_GLO) { prn -= 37; } if (!(sat = satno(sys, prn))) { trace(3, "oem4 rangecmpb satellite number error: sys=%d,prn=%d\n", sys, prn); continue; } if (sys == SYS_GLO && !parity) { continue; /* invalid if GLO parity unknown */ } dop = exsign(U4(p + 4) & 0xFFFFFFF, 28) / 256.0; psr = (U4(p + 7) >> 4) / 128.0 + U1(p + 11) * 2097152.0; if ((wavelen = satwavelen(sat, freq, &raw->nav)) <= 0.0) { if (sys == SYS_GLO) { wavelen = CLIGHT / (freq == 0 ? FREQ1_GLO : FREQ2_GLO); } else { wavelen = lam_carr[freq]; } } adr = I4(p + 12) / 256.0; adr_rolls = (psr / wavelen + adr) / MAXVAL; adr = -adr + MAXVAL * floor(adr_rolls + (adr_rolls <= 0 ? -0.5 : 0.5)); lockt = (U4(p + 18) & 0x1FFFFF) / 32.0; /* lock time */ tt = timediff(raw->time, raw->tobs); if (raw->tobs.time != 0) { lli = (lockt < 65535.968 && lockt - raw->lockt[sat - 1][pos] + 0.05 <= tt) || halfc != raw->halfc[sat - 1][pos]; } else { lli = 0; } if (!parity) { lli |= 2; } raw->lockt[sat - 1][pos] = lockt; raw->halfc[sat - 1][pos] = halfc; snr = ((U2(p + 20) & 0x3FF) >> 5) + 20.0; if (!clock) { psr = 0.0; /* code unlock */ } if (!plock) { adr = dop = 0.0; /* phase unlock */ } if (fabs(timediff(raw->obs.data[0].time, raw->time)) > 1E-9) { raw->obs.n = 0; } if ((index = obsindex(&raw->obs, raw->time, sat)) >= 0) { raw->obs.data[index].L[pos] = adr; raw->obs.data[index].P[pos] = psr; raw->obs.data[index].D[pos] = (float)dop; raw->obs.data[index].SNR[pos] = 0.0 <= snr && snr < 255.0 ? (unsigned char)(snr * 4.0 + 0.5) : 0; raw->obs.data[index].LLI[pos] = (unsigned char)lli; raw->obs.data[index].code[pos] = code; #if 0 /* L2C phase shift correction (L2C->L2P) */ if (code == CODE_L2X) { raw->obs.data[index].L[pos] += 0.25; trace(3, "oem4 L2C phase shift corrected: prn=%2d\n", prn); } #endif } } raw->tobs = raw->time; return 1; } /* decode rangeb -------------------------------------------------------------*/ static int decode_rangeb(raw_t* raw) { double psr = 0.0; double adr = 0.0; double dop = 0.0; double snr = 0.0; double lockt = 0.0; double tt = 0.0; char* msg = NULL; int i = 0; int index = 0; int nobs = 0; int prn = 0; int sat = 0; int sys = 0; int code = 0; int freq = 0; int pos = 0; ; int track = 0; int plock = 0; int clock = 0; int parity = 0; int halfc = 0; int lli = 0; int gfrq = 0; ; unsigned char* p = raw->buff + OEM4HLEN; trace(3, "decode_rangeb: len=%d\n", raw->len); nobs = U4(p); if (raw->outtype) { msg = raw->msgtype + strlen(raw->msgtype); sprintf(msg, " nobs=%2d", nobs); } if (raw->len < OEM4HLEN + 4 + nobs * 44) { trace(2, "oem4 rangeb length error: len=%d nobs=%d\n", raw->len, nobs); return -1; } for (i = 0, p += 4; i < nobs; ++i, p += 44) { /* decode tracking status */ if ((freq = decode_trackstat(U4(p + 40), &sys, &code, &track, &plock, &clock, &parity, &halfc)) < 0) { continue; } /* obs position */ if ((pos = checkpri(raw->opt, sys, code, freq)) < 0) { continue; } prn = U2(p); if (sys == SYS_GLO) { prn -= 37; } if (!(sat = satno(sys, prn))) { trace(3, "oem4 rangeb satellite number error: sys=%d,prn=%d\n", sys, prn); continue; } if (sys == SYS_GLO && !parity) { continue; /* invalid if GLO parity unknown */ } gfrq = U2(p + 2); psr = R8(p + 4); adr = R8(p + 16); dop = R4(p + 28); snr = R4(p + 32); lockt = R4(p + 36); /* set glonass frequency channel number */ if (sys == SYS_GLO && raw->nav.geph[prn - 1].sat != sat) { raw->nav.geph[prn - 1].frq = gfrq - 7; } tt = timediff(raw->time, raw->tobs); if (raw->tobs.time != 0) { lli = lockt - raw->lockt[sat - 1][pos] + 0.05 <= tt || halfc != raw->halfc[sat - 1][pos]; } else { lli = 0; } if (!parity) { lli |= 2; } raw->lockt[sat - 1][pos] = lockt; raw->halfc[sat - 1][pos] = halfc; if (!clock) { psr = 0.0; /* code unlock */ } if (!plock) { adr = dop = 0.0; /* phase unlock */ } if (fabs(timediff(raw->obs.data[0].time, raw->time)) > 1E-9) { raw->obs.n = 0; } if ((index = obsindex(&raw->obs, raw->time, sat)) >= 0) { raw->obs.data[index].L[pos] = -adr; raw->obs.data[index].P[pos] = psr; raw->obs.data[index].D[pos] = (float)dop; raw->obs.data[index].SNR[pos] = 0.0 <= snr && snr < 255.0 ? (unsigned char)(snr * 4.0 + 0.5) : 0; raw->obs.data[index].LLI[pos] = (unsigned char)lli; raw->obs.data[index].code[pos] = code; #if 0 /* L2C phase shift correction */ if (code == CODE_L2X) { raw->obs.data[index].L[pos] += 0.25; trace(3, "oem4 L2C phase shift corrected: prn=%2d\n", prn); } #endif } } raw->tobs = raw->time; return 1; } /* decode rawephemb ----------------------------------------------------------*/ static int decode_rawephemb(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; eph_t eph = {0}; int prn = 0; int sat = 0; trace(3, "decode_rawephemb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 102) { trace(2, "oem4 rawephemb length error: len=%d\n", raw->len); return -1; } prn = U4(p); if (!(sat = satno(SYS_GPS, prn))) { trace(2, "oem4 rawephemb satellite number error: prn=%d\n", prn); return -1; } if (decode_frame(p + 12, &eph, NULL, NULL, NULL, NULL) != 1 || decode_frame(p + 42, &eph, NULL, NULL, NULL, NULL) != 2 || decode_frame(p + 72, &eph, NULL, NULL, NULL, NULL) != 3) { trace(2, "oem4 rawephemb subframe error: prn=%d\n", prn); return -1; } if (!strstr(raw->opt, "-EPHALL")) { if (eph.iode == raw->nav.eph[sat - 1].iode) { return 0; /* unchanged */ } } eph.sat = sat; raw->nav.eph[sat - 1] = eph; raw->ephsat = sat; trace(4, "decode_rawephemb: sat=%2d\n", sat); return 2; } ///* decode ionutcb ///------------------------------------------------------------*/ static int decode_ionutcb(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; int i = 0; trace(3, "decode_ionutcb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 108) { trace(2, "oem4 ionutcb length error: len=%d\n", raw->len); return -1; } for (i = 0; i < 8; ++i) { raw->nav.ion_gps[i] = R8(p + i * 8); } raw->nav.utc_gps[0] = R8(p + 72); raw->nav.utc_gps[1] = R8(p + 80); raw->nav.utc_gps[2] = U4(p + 68); raw->nav.utc_gps[3] = U4(p + 64); raw->nav.leaps = I4(p + 96); return 9; } ///* decode rawwaasframeb ///------------------------------------------------------*/ static int decode_rawwaasframeb(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; int i = 0; int prn = 0; trace(3, "decode_rawwaasframeb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 48) { trace(2, "oem4 rawwaasframeb length error: len=%d\n", raw->len); return -1; } prn = U4(p + 4); if (MINPRNQZS_S <= prn && prn <= MAXPRNQZS_S) { prn += 10; /* QZSS SAIF PRN -> QZSS PRN */ } else if (prn < MINPRNSBS || MAXPRNSBS < prn) { return 0; } raw->sbsmsg.tow = (int)time2gpst(raw->time, &raw->sbsmsg.week); raw->sbsmsg.prn = prn; for (i = 0, p += 12; i < 29; ++i, ++p) { raw->sbsmsg.msg[i] = *p; } return 3; } ///* decode rawsbasframeb ///------------------------------------------------------*/ static int decode_rawsbasframeb(raw_t* raw) { trace(3, "decode_rawsbasframeb: len=%d\n", raw->len); /* format same as rawwaasframeb */ return decode_rawwaasframeb(raw); } /* decode gloephemerisb ------------------------------------------------------*/ static int decode_gloephemerisb(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; geph_t geph = {0}; char* msg = NULL; double tow = 0.0; double tof = 0.0; double toff = 0.0; int prn = 0; int sat = 0; int week = 0; trace(3, "decode_gloephemerisb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 144) { trace(2, "oem4 gloephemerisb length error: len=%d\n", raw->len); return -1; } prn = U2(p) - 37; if (raw->outtype) { msg = raw->msgtype + strlen(raw->msgtype); sprintf(msg, " prn=%3d", prn); } if (!(sat = satno(SYS_GLO, prn))) { trace(2, "oem4 gloephemerisb prn error: prn=%d\n", prn); return -1; } geph.frq = U2(p + 2) + OFF_FRQNO; week = U2(p + 6); tow = floor(U4(p + 8) / 1000.0 + 0.5); /* rounded to integer sec */ toff = U4(p + 12); geph.iode = U4(p + 20) & 0x7F; geph.svh = U4(p + 24); geph.pos[0] = R8(p + 28); geph.pos[1] = R8(p + 36); geph.pos[2] = R8(p + 44); geph.vel[0] = R8(p + 52); geph.vel[1] = R8(p + 60); geph.vel[2] = R8(p + 68); geph.acc[0] = R8(p + 76); geph.acc[1] = R8(p + 84); geph.acc[2] = R8(p + 92); geph.taun = R8(p + 100); geph.gamn = R8(p + 116); tof = U4(p + 124) - toff; /* glonasst->gpst */ geph.age = U4(p + 136); geph.toe = gpst2time(week, tow); tof += floor(tow / 86400.0) * 86400; if (tof < tow - 43200.0) { tof += 86400.0; } else if (tof > tow + 43200.0) { tof -= 86400.0; } geph.tof = gpst2time(week, tof); if (!strstr(raw->opt, "-EPHALL")) { if (fabs(timediff(geph.toe, raw->nav.geph[prn - 1].toe)) < 1.0 && geph.svh == raw->nav.geph[prn - 1].svh) { return 0; /* unchanged */ } } geph.sat = sat; raw->nav.geph[prn - 1] = geph; raw->ephsat = sat; return 2; } ///* decode qzss rawephemb ///-----------------------------------------------------*/ static int decode_qzssrawephemb(raw_t* raw) { unsigned char *p = raw->buff + OEM4HLEN, *q; eph_t eph = {0}; char* msg = NULL; int i = 0; int prn = 0; int id = 0; int sat = 0; trace(3, "decode_qzssrawephemb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 44) { trace(2, "oem4 qzssrawephemb length error: len=%d\n", raw->len); return -1; } prn = U4(p); id = U4(p + 4); if (raw->outtype) { msg = raw->msgtype + strlen(raw->msgtype); sprintf(msg, " prn=%3d id=%d", prn, id); } if (!(sat = satno(SYS_QZS, prn))) { trace(2, "oem4 qzssrawephemb satellite number error: prn=%d\n", prn); return -1; } if (id < 1 || 3 < id) { return 0; } q = raw->subfrm[sat - 1] + (id - 1) * 30; for (i = 0; i < 30; ++i) { *q++ = p[8 + i]; } if (id < 3) { return 0; } if (decode_frame(raw->subfrm[sat - 1], &eph, NULL, NULL, NULL, NULL) != 1 || decode_frame(raw->subfrm[sat - 1] + 30, &eph, NULL, NULL, NULL, NULL) != 2 || decode_frame(raw->subfrm[sat - 1] + 60, &eph, NULL, NULL, NULL, NULL) != 3) { return 0; } if (!strstr(raw->opt, "-EPHALL")) { if (eph.iodc == raw->nav.eph[sat - 1].iodc && eph.iode == raw->nav.eph[sat - 1].iode) { return 0; /* unchanged */ } } eph.sat = sat; raw->nav.eph[sat - 1] = eph; raw->ephsat = sat; trace(4, "decode_qzssrawephemb: sat=%2d\n", sat); return 2; } ///* decode qzss rawsubframeb ///--------------------------------------------------*/ static int decode_qzssrawsubframeb(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; eph_t eph = {0}; char* msg = NULL; int prn = 0; int sat = 0; trace(3, "decode_qzssrawsubframeb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 44) { trace(2, "oem4 qzssrawsubframeb length error: len=%d\n", raw->len); return -1; } prn = U4(p); if (raw->outtype) { msg = raw->msgtype + strlen(raw->msgtype); sprintf(msg, " prn=%3d", prn); } if (!(sat = satno(SYS_QZS, prn))) { trace(2, "oem4 qzssrawephemb satellite number error: prn=%d\n", prn); return -1; } if (decode_frame(p + 12, &eph, NULL, NULL, NULL, NULL) != 1 || decode_frame(p + 42, &eph, NULL, NULL, NULL, NULL) != 2 || decode_frame(p + 72, &eph, NULL, NULL, NULL, NULL) != 3) { return 0; } if (!strstr(raw->opt, "-EPHALL")) { if (eph.iodc == raw->nav.eph[sat - 1].iodc && eph.iode == raw->nav.eph[sat - 1].iode) { return 0; /* unchanged */ } } eph.sat = sat; raw->nav.eph[sat - 1] = eph; raw->ephsat = sat; trace(4, "decode_qzssrawsubframeb: sat=%2d\n", sat); return 2; } ///* decode qzssionutcb ///--------------------------------------------------------*/ static int decode_qzssionutcb(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; int i = 0; trace(3, "decode_qzssionutcb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 108) { trace(2, "oem4 qzssionutcb length error: len=%d\n", raw->len); return -1; } for (i = 0; i < 8; ++i) { raw->nav.ion_qzs[i] = R8(p + i * 8); } raw->nav.utc_qzs[0] = R8(p + 72); raw->nav.utc_qzs[1] = R8(p + 80); raw->nav.utc_qzs[2] = U4(p + 68); raw->nav.utc_qzs[3] = U4(p + 64); raw->nav.leaps = I4(p + 96); return 9; } /* decode galephemerisb ------------------------------------------------------*/ static int decode_galephemerisb(raw_t* raw) { eph_t eph = {0}; unsigned char* p = raw->buff + OEM4HLEN; double tow = 0.0; double sqrtA = 0.0; double af0_fnav = 0.0; double af1_fnav = 0.0; double af2_fnav = 0.0; double af0_inav = 0.0; double af1_inav = 0.0; double af2_inav = 0.0; double tt = 0.0; char* msg = NULL; int prn; int rcv_fnav = 0; int rcv_inav = 0; int svh_e1b = 0; int svh_e5a = 0; int svh_e5b = 0; int dvs_e1b = 0; int dvs_e5a = 0; int dvs_e5b = 0; int toc_fnav = 0; int toc_inav = 0; int week = 0; trace(3, "decode_galephemerisb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 220) { trace(2, "oem4 galephemrisb length error: len=%d\n", raw->len); return -1; } prn = U4(p); p += 4; rcv_fnav = U4(p) & 1; p += 4; rcv_inav = U4(p) & 1; (void)rcv_inav; p += 4; svh_e1b = U1(p) & 3; p += 1; svh_e5a = U1(p) & 3; p += 1; svh_e5b = U1(p) & 3; p += 1; dvs_e1b = U1(p) & 1; p += 1; dvs_e5a = U1(p) & 1; p += 1; dvs_e5b = U1(p) & 1; p += 1; eph.sva = U1(p); p += 1 + 1; /* SISA */ eph.iode = U4(p); p += 4; /* IODNav */ eph.toes = U4(p); p += 4; sqrtA = R8(p); p += 8; eph.deln = R8(p); p += 8; eph.M0 = R8(p); p += 8; eph.e = R8(p); p += 8; eph.omg = R8(p); p += 8; eph.cuc = R8(p); p += 8; eph.cus = R8(p); p += 8; eph.crc = R8(p); p += 8; eph.crs = R8(p); p += 8; eph.cic = R8(p); p += 8; eph.cis = R8(p); p += 8; eph.i0 = R8(p); p += 8; eph.idot = R8(p); p += 8; eph.OMG0 = R8(p); p += 8; eph.OMGd = R8(p); p += 8; toc_fnav = U4(p); p += 4; af0_fnav = R8(p); p += 8; af1_fnav = R8(p); p += 8; af2_fnav = R8(p); p += 8; toc_inav = U4(p); p += 4; af0_inav = R8(p); p += 8; af1_inav = R8(p); p += 8; af2_inav = R8(p); p += 8; eph.tgd[0] = R8(p); p += 8; /* BGD: E5A-E1 (s) */ eph.tgd[1] = R8(p); /* BGD: E5B-E1 (s) */ eph.iodc = eph.iode; eph.svh = (svh_e5b << 7) | (dvs_e5b << 6) | (svh_e5a << 4) | (dvs_e5a << 3) | (svh_e1b << 1) | dvs_e1b; eph.code = rcv_fnav ? 1 : 0; /* 0:INAV,1:FNAV */ eph.A = sqrtA * sqrtA; eph.f0 = rcv_fnav ? af0_fnav : af0_inav; eph.f1 = rcv_fnav ? af1_fnav : af1_inav; eph.f2 = rcv_fnav ? af2_fnav : af2_inav; if (raw->outtype) { msg = raw->msgtype + strlen(raw->msgtype); sprintf(msg, " prn=%3d iod=%3d toes=%6.0f", prn, eph.iode, eph.toes); } if (!(eph.sat = satno(SYS_GAL, prn))) { trace(2, "oemv galephemeris satellite error: prn=%d\n", prn); return -1; } tow = time2gpst(raw->time, &week); eph.week = week; /* gps week */ eph.toe = gpst2time(eph.week, eph.toes); /* for week-handover problem */ tt = timediff(eph.toe, raw->time); if (tt < -302400.0) { eph.week++; } else if (tt > 302400.0) { eph.week--; } eph.toe = gpst2time(eph.week, eph.toes); eph.toc = adjweek(eph.toe, rcv_fnav ? toc_fnav : toc_inav); eph.ttr = adjweek(eph.toe, tow); if (!strstr(raw->opt, "-EPHALL")) { if (raw->nav.eph[eph.sat - 1].iode == eph.iode && raw->nav.eph[eph.sat - 1].code == eph.code) { return 0; /* unchanged */ } } raw->nav.eph[eph.sat - 1] = eph; raw->ephsat = eph.sat; return 2; } ///* decode galalmanacb ///--------------------------------------------------------*/ static int decode_galalmanacb(raw_t* raw) { alm_t alm = {0}; unsigned char* p = raw->buff + OEM4HLEN; double dsqrtA = 0.0; double sqrtA = sqrt(29601297.0); int prn = 0; int rcv_fnav = 0; int rcv_inav = 0; int svh_e1b = 0; int svh_e5a = 0; int svh_e5b = 0; int ioda = 0; trace(3, "decode_galalmanacb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 100) { trace(2, "oem4 galephemrisb length error: len=%d\n", raw->len); return -1; } prn = U4(p); p += 4; rcv_fnav = U4(p) & 1; (void)rcv_fnav; p += 4; rcv_inav = U4(p) & 1; (void)rcv_inav; p += 4; svh_e1b = U1(p) & 3; p += 1; svh_e5a = U1(p) & 3; p += 1; svh_e5b = U1(p) & 3; p += 1 + 1; ioda = U4(p); (void)ioda; p += 4; alm.week = U4(p); p += 4; /* gst week */ alm.toas = U4(p); p += 4; alm.e = R8(p); p += 8; alm.OMGd = R8(p); p += 8; alm.OMG0 = R8(p); p += 8; alm.omg = R8(p); p += 8; alm.M0 = R8(p); p += 8; alm.f0 = R8(p); p += 8; alm.f1 = R8(p); p += 8; dsqrtA = R8(p); p += 8; alm.i0 = (R8(p) + 56.0) * D2R; alm.svh = (svh_e5b << 7) | (svh_e5a << 4) | (svh_e1b << 1); alm.A = (sqrtA + dsqrtA) * (sqrtA + dsqrtA); if (!(alm.sat = satno(SYS_GAL, prn))) { trace(2, "oemv galalmanac satellite error: prn=%d\n", prn); return -1; } alm.toa = gst2time(alm.week, alm.toas); raw->nav.alm[alm.sat - 1] = alm; return 0; } ///* decode galclockb ///----------------------------------------------------------*/ static int decode_galclockb(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; double a0 = 0.0; double a1 = 0.0; //double a0g = 0.0; //double a1g = 0.0; //int leaps = 0; int tot = 0; int wnt = 0; //int wnlsf = 0; //int dn = 0; //int dtlsf = 0; //int t0g = 0; //int wn0g = 0; trace(3, "decode_galclockb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 64) { trace(2, "oem4 galclockb length error: len=%d\n", raw->len); return -1; } a0 = R8(p); p += 8; a1 = R8(p); p += 8; //leaps = I4(p); I4(p); p += 4; tot = U4(p); p += 4; wnt = U4(p); p += 4; //wnlsf = U4(p); U4(p); p += 4; //dn = U4(p); U4(p); p += 4; //dtlsf = U4(p); U4(p); p += 4; //a0g = R8(p); R8(p); p += 8; //a1g = R8(p); R8(p); p += 8; //t0g = U4(p); U4(p); p += 4; //wn0g = U4(p); U4(p); raw->nav.utc_gal[0] = a0; raw->nav.utc_gal[1] = a1; raw->nav.utc_gal[2] = tot; /* utc reference tow (s) */ raw->nav.utc_gal[3] = wnt; /* utc reference week */ return 9; } ///* decode galionob ///-----------------------------------------------------------*/ static int decode_galionob(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; double ai[3]; int i = 0; int sf[5]; trace(3, "decode_galionob: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 29) { trace(2, "oem4 galionob length error: len=%d\n", raw->len); return -1; } ai[0] = R8(p); p += 8; ai[1] = R8(p); p += 8; ai[2] = R8(p); p += 8; sf[0] = U1(p); p += 1; sf[1] = U1(p); p += 1; sf[2] = U1(p); p += 1; sf[3] = U1(p); p += 1; sf[4] = U1(p); (void)sf; for (i = 0; i < 3; ++i) { raw->nav.ion_gal[i] = ai[i]; } return 9; } ///* decode galfnavrawpageb ///----------------------------------------------------*/ static int decode_galfnavrawpageb(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; unsigned char buff[27]; int i = 0; //int sigch = 0; int satid = 0; int page = 0; trace(3, "decode_galfnavrawpageb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 35) { trace(2, "oem4 galfnavrawpageb length error: len=%d\n", raw->len); return -1; } //sigch = U4(p); U4(p); p += 4; satid = U4(p); p += 4; for (i = 0; i < 27; ++i) { buff[i] = U1(p); p += 1; } page = getbitu(buff, 0, 6); trace(3, "%s E%2d FNAV (%2d) ", time_str(raw->time, 0), satid, page); traceb(3, buff, 27); return 0; } ///* decode galinavrawwordb ///----------------------------------------------------*/ static int decode_galinavrawwordb(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; unsigned char buff[16]; gtime_t time = raw->time; char* sig = NULL; int i = 0; //int sigch = 0; int satid = 0; int sigtype = 0; int type = 0; int week = 0; int tow = 0; trace(3, "decode_galinavrawwordb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 28) { trace(2, "oem4 galinavrawwordb length error: len=%d\n", raw->len); return -1; } //sigch = U4(p); U4(p); p += 4; satid = U4(p); p += 4; sigtype = U4(p); p += 4; switch (sigtype) { case 10433: sig = "E1 "; break; case 10466: sig = "E5A"; break; case 10499: sig = "E5B"; break; default: sig = "???"; break; } for (i = 0; i < 16; ++i) { buff[i] = U1(p); p += 1; } type = getbitu(buff, 0, 6); if (type == 0 && getbitu(buff, 6, 2) == 2) { week = getbitu(buff, 96, 12); /* gst week */ tow = getbitu(buff, 108, 20); time = gst2time(week, tow); } trace(3, "%s E%2d INAV-%s (%2d) ", time_str(time, 0), satid, sig, type); traceb(3, buff, 16); return 0; } ///* decode rawcnavframeb ///------------------------------------------------------*/ static int decode_rawcnavframeb(raw_t* raw) { unsigned char* p = raw->buff + OEM4HLEN; unsigned char buff[38]; int i = 0; int sigch = 0; int prn = 0; int frmid = 0; trace(3, "decode_rawcnavframeb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 50) { trace(2, "oem4 rawcnavframeb length error: len=%d\n", raw->len); return -1; } sigch = U4(p); (void)sigch; p += 4; prn = U4(p); p += 4; frmid = U4(p); p += 4; for (i = 0; i < 38; ++i) { buff[i] = U1(p); p += 1; } trace(3, "%s PRN=%3d FRMID=%2d ", time_str(raw->time, 0), prn, frmid); traceb(3, buff, 38); return 0; } ///* decode bdsephemerisb ///------------------------------------------------------*/ static int decode_bdsephemerisb(raw_t* raw) { eph_t eph = {0}; unsigned char* p = raw->buff + OEM4HLEN; double ura = 0.0; double sqrtA = 0.0; char* msg = NULL; int prn = 0; int toc = 0; trace(3, "decode_bdsephemerisb: len=%d\n", raw->len); if (raw->len < OEM4HLEN + 196) { trace(2, "oem4 bdsephemrisb length error: len=%d\n", raw->len); return -1; } prn = U4(p); p += 4; eph.week = U4(p); p += 4; ura = R8(p); p += 8; eph.svh = U4(p) & 1; p += 4; eph.tgd[0] = R8(p); p += 8; /* TGD1 for B1 (s) */ eph.tgd[1] = R8(p); p += 8; /* TGD2 for B2 (s) */ eph.iodc = U4(p); p += 4; /* AODC */ toc = U4(p); p += 4; eph.f0 = R8(p); p += 8; eph.f1 = R8(p); p += 8; eph.f2 = R8(p); p += 8; eph.iode = U4(p); p += 4; /* AODE */ eph.toes = U4(p); p += 4; sqrtA = R8(p); p += 8; eph.e = R8(p); p += 8; eph.omg = R8(p); p += 8; eph.deln = R8(p); p += 8; eph.M0 = R8(p); p += 8; eph.OMG0 = R8(p); p += 8; eph.OMGd = R8(p); p += 8; eph.i0 = R8(p); p += 8; eph.idot = R8(p); p += 8; eph.cuc = R8(p); p += 8; eph.cus = R8(p); p += 8; eph.crc = R8(p); p += 8; eph.crs = R8(p); p += 8; eph.cic = R8(p); p += 8; eph.cis = R8(p); eph.A = sqrtA * sqrtA; eph.sva = uraindex(ura); if (raw->outtype) { msg = raw->msgtype + strlen(raw->msgtype); sprintf(msg, " prn=%3d iod=%3d toes=%6.0f", prn, eph.iode, eph.toes); } if (!(eph.sat = satno(SYS_CMP, prn))) { trace(2, "oemv bdsephemeris satellite error: prn=%d\n", prn); return -1; } eph.toe = bdt2gpst(bdt2time(eph.week, eph.toes)); /* bdt -> gpst */ eph.toc = bdt2gpst(bdt2time(eph.week, toc)); /* bdt -> gpst */ eph.ttr = raw->time; if (!strstr(raw->opt, "-EPHALL")) { if (timediff(raw->nav.eph[eph.sat - 1].toe, eph.toe) == 0.0) { return 0; /* unchanged */ } } raw->nav.eph[eph.sat - 1] = eph; raw->ephsat = eph.sat; return 2; } ///* decode rgeb ///---------------------------------------------------------------*/ static int decode_rgeb(raw_t* raw) { unsigned char* p = raw->buff + OEM3HLEN; double tow = 0.0; double psr = 0.0; double adr = 0.0; double tt = 0.0; double lockt = 0.0; double dop = 0.0; double snr = 0.0; int i = 0; int week = 0; int nobs = 0; int prn = 0; int sat = 0; int stat = 0; int sys = 0; int parity = 0; int lli = 0; int index = 0; int freq = 0; trace(3, "decode_rgeb: len=%d\n", raw->len); week = adjgpsweek(U4(p)); tow = R8(p + 4); nobs = U4(p + 12); raw->time = gpst2time(week, tow); if (raw->len != OEM3HLEN + 20 + nobs * 44) { trace(2, "oem3 regb length error: len=%d nobs=%d\n", raw->len, nobs); return -1; } for (i = 0, p += 20; i < nobs; ++i, p += 44) { prn = U4(p); psr = R8(p + 4); adr = R8(p + 16); dop = R4(p + 28); snr = R4(p + 32); lockt = R4(p + 36); /* lock time (s) */ stat = I4(p + 40); /* tracking status */ freq = (stat >> 20) & 1; /* L1:0,L2:1 */ sys = (stat >> 15) & 7; /* satellite sys (0:GPS,1:GLONASS,2:WAAS) */ parity = (stat >> 10) & 1; /* parity known */ if (!(sat = satno(sys == 1 ? SYS_GLO : (sys == 2 ? SYS_SBS : SYS_GPS), prn))) { trace(2, "oem3 regb satellite number error: sys=%d prn=%d\n", sys, prn); continue; } tt = timediff(raw->time, raw->tobs); if (raw->tobs.time != 0) { lli = lockt - raw->lockt[sat - 1][freq] + 0.05 < tt || parity != raw->halfc[sat - 1][freq]; } else { lli = 0; } if (!parity) { lli |= 2; } raw->lockt[sat - 1][freq] = lockt; raw->halfc[sat - 1][freq] = parity; if (fabs(timediff(raw->obs.data[0].time, raw->time)) > 1E-9) { raw->obs.n = 0; } if ((index = obsindex(&raw->obs, raw->time, sat)) >= 0) { raw->obs.data[index].L[freq] = -adr; /* flip sign */ raw->obs.data[index].P[freq] = psr; raw->obs.data[index].D[freq] = (float)dop; raw->obs.data[index].SNR[freq] = 0.0 <= snr && snr < 255.0 ? (unsigned char)(snr * 4.0 + 0.5) : 0; raw->obs.data[index].LLI[freq] = (unsigned char)lli; raw->obs.data[index].code[freq] = freq == 0 ? CODE_L1C : CODE_L2P; } } raw->tobs = raw->time; return 1; } ///* decode rged ///---------------------------------------------------------------*/ static int decode_rged(raw_t* raw) { unsigned int word = 0; unsigned char* p = raw->buff + OEM3HLEN; double tow = 0.0; double psrh = 0.0; double psrl = 0.0; double psr = 0.0; double adr = 0.0; double adr_rolls = 0.0; double tt = 0.0; double lockt = 0.0; double dop = 0.0; int i = 0; int week = 0; int nobs = 0; int prn = 0; int sat = 0; int stat = 0; int sys = 0; int parity = 0; int lli = 0; int index = 0; int freq = 0; int snr = 0; trace(3, "decode_rged: len=%d\n", raw->len); nobs = U2(p); week = adjgpsweek(U2(p + 2)); tow = U4(p + 4) / 100.0; raw->time = gpst2time(week, tow); if (raw->len != OEM3HLEN + 12 + nobs * 20) { trace(2, "oem3 regd length error: len=%d nobs=%d\n", raw->len, nobs); return -1; } for (i = 0, p += 12; i < nobs; ++i, p += 20) { word = U4(p); prn = word & 0x3F; snr = ((word >> 6) & 0x1F) + 20; lockt = (word >> 11) / 32.0; adr = -I4(p + 4) / 256.0; word = U4(p + 8); psrh = word & 0xF; dop = exsign(word >> 4, 28) / 256.0; psrl = U4(p + 12); stat = U4(p + 16) >> 8; freq = (stat >> 20) & 1; /* L1:0,L2:1 */ sys = (stat >> 15) & 7; /* satellite sys (0:GPS,1:GLONASS,2:WAAS) */ parity = (stat >> 10) & 1; /* parity known */ if (!(sat = satno(sys == 1 ? SYS_GLO : (sys == 2 ? SYS_SBS : SYS_GPS), prn))) { trace(2, "oem3 regd satellite number error: sys=%d prn=%d\n", sys, prn); continue; } tt = timediff(raw->time, raw->tobs); psr = (psrh * 4294967296.0 + psrl) / 128.0; adr_rolls = floor((psr / (freq == 0 ? WL1 : WL2) - adr) / MAXVAL + 0.5); adr = adr + MAXVAL * adr_rolls; if (raw->tobs.time != 0) { lli = lockt - raw->lockt[sat - 1][freq] + 0.05 < tt || parity != raw->halfc[sat - 1][freq]; } else { lli = 0; } if (!parity) { lli |= 2; } raw->lockt[sat - 1][freq] = lockt; raw->halfc[sat - 1][freq] = parity; if (fabs(timediff(raw->obs.data[0].time, raw->time)) > 1E-9) { raw->obs.n = 0; } if ((index = obsindex(&raw->obs, raw->time, sat)) >= 0) { raw->obs.data[index].L[freq] = adr; raw->obs.data[index].P[freq] = psr; raw->obs.data[index].D[freq] = (float)dop; raw->obs.data[index].SNR[freq] = (unsigned char)(snr * 4.0 + 0.5); raw->obs.data[index].LLI[freq] = (unsigned char)lli; raw->obs.data[index].code[freq] = freq == 0 ? CODE_L1C : CODE_L2P; } } raw->tobs = raw->time; return 1; } ///* decode repb ///---------------------------------------------------------------*/ static int decode_repb(raw_t* raw) { unsigned char* p = raw->buff + OEM3HLEN; eph_t eph = {0}; int prn = 0; int sat = 0; trace(3, "decode_repb: len=%d\n", raw->len); if (raw->len != OEM3HLEN + 96) { trace(2, "oem3 repb length error: len=%d\n", raw->len); return -1; } prn = U4(p); if (!(sat = satno(SYS_GPS, prn))) { trace(2, "oem3 repb satellite number error: prn=%d\n", prn); return -1; } if (decode_frame(p + 4, &eph, NULL, NULL, NULL, NULL) != 1 || decode_frame(p + 34, &eph, NULL, NULL, NULL, NULL) != 2 || decode_frame(p + 64, &eph, NULL, NULL, NULL, NULL) != 3) { trace(2, "oem3 repb subframe error: prn=%d\n", prn); return -1; } if (!strstr(raw->opt, "-EPHALL")) { if (eph.iode == raw->nav.eph[sat - 1].iode) { return 0; /* unchanged */ } } eph.sat = sat; raw->nav.eph[sat - 1] = eph; raw->ephsat = sat; return 2; } ///* decode frmb ///--------------------------------------------------------------*/ static int decode_frmb(raw_t* raw) { unsigned char* p = raw->buff + OEM3HLEN; double tow = 0.0; int i = 0; int week = 0; int prn = 0; int nbit = 0; trace(3, "decode_frmb: len=%d\n", raw->len); week = adjgpsweek(U4(p)); tow = R8(p + 4); prn = U4(p + 12); nbit = U4(p + 20); raw->time = gpst2time(week, tow); if (nbit != 250) { return 0; } if (prn < MINPRNSBS || MAXPRNSBS < prn) { trace(2, "oem3 frmb satellite number error: prn=%d\n", prn); return -1; } raw->sbsmsg.week = week; raw->sbsmsg.tow = (int)tow; raw->sbsmsg.prn = prn; for (i = 0; i < 29; ++i) { raw->sbsmsg.msg[i] = p[24 + i]; } return 3; } ///* decode ionb ///---------------------------------------------------------------*/ static int decode_ionb(raw_t* raw) { unsigned char* p = raw->buff + OEM3HLEN; int i = 0; if (raw->len != 64 + OEM3HLEN) { trace(2, "oem3 ionb length error: len=%d\n", raw->len); return -1; } for (i = 0; i < 8; ++i) { raw->nav.ion_gps[i] = R8(p + i * 8); } return 9; } ///* decode utcb ///---------------------------------------------------------------*/ static int decode_utcb(raw_t* raw) { unsigned char* p = raw->buff + OEM3HLEN; trace(3, "decode_utcb: len=%d\n", raw->len); if (raw->len != 40 + OEM3HLEN) { trace(2, "oem3 utcb length error: len=%d\n", raw->len); return -1; } raw->nav.utc_gps[0] = R8(p); raw->nav.utc_gps[1] = R8(p + 8); raw->nav.utc_gps[2] = U4(p + 16); raw->nav.utc_gps[3] = adjgpsweek(U4(p + 20)); raw->nav.leaps = I4(p + 28); return 9; } /* decode oem4 message -------------------------------------------------------*/ static int decode_oem4(raw_t* raw) { double tow = 0.0; int msg = 0; int week = 0; int type = U2(raw->buff + 4); trace(3, "decode_oem4: type=%3d len=%d\n", type, raw->len); /* check crc32 */ // printf("before crc23\n"); // if (crc32(raw->buff,raw->len)!=U4(raw->buff+raw->len)) { // printf("check crc23 failed\n"); // trace(2,"oem4 crc error: type=%3d len=%d\n",type,raw->len); // printf("check crc error: type=%3d len=%d\n", type, raw->len); // return -1; // } msg = (U1(raw->buff + 6) >> 4) & 0x3; week = adjgpsweek(U2(raw->buff + 14)); tow = U4(raw->buff + 16) * 0.001; raw->time = gpst2time(week, tow); if (raw->outtype) { sprintf(raw->msgtype, "OEM4 %4d (%4d): msg=%d %s", type, raw->len, msg, time_str(gpst2time(week, tow), 2)); } if (msg != 0) { return 0; /* message type: 0=binary,1=ascii */ } switch (type) { case ID_RANGECMP: return decode_rangecmpb(raw); case ID_RANGE: return decode_rangeb(raw); case ID_RAWEPHEM: return decode_rawephemb(raw); case ID_RAWWAASFRAME: return decode_rawwaasframeb(raw); case ID_RAWSBASFRAME: return decode_rawsbasframeb(raw); case ID_IONUTC: return decode_ionutcb(raw); case ID_GLOEPHEMERIS: return decode_gloephemerisb(raw); case ID_QZSSRAWEPHEM: return decode_qzssrawephemb(raw); case ID_QZSSRAWSUBFRAME: return decode_qzssrawsubframeb(raw); case ID_QZSSIONUTC: return decode_qzssionutcb(raw); case ID_GALEPHEMERIS: return decode_galephemerisb(raw); case ID_GALALMANAC: return decode_galalmanacb(raw); case ID_GALCLOCK: return decode_galclockb(raw); case ID_GALIONO: return decode_galionob(raw); case ID_GALFNAVRAWPAGE: return decode_galfnavrawpageb(raw); case ID_GALINAVRAWWORD: return decode_galinavrawwordb(raw); case ID_RAWCNAVFRAME: return decode_rawcnavframeb(raw); case ID_BDSEPHEMERIS: return decode_bdsephemerisb(raw); } return 0; } /* decode oem3 message -------------------------------------------------------*/ static int decode_oem3(raw_t* raw) { int type = U4(raw->buff + 4); trace(3, "decode_oem3: type=%3d len=%d\n", type, raw->len); /* checksum */ if (chksum(raw->buff, raw->len)) { trace(2, "oem3 checksum error: type=%3d len=%d\n", type, raw->len); return -1; } if (raw->outtype) { sprintf(raw->msgtype, "OEM3 %4d (%4d):", type, raw->len); } switch (type) { case ID_RGEB: return decode_rgeb(raw); case ID_RGED: return decode_rged(raw); case ID_REPB: return decode_repb(raw); case ID_FRMB: return decode_frmb(raw); case ID_IONB: return decode_ionb(raw); case ID_UTCB: return decode_utcb(raw); } return 0; } /* sync header ---------------------------------------------------------------*/ static int sync_oem4(unsigned char* buff, unsigned char data) { buff[0] = buff[1]; buff[1] = buff[2]; buff[2] = data; return buff[0] == OEM4SYNC1 && buff[1] == OEM4SYNC2 && buff[2] == OEM4SYNC3; } static int sync_oem3(unsigned char* buff, unsigned char data) { buff[0] = buff[1]; buff[1] = buff[2]; buff[2] = data; return buff[0] == OEM3SYNC1 && buff[1] == OEM3SYNC2 && buff[2] == OEM3SYNC3; } /* input oem4/oem3 raw data from stream ---------------------------------------- * fetch next novatel oem4/oem3 raw data and input a mesasge from stream * args : raw_t *raw IO receiver raw data control struct * unsigned char data I stream data (1 byte) * return : status (-1: error message, 0: no message, 1: input observation data, * 2: input ephemeris, 3: input sbas message, * 9: input ion/utc parameter) * * notes : to specify input options for oem4, set raw->opt to the following * option strings separated by spaces. * * -EPHALL : input all ephemerides * -GL1P : select 1P for GPS L1 (default 1C) * -GL2X : select 2X for GPS L2 (default 2W) * -RL2C : select 2C for GLO L2 (default 2P) * -EL2C : select 2C for GAL L2 (default 2C) * *-----------------------------------------------------------------------------*/ extern int input_oem4(raw_t* raw, unsigned char data) { trace(5, "input_oem4: data=%02x\n", data); /* synchronize frame */ if (raw->nbyte == 0) { if (sync_oem4(raw->buff, data)) { raw->nbyte = 3; } return 0; } raw->buff[raw->nbyte++] = data; if (raw->nbyte == 10 && (raw->len = U2(raw->buff + 8) + OEM4HLEN) > MAXRAWLEN - 4) { trace(2, "oem4 length error: len=%d\n", raw->len); raw->nbyte = 0; return -1; } if (raw->nbyte < 10 || raw->nbyte < raw->len + 4) { return 0; } raw->nbyte = 0; /* decode oem4 message */ return decode_oem4(raw); } extern int input_oem3(raw_t* raw, unsigned char data) { trace(5, "input_oem3: data=%02x\n", data); /* synchronize frame */ if (raw->nbyte == 0) { if (sync_oem3(raw->buff, data)) { raw->nbyte = 3; } return 0; } raw->buff[raw->nbyte++] = data; if (raw->nbyte == 12 && (raw->len = U4(raw->buff + 8)) > MAXRAWLEN) { trace(2, "oem3 length error: len=%d\n", raw->len); raw->nbyte = 0; return -1; } if (raw->nbyte < 12 || raw->nbyte < raw->len) { return 0; } raw->nbyte = 0; /* decode oem3 message */ return decode_oem3(raw); } ///* input oem4/oem3 raw data from file ///------------------------------------------ //* fetch next novatel oem4/oem3 raw data and input a message from file //* args : raw_t *raw IO receiver raw data control struct //* int format I receiver raw data format (STRFMT_???) //* FILE *fp I file pointer //* return : status(-2: end of file, -1...9: same as above) //*-----------------------------------------------------------------------------*/ extern int input_oem4f(raw_t* raw, FILE* fp) { int i = 0; int data = 0; trace(4, "input_oem4f:\n"); /* synchronize frame */ if (raw->nbyte == 0) { for (i = 0;; ++i) { if ((data = fgetc(fp)) == EOF) { return -2; } if (sync_oem4(raw->buff, (unsigned char)data)) { break; } if (i >= 4096) { return 0; } } } if (fread(raw->buff + 3, 7, 1, fp) < 1) { return -2; } raw->nbyte = 10; if ((raw->len = U2(raw->buff + 8) + OEM4HLEN) > MAXRAWLEN - 4) { trace(2, "oem4 length error: len=%d\n", raw->len); raw->nbyte = 0; return -1; } if (fread(raw->buff + 10, raw->len - 6, 1, fp) < 1) { return -2; } raw->nbyte = 0; /* decode oem4 message */ return decode_oem4(raw); } extern int input_oem3f(raw_t* raw, FILE* fp) { int i = 0; int data = 0; trace(4, "input_oem3f:\n"); /* synchronize frame */ if (raw->nbyte == 0) { for (i = 0;; ++i) { if ((data = fgetc(fp)) == EOF) { return -2; } if (sync_oem3(raw->buff, (unsigned char)data)) { break; } if (i >= 4096) { return 0; } } } if (fread(raw->buff + 3, 1, 9, fp) < 9) { return -2; } raw->nbyte = 12; if ((raw->len = U4(raw->buff + 8)) > MAXRAWLEN) { trace(2, "oem3 length error: len=%d\n", raw->len); raw->nbyte = 0; return -1; } if (fread(raw->buff + 12, 1, raw->len - 12, fp) < (size_t)(raw->len - 12)) { return -2; } raw->nbyte = 0; /* decode oem3 message */ return decode_oem3(raw); }
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/rtklib/rtcm3.c
/********************************************************************************* * The RTKLIB software package is distributed under the following BSD 2-clause * license (http://opensource.org/licenses/BSD-2-Clause) and additional two * exclusive clauses. Users are permitted to develop, produce or sell their own * non-commercial or commercial products utilizing, linking or including RTKLIB *as long as they comply with the license. * * Copyright (c) 2007-2013, T. Takasu, 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. * * - The software package includes some companion executive binaries or shared * libraries necessary to execute APs on Windows. These licenses succeed to *the original ones of these software. * * 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 HOLDER 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. ***********************************************************************************/ /*------------------------------------------------------------------------------ * rtcm3.c : rtcm ver.3 message decorder functions * * Copyright (C) 2009-2015 by T.TAKASU, All rights reserved. * * options : * -DSSR_QZSS_DRAFT_V05: qzss ssr messages based on ref [16] * * references : * see rtcm.c * * version : $Revision:$ $Date:$ * history : 2012/05/14 1.0 separated from rtcm.c * 2012/12/12 1.1 support gal/qzs ephemeris, gal/qzs ssr, msm * add station id consistency test for obs data * 2012/12/25 1.2 change compass msm id table * 2013/01/31 1.3 change signal id by the latest draft (ref [13]) * 2013/02/23 1.4 change reference for rtcm 3 message (ref [14]) * 2013/05/19 1.5 gpst -> bdt of time-tag in beidou msm message * 2014/05/02 1.6 fix bug on dropping last field of ssr message * comply with rtcm 3.2 with amendment 1/2 (ref[15]) * delete MT 1046 according to ref [15] * 2014/09/14 1.7 add receiver option -RT_INP * 2014/12/06 1.8 support SBAS/BeiDou SSR messages (ref [16]) * 2015/03/22 1.9 add handling of iodcrc for beidou/sbas ssr messages *-----------------------------------------------------------------------------*/ /** * file: rtcm3.c * version: rtklib ver.2.4.2 * Copy from * https://github.com/tomojitakasu/RTKLIB/tree/76b9c97257f304aedad38b5a6bbbac444724aab3/src/rtcm3.c */ #include "rtklib.h" /* static const char rcsid[] = "$Id:$"; */ /* constants -----------------------------------------------------------------*/ #define PRUNIT_GPS 299792.458 /* rtcm ver.3 unit of gps pseudorange (m) */ #define PRUNIT_GLO 599584.916 /* rtcm ver.3 unit of glonass pseudorange (m) */ #define RANGE_MS (CLIGHT * 0.001) /* range in 1 ms */ #define P2_10 0.0009765625 /* 2^-10 */ #define P2_34 5.820766091346740E-11 /* 2^-34 */ #define P2_46 1.421085471520200E-14 /* 2^-46 */ #define P2_59 1.734723475976810E-18 /* 2^-59 */ /* type definition -----------------------------------------------------------*/ typedef struct { /* multi-signal-message header type */ unsigned char iod; /* issue of data station */ unsigned char time_s; /* cumulative session transmitting time */ unsigned char clk_str; /* clock steering indicator */ unsigned char clk_ext; /* external clock indicator */ unsigned char smooth; /* divergence free smoothing indicator */ unsigned char tint_s; /* soothing interval */ unsigned char nsat, nsig; /* number of satellites/signals */ unsigned char sats[64]; /* satellites */ unsigned char sigs[32]; /* signals */ unsigned char cellmask[64]; /* cell mask */ } msm_h_t; /* msm signal id table -------------------------------------------------------*/ const char* msm_sig_gps[32] = { /* GPS: ref [13] table 3.5-87, ref [14][15] table 3.5-91 */ "", "1C", "1P", "1W", "1Y", "1M", "", "2C", "2P", "2W", "2Y", "2M", /* 1-12 */ "", "", "2S", "2L", "2X", "", "", "", "", "5I", "5Q", "5X", /* 13-24 */ "", "", "", "", "", "1S", "1L", "1X" /* 25-32 */ }; const char* msm_sig_glo[32] = { /* GLONASS: ref [13] table 3.5-93, ref [14][15] table 3.5-97 */ "", "1C", "1P", "", "", "", "", "2C", "2P", "", "3I", "3Q", "3X", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""}; const char* msm_sig_gal[32] = { /* Galileo: ref [15] table 3.5-100 */ "", "1C", "1A", "1B", "1X", "1Z", "", "6C", "6A", "6B", "6X", "6Z", "", "7I", "7Q", "7X", "", "8I", "8Q", "8X", "", "5I", "5Q", "5X", "", "", "", "", "", "", "", ""}; const char* msm_sig_qzs[32] = { /* QZSS: ref [15] table 3.5-103 */ "", "1C", "", "", "", "", "", "", "6S", "6L", "6X", "", "", "", "2S", "2L", "2X", "", "", "", "", "5I", "5Q", "5X", "", "", "", "", "", "1S", "1L", "1X"}; const char* msm_sig_sbs[32] = { /* SBAS: ref [13] table 3.5-T+005 */ "", "1C", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "5I", "5Q", "5X", "", "", "", "", "", "", "", ""}; const char* msm_sig_cmp[32] = { /* BeiDou: ref [15] table 3.5-106 */ "", "1I", "1Q", "1X", "", "", "", "6I", "6Q", "6X", "", "", "", "7I", "7Q", "7X", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""}; /* ssr update intervals ------------------------------------------------------*/ static const double ssrudint[16] = { 1, 2, 5, 10, 15, 30, 60, 120, 240, 300, 600, 900, 1800, 3600, 7200, 10800}; /* get sign-magnitude bits ---------------------------------------------------*/ static double getbitg(const unsigned char* buff, int pos, int len) { double value = getbitu(buff, pos + 1, len - 1); return getbitu(buff, pos, 1) ? -value : value; } /* adjust weekly rollover of gps time ----------------------------------------*/ static void adjweek(rtcm_t* rtcm, double tow) { double tow_p; int week; /* if no time, get cpu time */ if (rtcm->time.time == 0) { rtcm->time = utc2gpst(timeget()); } tow_p = time2gpst(rtcm->time, &week); if (tow < tow_p - 302400.0) { tow += 604800.0; } else if (tow > tow_p + 302400.0) { tow -= 604800.0; } rtcm->time = gpst2time(week, tow); } /* adjust weekly rollover of bdt time ----------------------------------------*/ static int adjbdtweek(int week) { int w; (void)time2bdt(gpst2bdt(utc2gpst(timeget())), &w); if (w < 1) { w = 1; /* use 2006/1/1 if time is earlier than 2006/1/1 */ } return week + (w - week + 512) / 1024 * 1024; } /* adjust daily rollover of glonass time -------------------------------------*/ static void adjday_glot(rtcm_t* rtcm, double tod) { gtime_t time; double tow, tod_p; int week; if (rtcm->time.time == 0) { rtcm->time = utc2gpst(timeget()); } time = timeadd(gpst2utc(rtcm->time), 10800.0); /* glonass time */ tow = time2gpst(time, &week); tod_p = fmod(tow, 86400.0); tow -= tod_p; if (tod < tod_p - 43200.0) { tod += 86400.0; } else if (tod > tod_p + 43200.0) { tod -= 86400.0; } time = gpst2time(week, tow + tod); rtcm->time = utc2gpst(timeadd(time, -10800.0)); } /* adjust carrier-phase rollover ---------------------------------------------*/ static double adjcp(rtcm_t* rtcm, int sat, int freq, double cp) { if (rtcm->cp[sat - 1][freq] == 0.0) { ; } else if (cp < rtcm->cp[sat - 1][freq] - 750.0) { cp += 1500.0; } else if (cp > rtcm->cp[sat - 1][freq] + 750.0) { cp -= 1500.0; } rtcm->cp[sat - 1][freq] = cp; return cp; } /* loss-of-lock indicator ----------------------------------------------------*/ static int lossoflock(rtcm_t* rtcm, int sat, int freq, int lock) { int lli = (!lock && !rtcm->lock[sat - 1][freq]) || lock < rtcm->lock[sat - 1][freq]; rtcm->lock[sat - 1][freq] = lock; return lli; } /* s/n ratio -----------------------------------------------------------------*/ static unsigned char snratio(double snr) { return (unsigned char)(snr <= 0.0 || 255.5 <= snr ? 0.0 : snr * 4.0 + 0.5); } /* get observation data index ------------------------------------------------*/ static int obsindex(obs_t* obs, gtime_t time, int sat) { int i, j; for (i = 0; i < obs->n; ++i) { if (obs->data[i].sat == sat) { return i; /* field already exists */ } } if (i >= MAXOBS) { return -1; /* overflow */ } /* add new field */ obs->data[i].time = time; obs->data[i].sat = sat; for (j = 0; j < NFREQ + NEXOBS; ++j) { obs->data[i].L[j] = obs->data[i].P[j] = 0.0; obs->data[i].D[j] = 0.0; obs->data[i].SNR[j] = obs->data[i].LLI[j] = obs->data[i].code[j] = 0; } obs->n++; return i; } /* test station id consistency -----------------------------------------------*/ static int test_staid(rtcm_t* rtcm, int staid) { char* p; int type, id; /* test station id option */ if ((p = strstr(rtcm->opt, "-STA=")) && sscanf(p, "-STA=%d", &id) == 1) { if (staid != id) { return 0; } } /* save station id */ if (rtcm->staid == 0 || rtcm->obsflag) { rtcm->staid = staid; } else if (staid != rtcm->staid) { type = getbitu(rtcm->buff, 24, 12); trace(2, "rtcm3 %d staid invalid id=%d %d\n", type, staid, rtcm->staid); /* reset station id if station id error */ rtcm->staid = 0; return 0; } return 1; } /* decode type 1001-1004 message header --------------------------------------*/ static int decode_head1001(rtcm_t* rtcm, int* sync) { double tow; char* msg; int i = 24, staid, nsat, type; type = getbitu(rtcm->buff, i, 12); i += 12; if (i + 52 <= rtcm->len * 8) { staid = getbitu(rtcm->buff, i, 12); i += 12; tow = getbitu(rtcm->buff, i, 30) * 0.001; i += 30; *sync = getbitu(rtcm->buff, i, 1); i += 1; nsat = getbitu(rtcm->buff, i, 5); } else { trace(2, "rtcm3 %d length error: len=%d\n", type, rtcm->len); return -1; } /* test station id */ if (!test_staid(rtcm, staid)) { return -1; } adjweek(rtcm, tow); trace(4, "decode_head1001: time=%s nsat=%d sync=%d\n", time_str(rtcm->time, 2), nsat, *sync); if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " %s nsat=%2d sync=%d", time_str(rtcm->time, 2), nsat, *sync); } return nsat; } /* decode type 1001: L1-only gps rtk observation -----------------------------*/ static int decode_type1001(rtcm_t* rtcm) { int sync; if (decode_head1001(rtcm, &sync) < 0) { return -1; } rtcm->obsflag = !sync; return sync ? 0 : 1; } /* decode type 1002: extended L1-only gps rtk observables --------------------*/ static int decode_type1002(rtcm_t* rtcm) { double pr1, cnr1, tt, cp1; int i = 24 + 64, j, index, nsat, sync, prn, code, sat, ppr1, lock1, amb, sys; if ((nsat = decode_head1001(rtcm, &sync)) < 0) { return -1; } for (j = 0; j < nsat && rtcm->obs.n < MAXOBS && i + 74 <= rtcm->len * 8; ++j) { prn = getbitu(rtcm->buff, i, 6); i += 6; code = getbitu(rtcm->buff, i, 1); i += 1; pr1 = getbitu(rtcm->buff, i, 24); i += 24; ppr1 = getbits(rtcm->buff, i, 20); i += 20; lock1 = getbitu(rtcm->buff, i, 7); i += 7; amb = getbitu(rtcm->buff, i, 8); i += 8; cnr1 = getbitu(rtcm->buff, i, 8); i += 8; if (prn < 40) { sys = SYS_GPS; } else { sys = SYS_SBS; prn += 80; } if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 1002 satellite number error: prn=%d\n", prn); continue; } tt = timediff(rtcm->obs.data[0].time, rtcm->time); if (rtcm->obsflag || fabs(tt) > 1E-9) { rtcm->obs.n = rtcm->obsflag = 0; } if ((index = obsindex(&rtcm->obs, rtcm->time, sat)) < 0) { continue; } pr1 = pr1 * 0.02 + amb * PRUNIT_GPS; if (ppr1 != (int)0xFFF80000) { rtcm->obs.data[index].P[0] = pr1; cp1 = adjcp(rtcm, sat, 0, ppr1 * 0.0005 / lam_carr[0]); rtcm->obs.data[index].L[0] = pr1 / lam_carr[0] + cp1; } rtcm->obs.data[index].LLI[0] = lossoflock(rtcm, sat, 0, lock1); rtcm->obs.data[index].SNR[0] = snratio(cnr1 * 0.25); rtcm->obs.data[index].code[0] = code ? CODE_L1P : CODE_L1C; } return sync ? 0 : 1; } /* decode type 1003: L1&L2 gps rtk observables -------------------------------*/ static int decode_type1003(rtcm_t* rtcm) { int sync; if (decode_head1001(rtcm, &sync) < 0) { return -1; } rtcm->obsflag = !sync; return sync ? 0 : 1; } /* decode type 1004: extended L1&L2 gps rtk observables ----------------------*/ static int decode_type1004(rtcm_t* rtcm) { const int L2codes[] = {CODE_L2C, CODE_L2P, CODE_L2W, CODE_L2W}; double pr1, cnr1, cnr2, tt, cp1, cp2; int i = 24 + 64, j, index, nsat, sync, prn, sat, code1, code2, pr21, ppr1, ppr2; int lock1, lock2, amb, sys; if ((nsat = decode_head1001(rtcm, &sync)) < 0) { return -1; } for (j = 0; j < nsat && rtcm->obs.n < MAXOBS && i + 125 <= rtcm->len * 8; ++j) { prn = getbitu(rtcm->buff, i, 6); i += 6; code1 = getbitu(rtcm->buff, i, 1); i += 1; pr1 = getbitu(rtcm->buff, i, 24); i += 24; ppr1 = getbits(rtcm->buff, i, 20); i += 20; lock1 = getbitu(rtcm->buff, i, 7); i += 7; amb = getbitu(rtcm->buff, i, 8); i += 8; cnr1 = getbitu(rtcm->buff, i, 8); i += 8; code2 = getbitu(rtcm->buff, i, 2); i += 2; pr21 = getbits(rtcm->buff, i, 14); i += 14; ppr2 = getbits(rtcm->buff, i, 20); i += 20; lock2 = getbitu(rtcm->buff, i, 7); i += 7; cnr2 = getbitu(rtcm->buff, i, 8); i += 8; if (prn < 40) { sys = SYS_GPS; } else { sys = SYS_SBS; prn += 80; } if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 1004 satellite number error: sys=%d prn=%d\n", sys, prn); continue; } tt = timediff(rtcm->obs.data[0].time, rtcm->time); if (rtcm->obsflag || fabs(tt) > 1E-9) { rtcm->obs.n = rtcm->obsflag = 0; } if ((index = obsindex(&rtcm->obs, rtcm->time, sat)) < 0) { continue; } pr1 = pr1 * 0.02 + amb * PRUNIT_GPS; if (ppr1 != (int)0xFFF80000) { rtcm->obs.data[index].P[0] = pr1; cp1 = adjcp(rtcm, sat, 0, ppr1 * 0.0005 / lam_carr[0]); rtcm->obs.data[index].L[0] = pr1 / lam_carr[0] + cp1; } rtcm->obs.data[index].LLI[0] = lossoflock(rtcm, sat, 0, lock1); rtcm->obs.data[index].SNR[0] = snratio(cnr1 * 0.25); rtcm->obs.data[index].code[0] = code1 ? CODE_L1P : CODE_L1C; if (pr21 != (int)0xFFFFE000) { rtcm->obs.data[index].P[1] = pr1 + pr21 * 0.02; } if (ppr2 != (int)0xFFF80000) { cp2 = adjcp(rtcm, sat, 1, ppr2 * 0.0005 / lam_carr[1]); rtcm->obs.data[index].L[1] = pr1 / lam_carr[1] + cp2; } rtcm->obs.data[index].LLI[1] = lossoflock(rtcm, sat, 1, lock2); rtcm->obs.data[index].SNR[1] = snratio(cnr2 * 0.25); rtcm->obs.data[index].code[1] = L2codes[code2]; } rtcm->obsflag = !sync; return sync ? 0 : 1; } /* get signed 38bit field ----------------------------------------------------*/ static double getbits_38(const unsigned char* buff, int pos) { return (double)getbits(buff, pos, 32) * 64.0 + getbitu(buff, pos + 32, 6); } /* decode type 1005: stationary rtk reference station arp --------------------*/ static int decode_type1005(rtcm_t* rtcm) { double rr[3]; char* msg; int i = 24 + 12, j, staid, itrf; if (i + 140 == rtcm->len * 8) { staid = getbitu(rtcm->buff, i, 12); i += 12; itrf = getbitu(rtcm->buff, i, 6); i += 6 + 4; rr[0] = getbits_38(rtcm->buff, i); i += 38 + 2; rr[1] = getbits_38(rtcm->buff, i); i += 38 + 2; rr[2] = getbits_38(rtcm->buff, i); } else { trace(2, "rtcm3 1005 length error: len=%d\n", rtcm->len); return -1; } if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " staid=%4d", staid); } /* test station id */ if (!test_staid(rtcm, staid)) { return -1; } rtcm->sta.deltype = 0; /* xyz */ for (j = 0; j < 3; ++j) { rtcm->sta.pos[j] = rr[j] * 0.0001; rtcm->sta.del[j] = 0.0; } rtcm->sta.hgt = 0.0; rtcm->sta.itrf = itrf; return 5; } /* decode type 1006: stationary rtk reference station arp with height --------*/ static int decode_type1006(rtcm_t* rtcm) { double rr[3], anth; char* msg; int i = 24 + 12, j, staid, itrf; if (i + 156 <= rtcm->len * 8) { staid = getbitu(rtcm->buff, i, 12); i += 12; itrf = getbitu(rtcm->buff, i, 6); i += 6 + 4; rr[0] = getbits_38(rtcm->buff, i); i += 38 + 2; rr[1] = getbits_38(rtcm->buff, i); i += 38 + 2; rr[2] = getbits_38(rtcm->buff, i); i += 38; anth = getbitu(rtcm->buff, i, 16); } else { trace(2, "rtcm3 1006 length error: len=%d\n", rtcm->len); return -1; } if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " staid=%4d", staid); } /* test station id */ if (!test_staid(rtcm, staid)) { return -1; } rtcm->sta.deltype = 1; /* xyz */ for (j = 0; j < 3; ++j) { rtcm->sta.pos[j] = rr[j] * 0.0001; rtcm->sta.del[j] = 0.0; } rtcm->sta.hgt = anth * 0.0001; rtcm->sta.itrf = itrf; return 5; } /* decode type 1007: antenna descriptor --------------------------------------*/ static int decode_type1007(rtcm_t* rtcm) { char des[32] = ""; char* msg; int i = 24 + 12, j, staid, n, setup; n = getbitu(rtcm->buff, i + 12, 8); if (i + 28 + 8 * n <= rtcm->len * 8) { staid = getbitu(rtcm->buff, i, 12); i += 12 + 8; for (j = 0; j < n && j < 31; ++j) { des[j] = (char)getbitu(rtcm->buff, i, 8); i += 8; } setup = getbitu(rtcm->buff, i, 8); } else { trace(2, "rtcm3 1007 length error: len=%d\n", rtcm->len); return -1; } if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " staid=%4d", staid); } /* test station id */ if (!test_staid(rtcm, staid)) { return -1; } strncpy(rtcm->sta.antdes, des, n); rtcm->sta.antdes[n] = '\0'; rtcm->sta.antsetup = setup; rtcm->sta.antsno[0] = '\0'; return 5; } /* decode type 1008: antenna descriptor & serial number ----------------------*/ static int decode_type1008(rtcm_t* rtcm) { char des[32] = "", sno[32] = ""; char* msg; int i = 24 + 12, j, staid, n, m, setup; n = getbitu(rtcm->buff, i + 12, 8); m = getbitu(rtcm->buff, i + 28 + 8 * n, 8); if (i + 36 + 8 * (n + m) <= rtcm->len * 8) { staid = getbitu(rtcm->buff, i, 12); i += 12 + 8; for (j = 0; j < n && j < 31; ++j) { des[j] = (char)getbitu(rtcm->buff, i, 8); i += 8; } setup = getbitu(rtcm->buff, i, 8); i += 8 + 8; for (j = 0; j < m && j < 31; ++j) { sno[j] = (char)getbitu(rtcm->buff, i, 8); i += 8; } } else { trace(2, "rtcm3 1008 length error: len=%d\n", rtcm->len); return -1; } if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " staid=%4d", staid); } /* test station id */ if (!test_staid(rtcm, staid)) { return -1; } strncpy(rtcm->sta.antdes, des, n); rtcm->sta.antdes[n] = '\0'; rtcm->sta.antsetup = setup; strncpy(rtcm->sta.antsno, sno, m); rtcm->sta.antsno[m] = '\0'; return 5; } /* decode type 1009-1012 message header --------------------------------------*/ static int decode_head1009(rtcm_t* rtcm, int* sync) { double tod; char* msg; int i = 24, staid, nsat, type; type = getbitu(rtcm->buff, i, 12); i += 12; if (i + 49 <= rtcm->len * 8) { staid = getbitu(rtcm->buff, i, 12); i += 12; tod = getbitu(rtcm->buff, i, 27) * 0.001; i += 27; /* sec in a day */ *sync = getbitu(rtcm->buff, i, 1); i += 1; nsat = getbitu(rtcm->buff, i, 5); } else { trace(2, "rtcm3 %d length error: len=%d\n", type, rtcm->len); return -1; } /* test station id */ if (!test_staid(rtcm, staid)) { return -1; } adjday_glot(rtcm, tod); trace(4, "decode_head1009: time=%s nsat=%d sync=%d\n", time_str(rtcm->time, 2), nsat, *sync); if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " %s nsat=%2d sync=%d", time_str(rtcm->time, 2), nsat, *sync); } return nsat; } /* decode type 1009: L1-only glonass rtk observables -------------------------*/ static int decode_type1009(rtcm_t* rtcm) { int sync; if (decode_head1009(rtcm, &sync) < 0) { return -1; } rtcm->obsflag = !sync; return sync ? 0 : 1; } /* decode type 1010: extended L1-only glonass rtk observables ----------------*/ static int decode_type1010(rtcm_t* rtcm) { double pr1, cnr1, tt, cp1, lam1; int i = 24 + 61, j, index, nsat, sync, prn, sat, code, freq, ppr1, lock1, amb, sys = SYS_GLO; if ((nsat = decode_head1009(rtcm, &sync)) < 0) { return -1; } for (j = 0; j < nsat && rtcm->obs.n < MAXOBS && i + 79 <= rtcm->len * 8; ++j) { prn = getbitu(rtcm->buff, i, 6); i += 6; code = getbitu(rtcm->buff, i, 1); i += 1; freq = getbitu(rtcm->buff, i, 5); i += 5; pr1 = getbitu(rtcm->buff, i, 25); i += 25; ppr1 = getbits(rtcm->buff, i, 20); i += 20; lock1 = getbitu(rtcm->buff, i, 7); i += 7; amb = getbitu(rtcm->buff, i, 7); i += 7; cnr1 = getbitu(rtcm->buff, i, 8); i += 8; if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 1010 satellite number error: prn=%d\n", prn); continue; } tt = timediff(rtcm->obs.data[0].time, rtcm->time); if (rtcm->obsflag || fabs(tt) > 1E-9) { rtcm->obs.n = rtcm->obsflag = 0; } if ((index = obsindex(&rtcm->obs, rtcm->time, sat)) < 0) { continue; } pr1 = pr1 * 0.02 + amb * PRUNIT_GLO; if (ppr1 != (int)0xFFF80000) { rtcm->obs.data[index].P[0] = pr1; lam1 = CLIGHT / (FREQ1_GLO + DFRQ1_GLO * (freq - 7)); cp1 = adjcp(rtcm, sat, 0, ppr1 * 0.0005 / lam1); rtcm->obs.data[index].L[0] = pr1 / lam1 + cp1; } rtcm->obs.data[index].LLI[0] = lossoflock(rtcm, sat, 0, lock1); rtcm->obs.data[index].SNR[0] = snratio(cnr1 * 0.25); rtcm->obs.data[index].code[0] = code ? CODE_L1P : CODE_L1C; } return sync ? 0 : 1; } /* decode type 1011: L1&L2 glonass rtk observables ---------------------------*/ static int decode_type1011(rtcm_t* rtcm) { int sync; if (decode_head1009(rtcm, &sync) < 0) { return -1; } rtcm->obsflag = !sync; return sync ? 0 : 1; } /* decode type 1012: extended L1&L2 glonass rtk observables ------------------*/ static int decode_type1012(rtcm_t* rtcm) { double pr1, cnr1, cnr2, tt, cp1, cp2, lam1, lam2; int i = 24 + 61, j, index, nsat, sync, prn, sat, freq, code1, code2, pr21, ppr1, ppr2; int lock1, lock2, amb, sys = SYS_GLO; if ((nsat = decode_head1009(rtcm, &sync)) < 0) { return -1; } for (j = 0; j < nsat && rtcm->obs.n < MAXOBS && i + 130 <= rtcm->len * 8; ++j) { prn = getbitu(rtcm->buff, i, 6); i += 6; code1 = getbitu(rtcm->buff, i, 1); i += 1; freq = getbitu(rtcm->buff, i, 5); i += 5; pr1 = getbitu(rtcm->buff, i, 25); i += 25; ppr1 = getbits(rtcm->buff, i, 20); i += 20; lock1 = getbitu(rtcm->buff, i, 7); i += 7; amb = getbitu(rtcm->buff, i, 7); i += 7; cnr1 = getbitu(rtcm->buff, i, 8); i += 8; code2 = getbitu(rtcm->buff, i, 2); i += 2; pr21 = getbits(rtcm->buff, i, 14); i += 14; ppr2 = getbits(rtcm->buff, i, 20); i += 20; lock2 = getbitu(rtcm->buff, i, 7); i += 7; cnr2 = getbitu(rtcm->buff, i, 8); i += 8; if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 1012 satellite number error: sys=%d prn=%d\n", sys, prn); continue; } tt = timediff(rtcm->obs.data[0].time, rtcm->time); if (rtcm->obsflag || fabs(tt) > 1E-9) { rtcm->obs.n = rtcm->obsflag = 0; } if ((index = obsindex(&rtcm->obs, rtcm->time, sat)) < 0) { continue; } pr1 = pr1 * 0.02 + amb * PRUNIT_GLO; if (ppr1 != (int)0xFFF80000) { lam1 = CLIGHT / (FREQ1_GLO + DFRQ1_GLO * (freq - 7)); rtcm->obs.data[index].P[0] = pr1; cp1 = adjcp(rtcm, sat, 0, ppr1 * 0.0005 / lam1); rtcm->obs.data[index].L[0] = pr1 / lam1 + cp1; } rtcm->obs.data[index].LLI[0] = lossoflock(rtcm, sat, 0, lock1); rtcm->obs.data[index].SNR[0] = snratio(cnr1 * 0.25); rtcm->obs.data[index].code[0] = code1 ? CODE_L1P : CODE_L1C; if (pr21 != (int)0xFFFFE000) { rtcm->obs.data[index].P[1] = pr1 + pr21 * 0.02; } if (ppr2 != (int)0xFFF80000) { lam2 = CLIGHT / (FREQ2_GLO + DFRQ2_GLO * (freq - 7)); cp2 = adjcp(rtcm, sat, 1, ppr2 * 0.0005 / lam2); rtcm->obs.data[index].L[1] = pr1 / lam2 + cp2; } rtcm->obs.data[index].LLI[1] = lossoflock(rtcm, sat, 1, lock2); rtcm->obs.data[index].SNR[1] = snratio(cnr2 * 0.25); rtcm->obs.data[index].code[1] = code2 ? CODE_L2P : CODE_L2C; } rtcm->obsflag = !sync; return sync ? 0 : 1; } /* decode type 1013: system parameters ---------------------------------------*/ static int decode_type1013(rtcm_t* rtcm) { return 0; } /* decode type 1019: gps ephemerides -----------------------------------------*/ static int decode_type1019(rtcm_t* rtcm) { eph_t eph = {0}; double toc, sqrtA; char* msg; int i = 24 + 12, prn, sat, week, sys = SYS_GPS; if (i + 476 <= rtcm->len * 8) { prn = getbitu(rtcm->buff, i, 6); i += 6; week = getbitu(rtcm->buff, i, 10); i += 10; eph.sva = getbitu(rtcm->buff, i, 4); i += 4; eph.code = getbitu(rtcm->buff, i, 2); i += 2; eph.idot = getbits(rtcm->buff, i, 14) * P2_43 * SC2RAD; i += 14; eph.iode = getbitu(rtcm->buff, i, 8); i += 8; toc = getbitu(rtcm->buff, i, 16) * 16.0; i += 16; eph.f2 = getbits(rtcm->buff, i, 8) * P2_55; i += 8; eph.f1 = getbits(rtcm->buff, i, 16) * P2_43; i += 16; eph.f0 = getbits(rtcm->buff, i, 22) * P2_31; i += 22; eph.iodc = getbitu(rtcm->buff, i, 10); i += 10; eph.crs = getbits(rtcm->buff, i, 16) * P2_5; i += 16; eph.deln = getbits(rtcm->buff, i, 16) * P2_43 * SC2RAD; i += 16; eph.M0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.cuc = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.e = getbitu(rtcm->buff, i, 32) * P2_33; i += 32; eph.cus = getbits(rtcm->buff, i, 16) * P2_29; i += 16; sqrtA = getbitu(rtcm->buff, i, 32) * P2_19; i += 32; eph.toes = getbitu(rtcm->buff, i, 16) * 16.0; i += 16; eph.cic = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.OMG0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.cis = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.i0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.crc = getbits(rtcm->buff, i, 16) * P2_5; i += 16; eph.omg = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.OMGd = getbits(rtcm->buff, i, 24) * P2_43 * SC2RAD; i += 24; eph.tgd[0] = getbits(rtcm->buff, i, 8) * P2_31; i += 8; eph.svh = getbitu(rtcm->buff, i, 6); i += 6; eph.flag = getbitu(rtcm->buff, i, 1); i += 1; eph.fit = getbitu(rtcm->buff, i, 1) ? 0.0 : 4.0; /* 0:4hr,1:>4hr */ } else { trace(2, "rtcm3 1019 length error: len=%d\n", rtcm->len); return -1; } if (prn >= 40) { sys = SYS_SBS; prn += 80; } trace(4, "decode_type1019: prn=%d iode=%d toe=%.0f\n", prn, eph.iode, eph.toes); if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " prn=%2d iode=%3d iodc=%3d week=%d toe=%6.0f toc=%6.0f svh=%02X", prn, eph.iode, eph.iodc, week, eph.toes, toc, eph.svh); } if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 1019 satellite number error: prn=%d\n", prn); return -1; } eph.sat = sat; eph.week = adjgpsweek(week); eph.tocs = toc; eph.toe = gpst2time(eph.week, eph.toes); eph.toc = gpst2time(eph.week, toc); eph.ttr = rtcm->time; eph.A = sqrtA * sqrtA; if (!strstr(rtcm->opt, "-EPHALL")) { if (eph.iode == rtcm->nav.eph[sat - 1].iode) { return 0; /* unchanged */ } } rtcm->nav.eph[sat - 1] = eph; rtcm->ephsat = sat; return 2; } /* decode type 1020: glonass ephemerides -------------------------------------*/ static int decode_type1020(rtcm_t* rtcm) { geph_t geph = {0}; double tk_h, tk_m, tk_s, toe, tow, tod, tof; char* msg; int i = 24 + 12, prn, sat, week, tb, bn, sys = SYS_GLO; if (i + 348 <= rtcm->len * 8) { prn = getbitu(rtcm->buff, i, 6); i += 6; geph.frq = getbitu(rtcm->buff, i, 5) - 7; i += 5 + 2 + 2; tk_h = getbitu(rtcm->buff, i, 5); i += 5; tk_m = getbitu(rtcm->buff, i, 6); i += 6; tk_s = getbitu(rtcm->buff, i, 1) * 30.0; i += 1; bn = getbitu(rtcm->buff, i, 1); i += 1 + 1; tb = getbitu(rtcm->buff, i, 7); i += 7; geph.vel[0] = getbitg(rtcm->buff, i, 24) * P2_20 * 1E3; i += 24; geph.pos[0] = getbitg(rtcm->buff, i, 27) * P2_11 * 1E3; i += 27; geph.acc[0] = getbitg(rtcm->buff, i, 5) * P2_30 * 1E3; i += 5; geph.vel[1] = getbitg(rtcm->buff, i, 24) * P2_20 * 1E3; i += 24; geph.pos[1] = getbitg(rtcm->buff, i, 27) * P2_11 * 1E3; i += 27; geph.acc[1] = getbitg(rtcm->buff, i, 5) * P2_30 * 1E3; i += 5; geph.vel[2] = getbitg(rtcm->buff, i, 24) * P2_20 * 1E3; i += 24; geph.pos[2] = getbitg(rtcm->buff, i, 27) * P2_11 * 1E3; i += 27; geph.acc[2] = getbitg(rtcm->buff, i, 5) * P2_30 * 1E3; i += 5 + 1; geph.gamn = getbitg(rtcm->buff, i, 11) * P2_40; i += 11 + 3; geph.taun = getbitg(rtcm->buff, i, 22) * P2_30; } else { trace(2, "rtcm3 1020 length error: len=%d\n", rtcm->len); return -1; } if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 1020 satellite number error: prn=%d\n", prn); return -1; } trace(4, "decode_type1020: prn=%d tk=%02.0f:%02.0f:%02.0f\n", prn, tk_h, tk_m, tk_s); if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " prn=%2d tk=%02.0f:%02.0f:%02.0f frq=%2d bn=%d tb=%d", prn, tk_h, tk_m, tk_s, geph.frq, bn, tb); } geph.sat = sat; geph.svh = bn; geph.iode = tb & 0x7F; if (rtcm->time.time == 0) { rtcm->time = utc2gpst(timeget()); } tow = time2gpst(gpst2utc(rtcm->time), &week); tod = fmod(tow, 86400.0); tow -= tod; tof = tk_h * 3600.0 + tk_m * 60.0 + tk_s - 10800.0; /* lt->utc */ if (tof < tod - 43200.0) { tof += 86400.0; } else if (tof > tod + 43200.0) { tof -= 86400.0; } geph.tof = utc2gpst(gpst2time(week, tow + tof)); toe = tb * 900.0 - 10800.0; /* lt->utc */ if (toe < tod - 43200.0) { toe += 86400.0; } else if (toe > tod + 43200.0) { toe -= 86400.0; } geph.toe = utc2gpst(gpst2time(week, tow + toe)); /* utc->gpst */ if (!strstr(rtcm->opt, "-EPHALL")) { if (fabs(timediff(geph.toe, rtcm->nav.geph[sat - 1].toe)) < 1.0 && geph.svh == rtcm->nav.geph[sat - 1].svh) { return 0; /* unchanged */ } } rtcm->nav.geph[sat - 1] = geph; rtcm->ephsat = sat; return 2; } /* decode type 1021: helmert/abridged molodenski -----------------------------*/ static int decode_type1021(rtcm_t* rtcm) { trace(2, "rtcm3 1021: not supported message\n"); return 0; } /* decode type 1022: moledenski-badekas transfromation -----------------------*/ static int decode_type1022(rtcm_t* rtcm) { trace(2, "rtcm3 1022: not supported message\n"); return 0; } /* decode type 1023: residual, ellipoidal grid representation ----------------*/ static int decode_type1023(rtcm_t* rtcm) { trace(2, "rtcm3 1023: not supported message\n"); return 0; } /* decode type 1024: residual, plane grid representation ---------------------*/ static int decode_type1024(rtcm_t* rtcm) { trace(2, "rtcm3 1024: not supported message\n"); return 0; } /* decode type 1025: projection (types except LCC2SP,OM) ---------------------*/ static int decode_type1025(rtcm_t* rtcm) { trace(2, "rtcm3 1025: not supported message\n"); return 0; } /* decode type 1026: projection (LCC2SP - lambert conic conformal (2sp)) -----*/ static int decode_type1026(rtcm_t* rtcm) { trace(2, "rtcm3 1026: not supported message\n"); return 0; } /* decode type 1027: projection (type OM - oblique mercator) -----------------*/ static int decode_type1027(rtcm_t* rtcm) { trace(2, "rtcm3 1027: not supported message\n"); return 0; } /* decode type 1030: network rtk residual ------------------------------------*/ static int decode_type1030(rtcm_t* rtcm) { trace(2, "rtcm3 1030: not supported message\n"); return 0; } /* decode type 1031: glonass network rtk residual ----------------------------*/ static int decode_type1031(rtcm_t* rtcm) { trace(2, "rtcm3 1031: not supported message\n"); return 0; } /* decode type 1032: physical reference station position information ---------*/ static int decode_type1032(rtcm_t* rtcm) { trace(2, "rtcm3 1032: not supported message\n"); return 0; } /* decode type 1033: receiver and antenna descriptor -------------------------*/ static int decode_type1033(rtcm_t* rtcm) { char des[32] = "", sno[32] = "", rec[32] = "", ver[32] = "", rsn[32] = ""; char* msg; int i = 24 + 12, j, staid, n, m, n1, n2, n3, setup; n = getbitu(rtcm->buff, i + 12, 8); m = getbitu(rtcm->buff, i + 28 + 8 * n, 8); n1 = getbitu(rtcm->buff, i + 36 + 8 * (n + m), 8); n2 = getbitu(rtcm->buff, i + 44 + 8 * (n + m + n1), 8); n3 = getbitu(rtcm->buff, i + 52 + 8 * (n + m + n1 + n2), 8); if (i + 60 + 8 * (n + m + n1 + n2 + n3) <= rtcm->len * 8) { staid = getbitu(rtcm->buff, i, 12); i += 12 + 8; for (j = 0; j < n && j < 31; ++j) { des[j] = (char)getbitu(rtcm->buff, i, 8); i += 8; } setup = getbitu(rtcm->buff, i, 8); i += 8 + 8; for (j = 0; j < m && j < 31; ++j) { sno[j] = (char)getbitu(rtcm->buff, i, 8); i += 8; } i += 8; for (j = 0; j < n1 && j < 31; ++j) { rec[j] = (char)getbitu(rtcm->buff, i, 8); i += 8; } i += 8; for (j = 0; j < n2 && j < 31; ++j) { ver[j] = (char)getbitu(rtcm->buff, i, 8); i += 8; } i += 8; for (j = 0; j < n3 && j < 31; ++j) { rsn[j] = (char)getbitu(rtcm->buff, i, 8); i += 8; } } else { trace(2, "rtcm3 1033 length error: len=%d\n", rtcm->len); return -1; } if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " staid=%4d", staid); } /* test station id */ if (!test_staid(rtcm, staid)) { return -1; } strncpy(rtcm->sta.antdes, des, n); rtcm->sta.antdes[n] = '\0'; rtcm->sta.antsetup = setup; strncpy(rtcm->sta.antsno, sno, m); rtcm->sta.antsno[m] = '\0'; strncpy(rtcm->sta.rectype, rec, n1); rtcm->sta.rectype[n1] = '\0'; strncpy(rtcm->sta.recver, ver, n2); rtcm->sta.recver[n2] = '\0'; strncpy(rtcm->sta.recsno, rsn, n3); rtcm->sta.recsno[n3] = '\0'; trace(3, "rtcm3 1033: ant=%s:%s rec=%s:%s:%s\n", des, sno, rec, ver, rsn); return 5; } /* decode type 1034: gps network fkp gradient --------------------------------*/ static int decode_type1034(rtcm_t* rtcm) { trace(2, "rtcm3 1034: not supported message\n"); return 0; } /* decode type 1035: glonass network fkp gradient ----------------------------*/ static int decode_type1035(rtcm_t* rtcm) { trace(2, "rtcm3 1035: not supported message\n"); return 0; } /* decode type 1037: glonass network rtk ionospheric correction difference ---*/ static int decode_type1037(rtcm_t* rtcm) { trace(2, "rtcm3 1037: not supported message\n"); return 0; } /* decode type 1038: glonass network rtk geometic correction difference ------*/ static int decode_type1038(rtcm_t* rtcm) { trace(2, "rtcm3 1038: not supported message\n"); return 0; } /* decode type 1039: glonass network rtk combined correction difference ------*/ static int decode_type1039(rtcm_t* rtcm) { trace(2, "rtcm3 1039: not supported message\n"); return 0; } /* decode type 1044: qzss ephemerides (ref [15]) -----------------------------*/ static int decode_type1044(rtcm_t* rtcm) { eph_t eph = {0}; double toc, sqrtA; char* msg; int i = 24 + 12, prn, sat, week, sys = SYS_QZS; if (i + 473 <= rtcm->len * 8) { prn = getbitu(rtcm->buff, i, 4) + 192; i += 4; toc = getbitu(rtcm->buff, i, 16) * 16.0; i += 16; eph.f2 = getbits(rtcm->buff, i, 8) * P2_55; i += 8; eph.f1 = getbits(rtcm->buff, i, 16) * P2_43; i += 16; eph.f0 = getbits(rtcm->buff, i, 22) * P2_31; i += 22; eph.iode = getbitu(rtcm->buff, i, 8); i += 8; eph.crs = getbits(rtcm->buff, i, 16) * P2_5; i += 16; eph.deln = getbits(rtcm->buff, i, 16) * P2_43 * SC2RAD; i += 16; eph.M0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.cuc = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.e = getbitu(rtcm->buff, i, 32) * P2_33; i += 32; eph.cus = getbits(rtcm->buff, i, 16) * P2_29; i += 16; sqrtA = getbitu(rtcm->buff, i, 32) * P2_19; i += 32; eph.toes = getbitu(rtcm->buff, i, 16) * 16.0; i += 16; eph.cic = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.OMG0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.cis = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.i0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.crc = getbits(rtcm->buff, i, 16) * P2_5; i += 16; eph.omg = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.OMGd = getbits(rtcm->buff, i, 24) * P2_43 * SC2RAD; i += 24; eph.idot = getbits(rtcm->buff, i, 14) * P2_43 * SC2RAD; i += 14; eph.code = getbitu(rtcm->buff, i, 2); i += 2; week = getbitu(rtcm->buff, i, 10); i += 10; eph.sva = getbitu(rtcm->buff, i, 4); i += 4; eph.svh = getbitu(rtcm->buff, i, 6); i += 6; eph.tgd[0] = getbits(rtcm->buff, i, 8) * P2_31; i += 8; eph.iodc = getbitu(rtcm->buff, i, 10); i += 10; eph.fit = getbitu(rtcm->buff, i, 1) ? 0.0 : 2.0; /* 0:2hr,1:>2hr */ } else { trace(2, "rtcm3 1044 length error: len=%d\n", rtcm->len); return -1; } trace(4, "decode_type1044: prn=%d iode=%d toe=%.0f\n", prn, eph.iode, eph.toes); if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " prn=%3d iode=%3d iodc=%3d week=%d toe=%6.0f toc=%6.0f svh=%02X", prn, eph.iode, eph.iodc, week, eph.toes, toc, eph.svh); } if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 1044 satellite number error: prn=%d\n", prn); return -1; } eph.sat = sat; eph.week = adjgpsweek(week); eph.toe = gpst2time(eph.week, eph.toes); eph.toc = gpst2time(eph.week, toc); eph.ttr = rtcm->time; eph.A = sqrtA * sqrtA; if (!strstr(rtcm->opt, "-EPHALL")) { if (eph.iode == rtcm->nav.eph[sat - 1].iode && eph.iodc == rtcm->nav.eph[sat - 1].iodc) { return 0; /* unchanged */ } } rtcm->nav.eph[sat - 1] = eph; rtcm->ephsat = sat; return 2; } /* decode type 1045: galileo satellite ephemerides (ref [15]) ----------------*/ static int decode_type1045(rtcm_t* rtcm) { eph_t eph = {0}; double toc, sqrtA; char* msg; //int i = 24 + 12, prn, sat, week, e5a_hs, e5a_dvs, rsv, sys = SYS_GAL; int i = 24 + 12, prn, sat, week, e5a_hs, e5a_dvs, sys = SYS_GAL; if (i + 484 <= rtcm->len * 8) { prn = getbitu(rtcm->buff, i, 6); i += 6; week = getbitu(rtcm->buff, i, 12); i += 12; eph.iode = getbitu(rtcm->buff, i, 10); i += 10; eph.sva = getbitu(rtcm->buff, i, 8); i += 8; eph.idot = getbits(rtcm->buff, i, 14) * P2_43 * SC2RAD; i += 14; toc = getbitu(rtcm->buff, i, 14) * 60.0; i += 14; eph.f2 = getbits(rtcm->buff, i, 6) * P2_59; i += 6; eph.f1 = getbits(rtcm->buff, i, 21) * P2_46; i += 21; eph.f0 = getbits(rtcm->buff, i, 31) * P2_34; i += 31; eph.crs = getbits(rtcm->buff, i, 16) * P2_5; i += 16; eph.deln = getbits(rtcm->buff, i, 16) * P2_43 * SC2RAD; i += 16; eph.M0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.cuc = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.e = getbitu(rtcm->buff, i, 32) * P2_33; i += 32; eph.cus = getbits(rtcm->buff, i, 16) * P2_29; i += 16; sqrtA = getbitu(rtcm->buff, i, 32) * P2_19; i += 32; eph.toes = getbitu(rtcm->buff, i, 14) * 60.0; i += 14; eph.cic = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.OMG0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.cis = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.i0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.crc = getbits(rtcm->buff, i, 16) * P2_5; i += 16; eph.omg = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.OMGd = getbits(rtcm->buff, i, 24) * P2_43 * SC2RAD; i += 24; eph.tgd[0] = getbits(rtcm->buff, i, 10) * P2_32; i += 10; /* E5a/E1 */ e5a_hs = getbitu(rtcm->buff, i, 2); i += 2; /* OSHS */ e5a_dvs = getbitu(rtcm->buff, i, 1); i += 1; /* OSDVS */ //rsv = getbitu(rtcm->buff, i, 7); getbitu(rtcm->buff, i, 7); } else { trace(2, "rtcm3 1045 length error: len=%d\n", rtcm->len); return -1; } trace(4, "decode_type1045: prn=%d iode=%d toe=%.0f\n", prn, eph.iode, eph.toes); if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " prn=%2d iode=%3d week=%d toe=%6.0f toc=%6.0f hs=%d dvs=%d", prn, eph.iode, week, eph.toes, toc, e5a_hs, e5a_dvs); } if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 1045 satellite number error: prn=%d\n", prn); return -1; } eph.sat = sat; eph.week = adjgpsweek(week % 1024); eph.toe = gpst2time(eph.week, eph.toes); eph.toc = gpst2time(eph.week, toc); eph.ttr = rtcm->time; eph.A = sqrtA * sqrtA; eph.svh = (e5a_hs << 4) + (e5a_dvs << 3); eph.code = 2; /* data source = f/nav e5a */ if (!strstr(rtcm->opt, "-EPHALL")) { if (eph.iode == rtcm->nav.eph[sat - 1].iode) { return 0; /* unchanged */ } } rtcm->nav.eph[sat - 1] = eph; rtcm->ephsat = sat; return 2; } /* decode type 1047: beidou ephemerides (tentative mt and format) ------------*/ static int decode_type1047(rtcm_t* rtcm) { eph_t eph = {0}; double toc, sqrtA; char* msg; int i = 24 + 12, prn, sat, week, sys = SYS_CMP; if (i + 476 <= rtcm->len * 8) { prn = getbitu(rtcm->buff, i, 6); i += 6; week = getbitu(rtcm->buff, i, 10); i += 10; eph.sva = getbitu(rtcm->buff, i, 4); i += 4; eph.code = getbitu(rtcm->buff, i, 2); i += 2; eph.idot = getbits(rtcm->buff, i, 14) * P2_43 * SC2RAD; i += 14; eph.iode = getbitu(rtcm->buff, i, 8); i += 8; toc = getbitu(rtcm->buff, i, 16) * 16.0; i += 16; eph.f2 = getbits(rtcm->buff, i, 8) * P2_55; i += 8; eph.f1 = getbits(rtcm->buff, i, 16) * P2_43; i += 16; eph.f0 = getbits(rtcm->buff, i, 22) * P2_31; i += 22; eph.iodc = getbitu(rtcm->buff, i, 10); i += 10; eph.crs = getbits(rtcm->buff, i, 16) * P2_5; i += 16; eph.deln = getbits(rtcm->buff, i, 16) * P2_43 * SC2RAD; i += 16; eph.M0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.cuc = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.e = getbitu(rtcm->buff, i, 32) * P2_33; i += 32; eph.cus = getbits(rtcm->buff, i, 16) * P2_29; i += 16; sqrtA = getbitu(rtcm->buff, i, 32) * P2_19; i += 32; eph.toes = getbitu(rtcm->buff, i, 16) * 16.0; i += 16; eph.cic = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.OMG0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.cis = getbits(rtcm->buff, i, 16) * P2_29; i += 16; eph.i0 = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.crc = getbits(rtcm->buff, i, 16) * P2_5; i += 16; eph.omg = getbits(rtcm->buff, i, 32) * P2_31 * SC2RAD; i += 32; eph.OMGd = getbits(rtcm->buff, i, 24) * P2_43 * SC2RAD; i += 24; eph.tgd[0] = getbits(rtcm->buff, i, 8) * P2_31; i += 8; eph.svh = getbitu(rtcm->buff, i, 6); i += 6; eph.flag = getbitu(rtcm->buff, i, 1); i += 1; eph.fit = getbitu(rtcm->buff, i, 1) ? 0.0 : 4.0; /* 0:4hr,1:>4hr */ } else { trace(2, "rtcm3 1047 length error: len=%d\n", rtcm->len); return -1; } trace(4, "decode_type1047: prn=%d iode=%d toe=%.0f\n", prn, eph.iode, eph.toes); if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " prn=%2d iode=%3d iodc=%3d week=%d toe=%6.0f toc=%6.0f svh=%02X", prn, eph.iode, eph.iodc, week, eph.toes, toc, eph.svh); } if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 1047 satellite number error: prn=%d\n", prn); return -1; } eph.sat = sat; eph.week = adjbdtweek(week); eph.toe = bdt2gpst(bdt2time(eph.week, eph.toes)); /* bdt -> gpst */ eph.toc = bdt2gpst(bdt2time(eph.week, toc)); /* bdt -> gpst */ eph.ttr = rtcm->time; eph.A = sqrtA * sqrtA; if (!strstr(rtcm->opt, "-EPHALL")) { if (eph.iode == rtcm->nav.eph[sat - 1].iode) { return 0; /* unchanged */ } } rtcm->nav.eph[sat - 1] = eph; rtcm->ephsat = sat; return 2; } /* decode ssr 1,4 message header ---------------------------------------------*/ static int decode_ssr1_head(rtcm_t* rtcm, int sys, int* sync, int* iod, double* udint, int* refd, int* hsize) { double tod, tow; char* msg; int i = 24 + 12, nsat, udi, provid = 0, solid = 0, ns = 6; #ifndef SSR_QZSS_DRAFT_V05 ns = sys == SYS_QZS ? 4 : 6; #endif if (i + (sys == SYS_GLO ? 53 : 50 + ns) > rtcm->len * 8) { return -1; } if (sys == SYS_GLO) { tod = getbitu(rtcm->buff, i, 17); i += 17; adjday_glot(rtcm, tod); } else { tow = getbitu(rtcm->buff, i, 20); i += 20; adjweek(rtcm, tow); } udi = getbitu(rtcm->buff, i, 4); i += 4; *sync = getbitu(rtcm->buff, i, 1); i += 1; *refd = getbitu(rtcm->buff, i, 1); i += 1; /* satellite ref datum */ *iod = getbitu(rtcm->buff, i, 4); i += 4; /* iod */ provid = getbitu(rtcm->buff, i, 16); i += 16; /* provider id */ solid = getbitu(rtcm->buff, i, 4); i += 4; /* solution id */ nsat = getbitu(rtcm->buff, i, ns); i += ns; *udint = ssrudint[udi]; trace(4, "decode_ssr1_head: time=%s sys=%d nsat=%d sync=%d iod=%d provid=%d " "solid=%d\n", time_str(rtcm->time, 2), sys, nsat, *sync, *iod, provid, solid); if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " %s nsat=%2d iod=%2d udi=%2d sync=%d", time_str(rtcm->time, 2), nsat, *iod, udi, *sync); } *hsize = i; return nsat; } /* decode ssr 2,3,5,6 message header -----------------------------------------*/ static int decode_ssr2_head(rtcm_t* rtcm, int sys, int* sync, int* iod, double* udint, int* hsize) { double tod, tow; char* msg; int i = 24 + 12, nsat, udi, provid = 0, solid = 0, ns = 6; #ifndef SSR_QZSS_DRAFT_V05 ns = sys == SYS_QZS ? 4 : 6; #endif if (i + (sys == SYS_GLO ? 52 : 49 + ns) > rtcm->len * 8) { return -1; } if (sys == SYS_GLO) { tod = getbitu(rtcm->buff, i, 17); i += 17; adjday_glot(rtcm, tod); } else { tow = getbitu(rtcm->buff, i, 20); i += 20; adjweek(rtcm, tow); } udi = getbitu(rtcm->buff, i, 4); i += 4; *sync = getbitu(rtcm->buff, i, 1); i += 1; *iod = getbitu(rtcm->buff, i, 4); i += 4; provid = getbitu(rtcm->buff, i, 16); i += 16; /* provider id */ solid = getbitu(rtcm->buff, i, 4); i += 4; /* solution id */ nsat = getbitu(rtcm->buff, i, ns); i += ns; *udint = ssrudint[udi]; trace(4, "decode_ssr2_head: time=%s sys=%d nsat=%d sync=%d iod=%d provid=%d " "solid=%d\n", time_str(rtcm->time, 2), sys, nsat, *sync, *iod, provid, solid); if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " %s nsat=%2d iod=%2d udi=%2d sync=%d", time_str(rtcm->time, 2), nsat, *iod, udi, *sync); } *hsize = i; return nsat; } /* decode ssr 1: orbit corrections -------------------------------------------*/ static int decode_ssr1(rtcm_t* rtcm, int sys) { double udint, deph[3], ddeph[3]; int i, j, k, type, sync, iod, nsat, prn, sat, iode, iodcrc, refd = 0, np, ni, nj, offp; type = getbitu(rtcm->buff, 24, 12); if ((nsat = decode_ssr1_head(rtcm, sys, &sync, &iod, &udint, &refd, &i)) < 0) { trace(2, "rtcm3 %d length error: len=%d\n", type, rtcm->len); return -1; } switch (sys) { case SYS_GPS: np = 6; ni = 8; nj = 0; offp = 0; break; case SYS_GLO: np = 5; ni = 8; nj = 0; offp = 0; break; case SYS_GAL: np = 6; ni = 10; nj = 0; offp = 0; break; case SYS_QZS: np = 4; ni = 8; nj = 0; offp = 192; break; case SYS_CMP: np = 6; ni = 10; nj = 24; offp = 1; break; case SYS_SBS: np = 6; ni = 9; nj = 24; offp = 120; break; default: return sync ? 0 : 10; } for (j = 0; j < nsat && i + 121 + np + ni + nj <= rtcm->len * 8; ++j) { prn = getbitu(rtcm->buff, i, np) + offp; i += np; iode = getbitu(rtcm->buff, i, ni); i += ni; iodcrc = getbitu(rtcm->buff, i, nj); i += nj; deph[0] = getbits(rtcm->buff, i, 22) * 1E-4; i += 22; deph[1] = getbits(rtcm->buff, i, 20) * 4E-4; i += 20; deph[2] = getbits(rtcm->buff, i, 20) * 4E-4; i += 20; ddeph[0] = getbits(rtcm->buff, i, 21) * 1E-6; i += 21; ddeph[1] = getbits(rtcm->buff, i, 19) * 4E-6; i += 19; ddeph[2] = getbits(rtcm->buff, i, 19) * 4E-6; i += 19; if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 %d satellite number error: prn=%d\n", type, prn); continue; } rtcm->ssr[sat - 1].t0[0] = rtcm->time; rtcm->ssr[sat - 1].udi[0] = udint; rtcm->ssr[sat - 1].iod[0] = iod; rtcm->ssr[sat - 1].iode = iode; /* sbas/bds: toe/t0 modulo */ rtcm->ssr[sat - 1].iodcrc = iodcrc; /* sbas/bds: iod crc */ rtcm->ssr[sat - 1].refd = refd; for (k = 0; k < 3; ++k) { rtcm->ssr[sat - 1].deph[k] = deph[k]; rtcm->ssr[sat - 1].ddeph[k] = ddeph[k]; } rtcm->ssr[sat - 1].update = 1; } return sync ? 0 : 10; } /* decode ssr 2: clock corrections -------------------------------------------*/ static int decode_ssr2(rtcm_t* rtcm, int sys) { double udint, dclk[3]; int i, j, k, type, sync, iod, nsat, prn, sat, np, offp; type = getbitu(rtcm->buff, 24, 12); if ((nsat = decode_ssr2_head(rtcm, sys, &sync, &iod, &udint, &i)) < 0) { trace(2, "rtcm3 %d length error: len=%d\n", type, rtcm->len); return -1; } switch (sys) { case SYS_GPS: np = 6; offp = 0; break; case SYS_GLO: np = 5; offp = 0; break; case SYS_GAL: np = 6; offp = 0; break; case SYS_QZS: np = 4; offp = 192; break; case SYS_CMP: np = 6; offp = 1; break; case SYS_SBS: np = 6; offp = 120; break; default: return sync ? 0 : 10; } for (j = 0; j < nsat && i + 70 + np <= rtcm->len * 8; ++j) { prn = getbitu(rtcm->buff, i, np) + offp; i += np; dclk[0] = getbits(rtcm->buff, i, 22) * 1E-4; i += 22; dclk[1] = getbits(rtcm->buff, i, 21) * 1E-6; i += 21; dclk[2] = getbits(rtcm->buff, i, 27) * 2E-8; i += 27; if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 %d satellite number error: prn=%d\n", type, prn); continue; } rtcm->ssr[sat - 1].t0[1] = rtcm->time; rtcm->ssr[sat - 1].udi[1] = udint; rtcm->ssr[sat - 1].iod[1] = iod; for (k = 0; k < 3; ++k) { rtcm->ssr[sat - 1].dclk[k] = dclk[k]; } rtcm->ssr[sat - 1].update = 1; } return sync ? 0 : 10; } /* decode ssr 3: satellite code biases ---------------------------------------*/ static int decode_ssr3(rtcm_t* rtcm, int sys) { const int codes_gps[] = {CODE_L1C, CODE_L1P, CODE_L1W, CODE_L1Y, CODE_L1M, CODE_L2C, CODE_L2D, CODE_L2S, CODE_L2L, CODE_L2X, CODE_L2P, CODE_L2W, CODE_L2Y, CODE_L2M, CODE_L5I, CODE_L5Q, CODE_L5X}; const int codes_glo[] = {CODE_L1C, CODE_L1P, CODE_L2C, CODE_L2P}; const int codes_gal[] = {CODE_L1A, CODE_L1B, CODE_L1C, CODE_L1X, CODE_L1Z, CODE_L5I, CODE_L5Q, CODE_L5X, CODE_L7I, CODE_L7Q, CODE_L7X, CODE_L8I, CODE_L8Q, CODE_L8X, CODE_L6A, CODE_L6B, CODE_L6C, CODE_L6X, CODE_L6Z}; const int codes_qzs[] = {CODE_L1C, CODE_L1S, CODE_L1L, CODE_L2S, CODE_L2L, CODE_L2X, CODE_L5I, CODE_L5Q, CODE_L5X, CODE_L6S, CODE_L6L, CODE_L6X, CODE_L1X}; const int codes_bds[] = {CODE_L1I, CODE_L1Q, CODE_L1X, CODE_L7I, CODE_L7Q, CODE_L7X, CODE_L6I, CODE_L6Q, CODE_L6X}; const int codes_sbs[] = {CODE_L1C, CODE_L5I, CODE_L5Q, CODE_L5X}; const int* codes; double udint, bias, cbias[MAXCODE]; int i, j, k, type, mode, sync, iod, nsat, prn, sat, nbias, np, offp, ncode; type = getbitu(rtcm->buff, 24, 12); if ((nsat = decode_ssr2_head(rtcm, sys, &sync, &iod, &udint, &i)) < 0) { trace(2, "rtcm3 %d length error: len=%d\n", type, rtcm->len); return -1; } switch (sys) { case SYS_GPS: np = 6; offp = 0; codes = codes_gps; ncode = 16; break; case SYS_GLO: np = 5; offp = 0; codes = codes_glo; ncode = 3; break; case SYS_GAL: np = 6; offp = 0; codes = codes_gal; ncode = 18; break; case SYS_QZS: np = 4; offp = 192; codes = codes_qzs; ncode = 12; break; case SYS_CMP: np = 6; offp = 1; codes = codes_bds; ncode = 8; break; case SYS_SBS: np = 6; offp = 120; codes = codes_sbs; ncode = 3; break; default: return sync ? 0 : 10; } for (j = 0; j < nsat && i + 5 + np <= rtcm->len * 8; ++j) { prn = getbitu(rtcm->buff, i, np) + offp; i += np; nbias = getbitu(rtcm->buff, i, 5); i += 5; for (k = 0; k < MAXCODE; ++k) { cbias[k] = 0.0; } for (k = 0; k < nbias && i + 19 < rtcm->len * 8; ++k) { mode = getbitu(rtcm->buff, i, 5); i += 5; bias = getbits(rtcm->buff, i, 14) * 0.01; i += 14; if (mode <= ncode) { cbias[codes[mode] - 1] = (float)bias; } else { trace(2, "rtcm3 %d not supported mode: mode=%d\n", type, mode); } } if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 %d satellite number error: prn=%d\n", type, prn); continue; } rtcm->ssr[sat - 1].t0[4] = rtcm->time; rtcm->ssr[sat - 1].udi[4] = udint; rtcm->ssr[sat - 1].iod[4] = iod; for (k = 0; k < MAXCODE; ++k) { rtcm->ssr[sat - 1].cbias[k] = (float)cbias[k]; } rtcm->ssr[sat - 1].update = 1; } return sync ? 0 : 10; } /* decode ssr 4: combined orbit and clock corrections ------------------------*/ static int decode_ssr4(rtcm_t* rtcm, int sys) { double udint, deph[3], ddeph[3], dclk[3]; int i, j, k, type, nsat, sync, iod, prn, sat, iode, iodcrc, refd = 0, np, ni, nj, offp; type = getbitu(rtcm->buff, 24, 12); if ((nsat = decode_ssr1_head(rtcm, sys, &sync, &iod, &udint, &refd, &i)) < 0) { trace(2, "rtcm3 %d length error: len=%d\n", type, rtcm->len); return -1; } switch (sys) { case SYS_GPS: np = 6; ni = 8; nj = 0; offp = 0; break; case SYS_GLO: np = 5; ni = 8; nj = 0; offp = 0; break; case SYS_GAL: np = 6; ni = 10; nj = 0; offp = 0; break; case SYS_QZS: np = 4; ni = 8; nj = 0; offp = 192; break; case SYS_CMP: np = 6; ni = 10; nj = 24; offp = 1; break; case SYS_SBS: np = 6; ni = 9; nj = 24; offp = 120; break; default: return sync ? 0 : 10; } for (j = 0; j < nsat && i + 191 + np + ni + nj <= rtcm->len * 8; ++j) { prn = getbitu(rtcm->buff, i, np) + offp; i += np; iode = getbitu(rtcm->buff, i, ni); i += ni; iodcrc = getbitu(rtcm->buff, i, nj); i += nj; deph[0] = getbits(rtcm->buff, i, 22) * 1E-4; i += 22; deph[1] = getbits(rtcm->buff, i, 20) * 4E-4; i += 20; deph[2] = getbits(rtcm->buff, i, 20) * 4E-4; i += 20; ddeph[0] = getbits(rtcm->buff, i, 21) * 1E-6; i += 21; ddeph[1] = getbits(rtcm->buff, i, 19) * 4E-6; i += 19; ddeph[2] = getbits(rtcm->buff, i, 19) * 4E-6; i += 19; dclk[0] = getbits(rtcm->buff, i, 22) * 1E-4; i += 22; dclk[1] = getbits(rtcm->buff, i, 21) * 1E-6; i += 21; dclk[2] = getbits(rtcm->buff, i, 27) * 2E-8; i += 27; if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 %d satellite number error: prn=%d\n", type, prn); continue; } rtcm->ssr[sat - 1].t0[0] = rtcm->ssr[sat - 1].t0[1] = rtcm->time; rtcm->ssr[sat - 1].udi[0] = rtcm->ssr[sat - 1].udi[1] = udint; rtcm->ssr[sat - 1].iod[0] = rtcm->ssr[sat - 1].iod[1] = iod; rtcm->ssr[sat - 1].iode = iode; rtcm->ssr[sat - 1].iodcrc = iodcrc; rtcm->ssr[sat - 1].refd = refd; for (k = 0; k < 3; ++k) { rtcm->ssr[sat - 1].deph[k] = deph[k]; rtcm->ssr[sat - 1].ddeph[k] = ddeph[k]; rtcm->ssr[sat - 1].dclk[k] = dclk[k]; } rtcm->ssr[sat - 1].update = 1; } return sync ? 0 : 10; } /* decode ssr 5: ura ---------------------------------------------------------*/ static int decode_ssr5(rtcm_t* rtcm, int sys) { double udint; int i, j, type, nsat, sync, iod, prn, sat, ura, np, offp; type = getbitu(rtcm->buff, 24, 12); if ((nsat = decode_ssr2_head(rtcm, sys, &sync, &iod, &udint, &i)) < 0) { trace(2, "rtcm3 %d length error: len=%d\n", type, rtcm->len); return -1; } switch (sys) { case SYS_GPS: np = 6; offp = 0; break; case SYS_GLO: np = 5; offp = 0; break; case SYS_GAL: np = 6; offp = 0; break; case SYS_QZS: np = 4; offp = 192; break; case SYS_CMP: np = 6; offp = 1; break; case SYS_SBS: np = 6; offp = 120; break; default: return sync ? 0 : 10; } for (j = 0; j < nsat && i + 6 + np <= rtcm->len * 8; ++j) { prn = getbitu(rtcm->buff, i, np) + offp; i += np; ura = getbitu(rtcm->buff, i, 6); i += 6; if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 %d satellite number error: prn=%d\n", type, prn); continue; } rtcm->ssr[sat - 1].t0[3] = rtcm->time; rtcm->ssr[sat - 1].udi[3] = udint; rtcm->ssr[sat - 1].iod[3] = iod; rtcm->ssr[sat - 1].ura = ura; rtcm->ssr[sat - 1].update = 1; } return sync ? 0 : 10; } /* decode ssr 6: high rate clock correction ----------------------------------*/ static int decode_ssr6(rtcm_t* rtcm, int sys) { double udint, hrclk; int i, j, type, nsat, sync, iod, prn, sat, np, offp; type = getbitu(rtcm->buff, 24, 12); if ((nsat = decode_ssr2_head(rtcm, sys, &sync, &iod, &udint, &i)) < 0) { trace(2, "rtcm3 %d length error: len=%d\n", type, rtcm->len); return -1; } switch (sys) { case SYS_GPS: np = 6; offp = 0; break; case SYS_GLO: np = 5; offp = 0; break; case SYS_GAL: np = 6; offp = 0; break; case SYS_QZS: np = 4; offp = 192; break; case SYS_CMP: np = 6; offp = 1; break; case SYS_SBS: np = 6; offp = 120; break; default: return sync ? 0 : 10; } for (j = 0; j < nsat && i + 22 + np <= rtcm->len * 8; ++j) { prn = getbitu(rtcm->buff, i, np) + offp; i += np; hrclk = getbits(rtcm->buff, i, 22) * 1E-4; i += 22; if (!(sat = satno(sys, prn))) { trace(2, "rtcm3 %d satellite number error: prn=%d\n", type, prn); continue; } rtcm->ssr[sat - 1].t0[2] = rtcm->time; rtcm->ssr[sat - 1].udi[2] = udint; rtcm->ssr[sat - 1].iod[2] = iod; rtcm->ssr[sat - 1].hrclk = hrclk; rtcm->ssr[sat - 1].update = 1; } return sync ? 0 : 10; } /* get signal index ----------------------------------------------------------*/ static void sigindex(int sys, const unsigned char* code, const int* freq, int n, const char* opt, int* ind) { int i, nex, pri, pri_h[8] = {0}, index[8] = {0}, ex[32] = {0}; /* test code priority */ for (i = 0; i < n; ++i) { if (!code[i]) { continue; } if (freq[i] > NFREQ) { /* save as extended signal if freq > NFREQ */ ex[i] = 1; continue; } /* code priority */ pri = getcodepri(sys, code[i], opt); /* select highest priority signal */ if (pri > pri_h[freq[i] - 1]) { if (index[freq[i] - 1]) { ex[index[freq[i] - 1] - 1] = 1; } pri_h[freq[i] - 1] = pri; index[freq[i] - 1] = i + 1; } else { ex[i] = 1; } } /* signal index in obs data */ for (i = nex = 0; i < n; ++i) { if (ex[i] == 0) { ind[i] = freq[i] - 1; } else if (nex < NEXOBS) { ind[i] = NFREQ + nex++; } else { /* no space in obs data */ trace(2, "rtcm msm: no space in obs data sys=%d code=%d\n", sys, code[i]); ind[i] = -1; } #if 0 trace(2, "sig pos: sys=%d code=%d ex=%d ind=%d\n", sys, code[i], ex[i], ind[i]); #endif } } /* save obs data in msm message ----------------------------------------------*/ static void save_msm_obs(rtcm_t* rtcm, int sys, msm_h_t* h, const double* r, const double* pr, const double* cp, const double* rr, const double* rrf, const double* cnr, const int* lock, const int* ex, const int* half) { const char* sig[32]; double tt, wl; unsigned char code[32]; char *msm_type = "", *q = NULL; int i, j, k, type, prn, sat, fn, index = 0, freq[32], ind[32]; type = getbitu(rtcm->buff, 24, 12); switch (sys) { case SYS_GPS: msm_type = q = rtcm->msmtype[0]; break; case SYS_GLO: msm_type = q = rtcm->msmtype[1]; break; case SYS_GAL: msm_type = q = rtcm->msmtype[2]; break; case SYS_QZS: msm_type = q = rtcm->msmtype[3]; break; case SYS_SBS: msm_type = q = rtcm->msmtype[4]; break; case SYS_CMP: msm_type = q = rtcm->msmtype[5]; break; } /* id to signal */ for (i = 0; i < h->nsig; ++i) { switch (sys) { case SYS_GPS: sig[i] = msm_sig_gps[h->sigs[i] - 1]; break; case SYS_GLO: sig[i] = msm_sig_glo[h->sigs[i] - 1]; break; case SYS_GAL: sig[i] = msm_sig_gal[h->sigs[i] - 1]; break; case SYS_QZS: sig[i] = msm_sig_qzs[h->sigs[i] - 1]; break; case SYS_SBS: sig[i] = msm_sig_sbs[h->sigs[i] - 1]; break; case SYS_CMP: sig[i] = msm_sig_cmp[h->sigs[i] - 1]; break; default: sig[i] = ""; break; } /* signal to rinex obs type */ code[i] = obs2code(sig[i], freq + i); /* freqency index for beidou */ if (sys == SYS_CMP) { if (freq[i] == 5) { freq[i] = 2; /* B2 */ } else if (freq[i] == 4) { freq[i] = 3; /* B3 */ } } if (code[i] != CODE_NONE) { if (q) { q += sprintf(q, "L%s%s", sig[i], i < h->nsig - 1 ? "," : ""); } } else { if (q) { q += sprintf(q, "(%d)%s", h->sigs[i], i < h->nsig - 1 ? "," : ""); } trace(2, "rtcm3 %d: unknown signal id=%2d\n", type, h->sigs[i]); } } trace(3, "rtcm3 %d: signals=%s\n", type, msm_type); /* get signal index */ sigindex(sys, code, freq, h->nsig, rtcm->opt, ind); for (i = j = 0; i < h->nsat; ++i) { prn = h->sats[i]; if (sys == SYS_QZS) { prn += MINPRNQZS - 1; } else if (sys == SYS_SBS) { prn += MINPRNSBS - 1; } if ((sat = satno(sys, prn))) { tt = timediff(rtcm->obs.data[0].time, rtcm->time); if (rtcm->obsflag || fabs(tt) > 1E-9) { rtcm->obs.n = rtcm->obsflag = 0; } index = obsindex(&rtcm->obs, rtcm->time, sat); } else { trace(2, "rtcm3 %d satellite error: prn=%d\n", type, prn); } for (k = 0; k < h->nsig; ++k) { if (!h->cellmask[k + i * h->nsig]) { continue; } if (sat && index >= 0 && ind[k] >= 0) { /* satellite carrier wave length */ wl = satwavelen(sat, freq[k] - 1, &rtcm->nav); /* glonass wave length by extended info */ if (sys == SYS_GLO && ex && ex[i] <= 13) { fn = ex[i] - 7; wl = CLIGHT / ((freq[k] == 2 ? FREQ2_GLO : FREQ1_GLO) + (freq[k] == 2 ? DFRQ2_GLO : DFRQ1_GLO) * fn); } /* pseudorange (m) */ if (r[i] != 0.0 && pr[j] > -1E12) { rtcm->obs.data[index].P[ind[k]] = r[i] + pr[j]; } /* carrier-phase (cycle) */ if (r[i] != 0.0 && cp[j] > -1E12 && wl > 0.0) { rtcm->obs.data[index].L[ind[k]] = (r[i] + cp[j]) / wl; } /* doppler (hz) */ if (rr && rrf && rrf[j] > -1E12 && wl > 0.0) { rtcm->obs.data[index].D[ind[k]] = (float)(-(rr[i] + rrf[j]) / wl); } rtcm->obs.data[index].LLI[ind[k]] = lossoflock(rtcm, sat, ind[k], lock[j]) + (half[j] ? 3 : 0); rtcm->obs.data[index].SNR[ind[k]] = (unsigned char)(cnr[j] * 4.0); rtcm->obs.data[index].code[ind[k]] = code[k]; } ++j; } } } /* decode type msm message header --------------------------------------------*/ static int decode_msm_head(rtcm_t* rtcm, int sys, int* sync, int* iod, msm_h_t* h, int* hsize) { msm_h_t h0 = {0}; double tow, tod; char* msg; //int i = 24, j, dow, mask, staid, type, ncell = 0; int i = 24, j, mask, staid, type, ncell = 0; type = getbitu(rtcm->buff, i, 12); i += 12; *h = h0; if (i + 157 <= rtcm->len * 8) { staid = getbitu(rtcm->buff, i, 12); i += 12; if (sys == SYS_GLO) { //dow = getbitu(rtcm->buff, i, 3); getbitu(rtcm->buff, i, 3); i += 3; tod = getbitu(rtcm->buff, i, 27) * 0.001; i += 27; adjday_glot(rtcm, tod); } else if (sys == SYS_CMP) { tow = getbitu(rtcm->buff, i, 30) * 0.001; i += 30; tow += 14.0; /* BDT -> GPST */ adjweek(rtcm, tow); } else { tow = getbitu(rtcm->buff, i, 30) * 0.001; i += 30; adjweek(rtcm, tow); } *sync = getbitu(rtcm->buff, i, 1); i += 1; *iod = getbitu(rtcm->buff, i, 3); i += 3; h->time_s = getbitu(rtcm->buff, i, 7); i += 7; h->clk_str = getbitu(rtcm->buff, i, 2); i += 2; h->clk_ext = getbitu(rtcm->buff, i, 2); i += 2; h->smooth = getbitu(rtcm->buff, i, 1); i += 1; h->tint_s = getbitu(rtcm->buff, i, 3); i += 3; for (j = 1; j <= 64; ++j) { mask = getbitu(rtcm->buff, i, 1); i += 1; if (mask) { h->sats[h->nsat++] = j; } } for (j = 1; j <= 32; ++j) { mask = getbitu(rtcm->buff, i, 1); i += 1; if (mask) { h->sigs[h->nsig++] = j; } } } else { trace(2, "rtcm3 %d length error: len=%d\n", type, rtcm->len); return -1; } /* test station id */ if (!test_staid(rtcm, staid)) { return -1; } if (h->nsat * h->nsig > 64) { trace(2, "rtcm3 %d number of sats and sigs error: nsat=%d nsig=%d\n", type, h->nsat, h->nsig); return -1; } if (i + h->nsat * h->nsig > rtcm->len * 8) { trace(2, "rtcm3 %d length error: len=%d nsat=%d nsig=%d\n", type, rtcm->len, h->nsat, h->nsig); return -1; } for (j = 0; j < h->nsat * h->nsig; ++j) { h->cellmask[j] = getbitu(rtcm->buff, i, 1); i += 1; if (h->cellmask[j]) { ncell++; } } *hsize = i; trace(4, "decode_head_msm: time=%s sys=%d staid=%d nsat=%d nsig=%d sync=%d " "iod=%d ncell=%d\n", time_str(rtcm->time, 2), sys, staid, h->nsat, h->nsig, *sync, *iod, ncell); if (rtcm->outtype) { msg = rtcm->msgtype + strlen(rtcm->msgtype); sprintf(msg, " %s staid=%3d nsat=%2d nsig=%2d iod=%2d ncell=%2d sync=%d", time_str(rtcm->time, 2), staid, h->nsat, h->nsig, *iod, ncell, *sync); } return ncell; } /* decode unsupported msm message --------------------------------------------*/ static int decode_msm0(rtcm_t* rtcm, int sys) { msm_h_t h = {0}; int i, sync, iod; if (decode_msm_head(rtcm, sys, &sync, &iod, &h, &i) < 0) { return -1; } rtcm->obsflag = !sync; return sync ? 0 : 1; } /* decode msm 4: full pseudorange and phaserange plus cnr --------------------*/ static int decode_msm4(rtcm_t* rtcm, int sys) { msm_h_t h = {0}; double r[64], pr[64], cp[64], cnr[64]; int i, j, type, sync, iod, ncell, rng, rng_m, prv, cpv, lock[64], half[64]; type = getbitu(rtcm->buff, 24, 12); /* decode msm header */ if ((ncell = decode_msm_head(rtcm, sys, &sync, &iod, &h, &i)) < 0) { return -1; } if (i + h.nsat * 18 + ncell * 48 > rtcm->len * 8) { trace(2, "rtcm3 %d length error: nsat=%d ncell=%d len=%d\n", type, h.nsat, ncell, rtcm->len); return -1; } for (j = 0; j < h.nsat; ++j) { r[j] = 0.0; } for (j = 0; j < ncell; ++j) { pr[j] = cp[j] = -1E16; } /* decode satellite data */ for (j = 0; j < h.nsat; ++j) { /* range */ rng = getbitu(rtcm->buff, i, 8); i += 8; if (rng != 255) { r[j] = rng * RANGE_MS; } } for (j = 0; j < h.nsat; ++j) { rng_m = getbitu(rtcm->buff, i, 10); i += 10; if (r[j] != 0.0) { r[j] += rng_m * P2_10 * RANGE_MS; } } /* decode signal data */ for (j = 0; j < ncell; ++j) { /* pseudorange */ prv = getbits(rtcm->buff, i, 15); i += 15; if (prv != -16384) { pr[j] = prv * P2_24 * RANGE_MS; } } for (j = 0; j < ncell; ++j) { /* phaserange */ cpv = getbits(rtcm->buff, i, 22); i += 22; if (cpv != -2097152) { cp[j] = cpv * P2_29 * RANGE_MS; } } for (j = 0; j < ncell; ++j) { /* lock time */ lock[j] = getbitu(rtcm->buff, i, 4); i += 4; } for (j = 0; j < ncell; ++j) { /* half-cycle ambiguity */ half[j] = getbitu(rtcm->buff, i, 1); i += 1; } for (j = 0; j < ncell; ++j) { /* cnr */ cnr[j] = getbitu(rtcm->buff, i, 6) * 1.0; i += 6; } /* save obs data in msm message */ save_msm_obs(rtcm, sys, &h, r, pr, cp, NULL, NULL, cnr, lock, NULL, half); rtcm->obsflag = !sync; return sync ? 0 : 1; } /* decode msm 5: full pseudorange, phaserange, phaserangerate and cnr --------*/ static int decode_msm5(rtcm_t* rtcm, int sys) { msm_h_t h = {0}; double r[64], rr[64], pr[64], cp[64], rrf[64], cnr[64]; int i, j, type, sync, iod, ncell, rng, rng_m, rate, prv, cpv, rrv, lock[64]; int ex[64], half[64]; type = getbitu(rtcm->buff, 24, 12); /* decode msm header */ if ((ncell = decode_msm_head(rtcm, sys, &sync, &iod, &h, &i)) < 0) { return -1; } if (i + h.nsat * 36 + ncell * 63 > rtcm->len * 8) { trace(2, "rtcm3 %d length error: nsat=%d ncell=%d len=%d\n", type, h.nsat, ncell, rtcm->len); return -1; } for (j = 0; j < h.nsat; ++j) { r[j] = rr[j] = 0.0; ex[j] = 15; } for (j = 0; j < ncell; ++j) { pr[j] = cp[j] = rrf[j] = -1E16; } /* decode satellite data */ for (j = 0; j < h.nsat; ++j) { /* range */ rng = getbitu(rtcm->buff, i, 8); i += 8; if (rng != 255) { r[j] = rng * RANGE_MS; } } for (j = 0; j < h.nsat; ++j) { /* extended info */ ex[j] = getbitu(rtcm->buff, i, 4); i += 4; } for (j = 0; j < h.nsat; ++j) { rng_m = getbitu(rtcm->buff, i, 10); i += 10; if (r[j] != 0.0) { r[j] += rng_m * P2_10 * RANGE_MS; } } for (j = 0; j < h.nsat; ++j) { /* phaserangerate */ rate = getbits(rtcm->buff, i, 14); i += 14; if (rate != -8192) { rr[j] = rate * 1.0; } } /* decode signal data */ for (j = 0; j < ncell; ++j) { /* pseudorange */ prv = getbits(rtcm->buff, i, 15); i += 15; if (prv != -16384) { pr[j] = prv * P2_24 * RANGE_MS; } } for (j = 0; j < ncell; ++j) { /* phaserange */ cpv = getbits(rtcm->buff, i, 22); i += 22; if (cpv != -2097152) { cp[j] = cpv * P2_29 * RANGE_MS; } } for (j = 0; j < ncell; ++j) { /* lock time */ lock[j] = getbitu(rtcm->buff, i, 4); i += 4; } for (j = 0; j < ncell; ++j) { /* half-cycle ambiguity */ half[j] = getbitu(rtcm->buff, i, 1); i += 1; } for (j = 0; j < ncell; ++j) { /* cnr */ cnr[j] = getbitu(rtcm->buff, i, 6) * 1.0; i += 6; } for (j = 0; j < ncell; ++j) { /* phaserangerate */ rrv = getbits(rtcm->buff, i, 15); i += 15; if (rrv != -16384) { rrf[j] = rrv * 0.0001; } } /* save obs data in msm message */ save_msm_obs(rtcm, sys, &h, r, pr, cp, rr, rrf, cnr, lock, ex, half); rtcm->obsflag = !sync; return sync ? 0 : 1; } /* decode msm 6: full pseudorange and phaserange plus cnr (high-res) ---------*/ static int decode_msm6(rtcm_t* rtcm, int sys) { msm_h_t h = {0}; double r[64], pr[64], cp[64], cnr[64]; int i, j, type, sync, iod, ncell, rng, rng_m, prv, cpv, lock[64], half[64]; type = getbitu(rtcm->buff, 24, 12); /* decode msm header */ if ((ncell = decode_msm_head(rtcm, sys, &sync, &iod, &h, &i)) < 0) { return -1; } if (i + h.nsat * 18 + ncell * 65 > rtcm->len * 8) { trace(2, "rtcm3 %d length error: nsat=%d ncell=%d len=%d\n", type, h.nsat, ncell, rtcm->len); return -1; } for (j = 0; j < h.nsat; ++j) { r[j] = 0.0; } for (j = 0; j < ncell; ++j) { pr[j] = cp[j] = -1E16; } /* decode satellite data */ for (j = 0; j < h.nsat; ++j) { /* range */ rng = getbitu(rtcm->buff, i, 8); i += 8; if (rng != 255) { r[j] = rng * RANGE_MS; } } for (j = 0; j < h.nsat; ++j) { rng_m = getbitu(rtcm->buff, i, 10); i += 10; if (r[j] != 0.0) { r[j] += rng_m * P2_10 * RANGE_MS; } } /* decode signal data */ for (j = 0; j < ncell; ++j) { /* pseudorange */ prv = getbits(rtcm->buff, i, 20); i += 20; if (prv != -524288) { pr[j] = prv * P2_29 * RANGE_MS; } } for (j = 0; j < ncell; ++j) { /* phaserange */ cpv = getbits(rtcm->buff, i, 24); i += 24; if (cpv != -8388608) { cp[j] = cpv * P2_31 * RANGE_MS; } } for (j = 0; j < ncell; ++j) { /* lock time */ lock[j] = getbitu(rtcm->buff, i, 10); i += 10; } for (j = 0; j < ncell; ++j) { /* half-cycle ambiguity */ half[j] = getbitu(rtcm->buff, i, 1); i += 1; } for (j = 0; j < ncell; ++j) { /* cnr */ cnr[j] = getbitu(rtcm->buff, i, 10) * 0.0625; i += 10; } /* save obs data in msm message */ save_msm_obs(rtcm, sys, &h, r, pr, cp, NULL, NULL, cnr, lock, NULL, half); rtcm->obsflag = !sync; return sync ? 0 : 1; } /* decode msm 7: full pseudorange, phaserange, phaserangerate and cnr (h-res) */ static int decode_msm7(rtcm_t* rtcm, int sys) { msm_h_t h = {0}; double r[64], rr[64], pr[64], cp[64], rrf[64], cnr[64]; int i, j, type, sync, iod, ncell, rng, rng_m, rate, prv, cpv, rrv, lock[64]; int ex[64], half[64]; type = getbitu(rtcm->buff, 24, 12); /* decode msm header */ if ((ncell = decode_msm_head(rtcm, sys, &sync, &iod, &h, &i)) < 0) { return -1; } if (i + h.nsat * 36 + ncell * 80 > rtcm->len * 8) { trace(2, "rtcm3 %d length error: nsat=%d ncell=%d len=%d\n", type, h.nsat, ncell, rtcm->len); return -1; } for (j = 0; j < h.nsat; ++j) { r[j] = rr[j] = 0.0; ex[j] = 15; } for (j = 0; j < ncell; ++j) { pr[j] = cp[j] = rrf[j] = -1E16; } /* decode satellite data */ for (j = 0; j < h.nsat; ++j) { /* range */ rng = getbitu(rtcm->buff, i, 8); i += 8; if (rng != 255) { r[j] = rng * RANGE_MS; } } for (j = 0; j < h.nsat; ++j) { /* extended info */ ex[j] = getbitu(rtcm->buff, i, 4); i += 4; } for (j = 0; j < h.nsat; ++j) { rng_m = getbitu(rtcm->buff, i, 10); i += 10; if (r[j] != 0.0) { r[j] += rng_m * P2_10 * RANGE_MS; } } for (j = 0; j < h.nsat; ++j) { /* phaserangerate */ rate = getbits(rtcm->buff, i, 14); i += 14; if (rate != -8192) { rr[j] = rate * 1.0; } } /* decode signal data */ for (j = 0; j < ncell; ++j) { /* pseudorange */ prv = getbits(rtcm->buff, i, 20); i += 20; if (prv != -524288) { pr[j] = prv * P2_29 * RANGE_MS; } } for (j = 0; j < ncell; ++j) { /* phaserange */ cpv = getbits(rtcm->buff, i, 24); i += 24; if (cpv != -8388608) { cp[j] = cpv * P2_31 * RANGE_MS; } } for (j = 0; j < ncell; ++j) { /* lock time */ lock[j] = getbitu(rtcm->buff, i, 10); i += 10; } for (j = 0; j < ncell; ++j) { /* half-cycle amiguity */ half[j] = getbitu(rtcm->buff, i, 1); i += 1; } for (j = 0; j < ncell; ++j) { /* cnr */ cnr[j] = getbitu(rtcm->buff, i, 10) * 0.0625; i += 10; } for (j = 0; j < ncell; ++j) { /* phaserangerate */ rrv = getbits(rtcm->buff, i, 15); i += 15; if (rrv != -16384) { rrf[j] = rrv * 0.0001; } } /* save obs data in msm message */ save_msm_obs(rtcm, sys, &h, r, pr, cp, rr, rrf, cnr, lock, ex, half); rtcm->obsflag = !sync; return sync ? 0 : 1; } /* decode type 1230: glonass L1 and L2 code-phase biases ---------------------*/ static int decode_type1230(rtcm_t* rtcm) { trace(2, "rtcm3 1230: not supported message\n"); return 0; } /* decode rtcm ver.3 message -------------------------------------------------*/ extern int decode_rtcm3(rtcm_t* rtcm) { int ret = 0, type = getbitu(rtcm->buff, 24, 12); trace(3, "decode_rtcm3: len=%3d type=%d\n", rtcm->len, type); if (rtcm->outtype) { sprintf(rtcm->msgtype, "RTCM %4d (%4d):", type, rtcm->len); } rtcm->message_type = type; /* real-time input option */ if (strstr(rtcm->opt, "-RT_INP")) { rtcm->time = utc2gpst(timeget()); } switch (type) { case 1001: ret = decode_type1001(rtcm); break; /* not supported */ case 1002: ret = decode_type1002(rtcm); break; case 1003: ret = decode_type1003(rtcm); break; /* not supported */ case 1004: ret = decode_type1004(rtcm); break; case 1005: ret = decode_type1005(rtcm); break; case 1006: ret = decode_type1006(rtcm); break; case 1007: ret = decode_type1007(rtcm); break; case 1008: ret = decode_type1008(rtcm); break; case 1009: ret = decode_type1009(rtcm); break; /* not supported */ case 1010: ret = decode_type1010(rtcm); break; case 1011: ret = decode_type1011(rtcm); break; /* not supported */ case 1012: ret = decode_type1012(rtcm); break; case 1013: ret = decode_type1013(rtcm); break; /* not supported */ case 1019: ret = decode_type1019(rtcm); break; case 1020: ret = decode_type1020(rtcm); break; case 1021: ret = decode_type1021(rtcm); break; /* not supported */ case 1022: ret = decode_type1022(rtcm); break; /* not supported */ case 1023: ret = decode_type1023(rtcm); break; /* not supported */ case 1024: ret = decode_type1024(rtcm); break; /* not supported */ case 1025: ret = decode_type1025(rtcm); break; /* not supported */ case 1026: ret = decode_type1026(rtcm); break; /* not supported */ case 1027: ret = decode_type1027(rtcm); break; /* not supported */ case 1030: ret = decode_type1030(rtcm); break; /* not supported */ case 1031: ret = decode_type1031(rtcm); break; /* not supported */ case 1032: ret = decode_type1032(rtcm); break; /* not supported */ case 1033: ret = decode_type1033(rtcm); break; case 1034: ret = decode_type1034(rtcm); break; /* not supported */ case 1035: ret = decode_type1035(rtcm); break; /* not supported */ case 1037: ret = decode_type1037(rtcm); break; /* not supported */ case 1038: ret = decode_type1038(rtcm); break; /* not supported */ case 1039: ret = decode_type1039(rtcm); break; /* not supported */ case 1044: ret = decode_type1044(rtcm); break; case 1045: ret = decode_type1045(rtcm); break; case 1047: ret = decode_type1047(rtcm); break; /* tentative mt */ case 1057: ret = decode_ssr1(rtcm, SYS_GPS); break; case 1058: ret = decode_ssr2(rtcm, SYS_GPS); break; case 1059: ret = decode_ssr3(rtcm, SYS_GPS); break; case 1060: ret = decode_ssr4(rtcm, SYS_GPS); break; case 1061: ret = decode_ssr5(rtcm, SYS_GPS); break; case 1062: ret = decode_ssr6(rtcm, SYS_GPS); break; case 1063: ret = decode_ssr1(rtcm, SYS_GLO); break; case 1064: ret = decode_ssr2(rtcm, SYS_GLO); break; case 1065: ret = decode_ssr3(rtcm, SYS_GLO); break; case 1066: ret = decode_ssr4(rtcm, SYS_GLO); break; case 1067: ret = decode_ssr5(rtcm, SYS_GLO); break; case 1068: ret = decode_ssr6(rtcm, SYS_GLO); break; case 1071: ret = decode_msm0(rtcm, SYS_GPS); break; /* not supported */ case 1072: ret = decode_msm0(rtcm, SYS_GPS); break; /* not supported */ case 1073: ret = decode_msm0(rtcm, SYS_GPS); break; /* not supported */ case 1074: ret = decode_msm4(rtcm, SYS_GPS); break; case 1075: ret = decode_msm5(rtcm, SYS_GPS); break; case 1076: ret = decode_msm6(rtcm, SYS_GPS); break; case 1077: ret = decode_msm7(rtcm, SYS_GPS); break; case 1081: ret = decode_msm0(rtcm, SYS_GLO); break; /* not supported */ case 1082: ret = decode_msm0(rtcm, SYS_GLO); break; /* not supported */ case 1083: ret = decode_msm0(rtcm, SYS_GLO); break; /* not supported */ case 1084: ret = decode_msm4(rtcm, SYS_GLO); break; case 1085: ret = decode_msm5(rtcm, SYS_GLO); break; case 1086: ret = decode_msm6(rtcm, SYS_GLO); break; case 1087: ret = decode_msm7(rtcm, SYS_GLO); break; case 1091: ret = decode_msm0(rtcm, SYS_GAL); break; /* not supported */ case 1092: ret = decode_msm0(rtcm, SYS_GAL); break; /* not supported */ case 1093: ret = decode_msm0(rtcm, SYS_GAL); break; /* not supported */ case 1094: ret = decode_msm4(rtcm, SYS_GAL); break; case 1095: ret = decode_msm5(rtcm, SYS_GAL); break; case 1096: ret = decode_msm6(rtcm, SYS_GAL); break; case 1097: ret = decode_msm7(rtcm, SYS_GAL); break; case 1101: ret = decode_msm0(rtcm, SYS_SBS); break; /* not supported */ case 1102: ret = decode_msm0(rtcm, SYS_SBS); break; /* not supported */ case 1103: ret = decode_msm0(rtcm, SYS_SBS); break; /* not supported */ case 1104: ret = decode_msm4(rtcm, SYS_SBS); break; case 1105: ret = decode_msm5(rtcm, SYS_SBS); break; case 1106: ret = decode_msm6(rtcm, SYS_SBS); break; case 1107: ret = decode_msm7(rtcm, SYS_SBS); break; case 1111: ret = decode_msm0(rtcm, SYS_QZS); break; /* not supported */ case 1112: ret = decode_msm0(rtcm, SYS_QZS); break; /* not supported */ case 1113: ret = decode_msm0(rtcm, SYS_QZS); break; /* not supported */ case 1114: ret = decode_msm4(rtcm, SYS_QZS); break; case 1115: ret = decode_msm5(rtcm, SYS_QZS); break; case 1116: ret = decode_msm6(rtcm, SYS_QZS); break; case 1117: ret = decode_msm7(rtcm, SYS_QZS); break; case 1121: ret = decode_msm0(rtcm, SYS_CMP); break; /* not supported */ case 1122: ret = decode_msm0(rtcm, SYS_CMP); break; /* not supported */ case 1123: ret = decode_msm0(rtcm, SYS_CMP); break; /* not supported */ case 1124: ret = decode_msm4(rtcm, SYS_CMP); break; case 1125: ret = decode_msm5(rtcm, SYS_CMP); break; case 1126: ret = decode_msm6(rtcm, SYS_CMP); break; case 1127: ret = decode_msm7(rtcm, SYS_CMP); break; case 1230: ret = decode_type1230(rtcm); break; /* not supported */ case 1240: ret = decode_ssr1(rtcm, SYS_GAL); break; case 1241: ret = decode_ssr2(rtcm, SYS_GAL); break; case 1242: ret = decode_ssr3(rtcm, SYS_GAL); break; case 1243: ret = decode_ssr4(rtcm, SYS_GAL); break; case 1244: ret = decode_ssr5(rtcm, SYS_GAL); break; case 1245: ret = decode_ssr6(rtcm, SYS_GAL); break; case 1246: ret = decode_ssr1(rtcm, SYS_QZS); break; case 1247: ret = decode_ssr2(rtcm, SYS_QZS); break; case 1248: ret = decode_ssr3(rtcm, SYS_QZS); break; case 1249: ret = decode_ssr4(rtcm, SYS_QZS); break; case 1250: ret = decode_ssr5(rtcm, SYS_QZS); break; case 1251: ret = decode_ssr6(rtcm, SYS_QZS); break; case 1252: ret = decode_ssr1(rtcm, SYS_SBS); break; case 1253: ret = decode_ssr2(rtcm, SYS_SBS); break; case 1254: ret = decode_ssr3(rtcm, SYS_SBS); break; case 1255: ret = decode_ssr4(rtcm, SYS_SBS); break; case 1256: ret = decode_ssr5(rtcm, SYS_SBS); break; case 1257: ret = decode_ssr6(rtcm, SYS_SBS); break; case 1258: ret = decode_ssr1(rtcm, SYS_CMP); break; case 1259: ret = decode_ssr2(rtcm, SYS_CMP); break; case 1260: ret = decode_ssr3(rtcm, SYS_CMP); break; case 1261: ret = decode_ssr4(rtcm, SYS_CMP); break; case 1262: ret = decode_ssr5(rtcm, SYS_CMP); break; case 1263: ret = decode_ssr6(rtcm, SYS_CMP); break; } if (ret >= 0) { type -= 1000; if (1 <= type && type <= 299) { rtcm->nmsg3[type]++; } else { rtcm->nmsg3[0]++; } } return ret; }
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/rtklib/rtkcmn.c
/********************************************************************************* * The RTKLIB software package is distributed under the following BSD 2-clause * license (http://opensource.org/licenses/BSD-2-Clause) and additional two * exclusive clauses. Users are permitted to develop, produce or sell their own * non-commercial or commercial products utilizing, linking or including RTKLIB * as long as they comply with the license. * * Copyright (c) 2007-2013, T. Takasu, 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. * * - The software package includes some companion executive binaries or shared * libraries necessary to execute APs on Windows. These licenses succeed to the * original ones of these software. * * 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 HOLDER 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. ***********************************************************************************/ /*------------------------------------------------------------------------------ * rtkcmn.c : rtklib common functions * * Copyright (C) 2007-2015 by T.TAKASU, All rights reserved. * * options : -DLAPACK use LAPACK/BLAS * -DMKL use Intel MKL * -DTRACE enable debug trace * -DWIN32 use WIN32 API * -DNOCALLOC no use calloc for zero matrix * -DIERS_MODEL use GMF instead of NMF * -DDLL built for shared library * * references : * [1] IS-GPS-200D, Navstar GPS Space Segment/Navigation User Interfaces, * 7 March, 2006 * [2] RTCA/DO-229C, Minimum operational performanc standards for global * positioning system/wide area augmentation system airborne equipment, * RTCA inc, November 28, 2001 * [3] M.Rothacher, R.Schmid, ANTEX: The Antenna Exchange Format Version 1.4, * 15 September, 2010 * [4] A.Gelb ed., Applied Optimal Estimation, The M.I.T Press, 1974 * [5] A.E.Niell, Global mapping functions for the atmosphere delay at radio * wavelengths, Jounal of geophysical research, 1996 * [6] W.Gurtner and L.Estey, RINEX The Receiver Independent Exchange Format * Version 3.00, November 28, 2007 * [7] J.Kouba, A Guide to using International GNSS Service (IGS) products, * May 2009 * [8] China Satellite Navigation Office, BeiDou navigation satellite system * signal in space interface control document, open service signal B1I * (version 1.0), Dec 2012 * [9] J.Boehm, A.Niell, P.Tregoning and H.Shuh, Global Mapping Function * (GMF): A new empirical mapping function base on numerical weather * model data, Geophysical Research Letters, 33, L07304, 2006 * [10] GLONASS/GPS/Galileo/Compass/SBAS NV08C receiver series BINR interface * protocol specification ver.1.3, August, 2012 * * version : $Revision: 1.1 $ $Date: 2008/07/17 21:48:06 $ * history : 2007/01/12 1.0 new * 2007/03/06 1.1 input initial rover pos of pntpos() * update only effective states of filter() * fix bug of atan2() domain error * 2007/04/11 1.2 add function antmodel() * add gdop mask for pntpos() * change constant MAXDTOE value * 2007/05/25 1.3 add function execcmd(),expandpath() * 2008/06/21 1.4 add funciton sortobs(),uniqeph(),screent() * replace geodist() by sagnac correction way * 2008/10/29 1.5 fix bug of ionosphereic mapping function * fix bug of seasonal variation term of tropmapf * 2008/12/27 1.6 add function tickget(), sleepms(), tracenav(), * xyz2enu(), satposv(), pntvel(), covecef() * 2009/03/12 1.7 fix bug on error-stop when localtime() returns NULL * 2009/03/13 1.8 fix bug on time adjustment for summer time * 2009/04/10 1.9 add function adjgpsweek(),getbits(),getbitu() * add function geph2pos() * 2009/06/08 1.10 add function seph2pos() * 2009/11/28 1.11 change function pntpos() * add function tracegnav(),tracepeph() * 2009/12/22 1.12 change default parameter of ionos std * valid under second for timeget() * 2010/07/28 1.13 fix bug in tropmapf() * added api: * obs2code(),code2obs(),cross3(),normv3(), * gst2time(),time2gst(),time_str(),timeset(), * deg2dms(),dms2deg(),searchpcv(),antmodel_s(), * tracehnav(),tracepclk(),reppath(),reppaths(), * createdir() * changed api: * readpcv(), * deleted api: * uniqeph() * 2010/08/20 1.14 omit to include mkl header files * fix bug on chi-sqr(n) table * 2010/12/11 1.15 added api: * freeobs(),freenav(),ionppp() * 2011/05/28 1.16 fix bug on half-hour offset by time2epoch() * added api: * uniqnav() * 2012/06/09 1.17 add a leap second after 2012-6-30 * 2012/07/15 1.18 add api setbits(),setbitu(),utc2gmst() * fix bug on interpolation of antenna pcv * fix bug on str2num() for string with over 256 char * add api readblq(),satexclude(),setcodepri(), * getcodepri() * change api obs2code(),code2obs(),antmodel() * 2012/12/25 1.19 fix bug on satwavelen(),code2obs(),obs2code() * add api testsnr() * 2013/01/04 1.20 add api gpst2bdt(),bdt2gpst(),bdt2time(),time2bdt() * readblq(),readerp(),geterp(),crc16() * change api eci2ecef(),sunmoonpos() * 2013/03/26 1.21 tickget() uses clock_gettime() for linux * 2013/05/08 1.22 fix bug on nutation coefficients for ast_args() * 2013/06/02 1.23 add #ifdef for undefined CLOCK_MONOTONIC_RAW * 2013/09/01 1.24 fix bug on interpolation of satellite antenna pcv * 2013/09/06 1.25 fix bug on extrapolation of erp * 2014/04/27 1.26 add SYS_LEO for satellite system * add BDS L1 code for RINEX 3.02 and RTCM 3.2 * support BDS L1 in satwavelen() * 2014/05/29 1.27 fix bug on obs2code() to search obs code table * 2014/08/26 1.28 fix problem on output of uncompress() for tar file * add function to swap trace file with keywords * 2014/10/21 1.29 strtok() -> strtok_r() in expath() for thread-safe * add bdsmodear in procopt_default * 2015/03/19 1.30 fix bug on interpolation of erp values in geterp() * add leap second insertion before 2015/07/01 00:00 * add api read_leaps() *-----------------------------------------------------------------------------*/ /** * file: rtkcmn.c * version: rtklib ver.2.4.2 * Copy from * https://github.com/tomojitakasu/RTKLIB/tree/76b9c97257f304aedad38b5a6bbbac444724aab3/src/rtkcmn.c */ #define _POSIX_C_SOURCE 199309 #include <ctype.h> #include <stdarg.h> #ifndef WIN32 #include <dirent.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #endif #include "rtklib.h" /* static const char rcsid[] = "$Id: rtkcmn.c,v 1.1 2008/07/17 21:48:06 ttaka Exp ttaka $"; */ /* constants -----------------------------------------------------------------*/ #define POLYCRC32 0xEDB88320u /* CRC32 polynomial */ #define POLYCRC24Q 0x1864CFBu /* CRC24Q polynomial */ const static double gpst0[] = {1980, 1, 6, 0, 0, 0}; /* gps time reference */ const static double gst0[] = {1999, 8, 22, 0, 0, 0}; /* galileo system time reference */ const static double bdt0[] = {2006, 1, 1, 0, 0, 0}; /* beidou time reference */ static double leaps[MAXLEAPS + 1] [7] = {/* leap seconds (y,m,d,h,m,s,utc-gpst) */ {2017, 1, 1, 0, 0, 0, -18}, {2015, 7, 1, 0, 0, 0, -17}, {2012, 7, 1, 0, 0, 0, -16}, {2009, 1, 1, 0, 0, 0, -15}, {2006, 1, 1, 0, 0, 0, -14}, {1999, 1, 1, 0, 0, 0, -13}, {1997, 7, 1, 0, 0, 0, -12}, {1996, 1, 1, 0, 0, 0, -11}, {1994, 7, 1, 0, 0, 0, -10}, {1993, 7, 1, 0, 0, 0, -9}, {1992, 7, 1, 0, 0, 0, -8}, {1991, 1, 1, 0, 0, 0, -7}, {1990, 1, 1, 0, 0, 0, -6}, {1988, 1, 1, 0, 0, 0, -5}, {1985, 7, 1, 0, 0, 0, -4}, {1983, 7, 1, 0, 0, 0, -3}, {1982, 7, 1, 0, 0, 0, -2}, {1981, 7, 1, 0, 0, 0, -1}, {0}}; const double chisqr[100] = {/* chi-sqr(n) (alpha=0.001) */ 10.8, 13.8, 16.3, 18.5, 20.5, 22.5, 24.3, 26.1, 27.9, 29.6, 31.3, 32.9, 34.5, 36.1, 37.7, 39.3, 40.8, 42.3, 43.8, 45.3, 46.8, 48.3, 49.7, 51.2, 52.6, 54.1, 55.5, 56.9, 58.3, 59.7, 61.1, 62.5, 63.9, 65.2, 66.6, 68.0, 69.3, 70.7, 72.1, 73.4, 74.7, 76.0, 77.3, 78.6, 80.0, 81.3, 82.6, 84.0, 85.4, 86.7, 88.0, 89.3, 90.6, 91.9, 93.3, 94.7, 96.0, 97.4, 98.7, 100, 101, 102, 103, 104, 105, 107, 108, 109, 110, 112, 113, 114, 115, 116, 118, 119, 120, 122, 123, 125, 126, 127, 128, 129, 131, 132, 133, 134, 135, 137, 138, 139, 140, 142, 143, 144, 145, 147, 148, 149}; const double lam_carr[] = {/* carrier wave length (m) */ CLIGHT / FREQ1, CLIGHT / FREQ2, CLIGHT / FREQ5, CLIGHT / FREQ6, CLIGHT / FREQ7, CLIGHT / FREQ8}; const prcopt_t prcopt_default = { /* defaults processing options */ PMODE_SINGLE, 0, 2, SYS_GPS, /* mode,soltype,nf,navsys */ 15.0 * D2R, {{0, 0}}, /* elmin,snrmask */ 0, 1, 1, 1, /* sateph,modear,glomodear,bdsmodear */ 5, 0, 10, /* glomodear,maxout,minlock,minfix */ 0, 0, 0, 0, /* estion,esttrop,dynamics,tidecorr */ 1, 0, 0, 0, 0, /* niter,codesmooth,intpref,sbascorr,sbassatsel */ 0, 0, /* rovpos,refpos */ {100.0, 100.0}, /* eratio[] */ {100.0, 0.003, 0.003, 0.0, 1.0}, /* err[] */ {30.0, 0.03, 0.3}, /* std[] */ {1E-4, 1E-3, 1E-4, 1E-1, 1E-2}, /* prn[] */ 5E-12, /* sclkstab */ {3.0, 0.9999, 0.20}, /* thresar */ 0.0, 0.0, 0.05, /* elmaskar,almaskhold,thresslip */ 30.0, 30.0, 30.0, /* maxtdif,maxinno,maxgdop */ {0}, {0}, {0}, /* baseline,ru,rb */ {"", ""}, /* anttype */ {{0}}, {{0}}, {0} /* antdel,pcv,exsats */ }; const solopt_t solopt_default = { /* defaults solution output options */ SOLF_LLH, TIMES_GPST, 1, 3, /* posf,times,timef,timeu */ 0, 1, 0, 0, 0, 0, /* degf,outhead,outopt,datum,height,geoid */ 0, 0, 0, /* solstatic,sstat,trace */ {0.0, 0.0}, /* nmeaintv */ " ", "" /* separator/program name */ }; const char* formatstrs[] = { /* stream format strings */ "RTCM 2", /* 0 */ "RTCM 3", /* 1 */ "NovAtel OEM6", /* 2 */ "NovAtel OEM3", /* 3 */ "u-blox", /* 4 */ "Superstar II", /* 5 */ "Hemisphere", /* 6 */ "SkyTraq", /* 7 */ "GW10", /* 8 */ "Javad", /* 9 */ "NVS BINR", /* 10 */ "BINEX", /* 11 */ "Trimble RT17", /* 12 */ "LEX Receiver", /* 13 */ "Septentrio", /* 14 */ "RINEX", /* 15 */ "SP3", /* 16 */ "RINEX CLK", /* 17 */ "SBAS", /* 18 */ "NMEA 0183", /* 19 */ NULL}; static char* obscodes[] = { /* observation code strings */ "", "1C", "1P", "1W", "1Y", "1M", "1N", "1S", "1L", "1E", /* 0- 9 */ "1A", "1B", "1X", "1Z", "2C", "2D", "2S", "2L", "2X", "2P", /* 10-19 */ "2W", "2Y", "2M", "2N", "5I", "5Q", "5X", "7I", "7Q", "7X", /* 20-29 */ "6A", "6B", "6C", "6X", "6Z", "6S", "6L", "8L", "8Q", "8X", /* 30-39 */ "2I", "2Q", "6I", "6Q", "3I", "3Q", "3X", "1I", "1Q", "" /* 40-49 */ }; static unsigned char obsfreqs[] = { /* 1:L1,2:L2,3:L5,4:L6,5:L7,6:L8,7:L3 */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0- 9 */ 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, /* 10-19 */ 2, 2, 2, 2, 3, 3, 3, 5, 5, 5, /* 20-29 */ 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, /* 30-39 */ 2, 2, 4, 4, 3, 3, 3, 1, 1, 0 /* 40-49 */ }; static char codepris[6][MAXFREQ][16] = { /* code priority table */ /* L1,G1E1a L2,G2,B1 L5,G3,E5a L6,LEX,B3 E5a,B2 E5a+b */ {"CPYWMNSL", "PYWCMNDSLX", "IQX", "", "", ""}, /* GPS */ {"PC", "PC", "IQX", "", "", ""}, /* GLO */ {"CABXZ", "", "IQX", "ABCXZ", "IQX", "IQX"}, /* GAL */ {"CSLXZ", "SLX", "IQX", "SLX", "", ""}, /* QZS */ {"C", "", "IQX", "", "", ""}, /* SBS */ {"IQX", "IQX", "IQX", "IQX", "IQX", ""} /* BDS */ }; /* crc tables generated by util/gencrc ---------------------------------------*/ static const unsigned short tbl_CRC16[] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0}; static const unsigned int tbl_CRC24Q[] = { 0x000000, 0x864CFB, 0x8AD50D, 0x0C99F6, 0x93E6E1, 0x15AA1A, 0x1933EC, 0x9F7F17, 0xA18139, 0x27CDC2, 0x2B5434, 0xAD18CF, 0x3267D8, 0xB42B23, 0xB8B2D5, 0x3EFE2E, 0xC54E89, 0x430272, 0x4F9B84, 0xC9D77F, 0x56A868, 0xD0E493, 0xDC7D65, 0x5A319E, 0x64CFB0, 0xE2834B, 0xEE1ABD, 0x685646, 0xF72951, 0x7165AA, 0x7DFC5C, 0xFBB0A7, 0x0CD1E9, 0x8A9D12, 0x8604E4, 0x00481F, 0x9F3708, 0x197BF3, 0x15E205, 0x93AEFE, 0xAD50D0, 0x2B1C2B, 0x2785DD, 0xA1C926, 0x3EB631, 0xB8FACA, 0xB4633C, 0x322FC7, 0xC99F60, 0x4FD39B, 0x434A6D, 0xC50696, 0x5A7981, 0xDC357A, 0xD0AC8C, 0x56E077, 0x681E59, 0xEE52A2, 0xE2CB54, 0x6487AF, 0xFBF8B8, 0x7DB443, 0x712DB5, 0xF7614E, 0x19A3D2, 0x9FEF29, 0x9376DF, 0x153A24, 0x8A4533, 0x0C09C8, 0x00903E, 0x86DCC5, 0xB822EB, 0x3E6E10, 0x32F7E6, 0xB4BB1D, 0x2BC40A, 0xAD88F1, 0xA11107, 0x275DFC, 0xDCED5B, 0x5AA1A0, 0x563856, 0xD074AD, 0x4F0BBA, 0xC94741, 0xC5DEB7, 0x43924C, 0x7D6C62, 0xFB2099, 0xF7B96F, 0x71F594, 0xEE8A83, 0x68C678, 0x645F8E, 0xE21375, 0x15723B, 0x933EC0, 0x9FA736, 0x19EBCD, 0x8694DA, 0x00D821, 0x0C41D7, 0x8A0D2C, 0xB4F302, 0x32BFF9, 0x3E260F, 0xB86AF4, 0x2715E3, 0xA15918, 0xADC0EE, 0x2B8C15, 0xD03CB2, 0x567049, 0x5AE9BF, 0xDCA544, 0x43DA53, 0xC596A8, 0xC90F5E, 0x4F43A5, 0x71BD8B, 0xF7F170, 0xFB6886, 0x7D247D, 0xE25B6A, 0x641791, 0x688E67, 0xEEC29C, 0x3347A4, 0xB50B5F, 0xB992A9, 0x3FDE52, 0xA0A145, 0x26EDBE, 0x2A7448, 0xAC38B3, 0x92C69D, 0x148A66, 0x181390, 0x9E5F6B, 0x01207C, 0x876C87, 0x8BF571, 0x0DB98A, 0xF6092D, 0x7045D6, 0x7CDC20, 0xFA90DB, 0x65EFCC, 0xE3A337, 0xEF3AC1, 0x69763A, 0x578814, 0xD1C4EF, 0xDD5D19, 0x5B11E2, 0xC46EF5, 0x42220E, 0x4EBBF8, 0xC8F703, 0x3F964D, 0xB9DAB6, 0xB54340, 0x330FBB, 0xAC70AC, 0x2A3C57, 0x26A5A1, 0xA0E95A, 0x9E1774, 0x185B8F, 0x14C279, 0x928E82, 0x0DF195, 0x8BBD6E, 0x872498, 0x016863, 0xFAD8C4, 0x7C943F, 0x700DC9, 0xF64132, 0x693E25, 0xEF72DE, 0xE3EB28, 0x65A7D3, 0x5B59FD, 0xDD1506, 0xD18CF0, 0x57C00B, 0xC8BF1C, 0x4EF3E7, 0x426A11, 0xC426EA, 0x2AE476, 0xACA88D, 0xA0317B, 0x267D80, 0xB90297, 0x3F4E6C, 0x33D79A, 0xB59B61, 0x8B654F, 0x0D29B4, 0x01B042, 0x87FCB9, 0x1883AE, 0x9ECF55, 0x9256A3, 0x141A58, 0xEFAAFF, 0x69E604, 0x657FF2, 0xE33309, 0x7C4C1E, 0xFA00E5, 0xF69913, 0x70D5E8, 0x4E2BC6, 0xC8673D, 0xC4FECB, 0x42B230, 0xDDCD27, 0x5B81DC, 0x57182A, 0xD154D1, 0x26359F, 0xA07964, 0xACE092, 0x2AAC69, 0xB5D37E, 0x339F85, 0x3F0673, 0xB94A88, 0x87B4A6, 0x01F85D, 0x0D61AB, 0x8B2D50, 0x145247, 0x921EBC, 0x9E874A, 0x18CBB1, 0xE37B16, 0x6537ED, 0x69AE1B, 0xEFE2E0, 0x709DF7, 0xF6D10C, 0xFA48FA, 0x7C0401, 0x42FA2F, 0xC4B6D4, 0xC82F22, 0x4E63D9, 0xD11CCE, 0x575035, 0x5BC9C3, 0xDD8538}; /* function prototypes -------------------------------------------------------*/ #ifdef MKL #define LAPACK #define dgemm_ dgemm #define dgetrf_ dgetrf #define dgetri_ dgetri #define dgetrs_ dgetrs #endif #ifdef LAPACK extern void dgemm_(char*, char*, int*, int*, int*, double*, double*, int*, double*, int*, double*, double*, int*); extern void dgetrf_(int*, int*, double*, int*, int*, int*); extern void dgetri_(int*, double*, int*, int*, double*, int*, int*); extern void dgetrs_(char*, int*, int*, double*, int*, int*, double*, int*, int*); #endif #ifdef IERS_MODEL extern int gmf_(double* mjd, double* lat, double* lon, double* hgt, double* zd, double* gmfh, double* gmfw); #endif /* fatal error ---------------------------------------------------------------*/ static void fatalerr(const char* format, ...) { va_list ap; va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); exit(-9); } /* satellite system+prn/slot number to satellite number ------------------------ * convert satellite system+prn/slot number to satellite number * args : int sys I satellite system (SYS_GPS,SYS_GLO,...) * int prn I satellite prn/slot number * return : satellite number (0:error) *-----------------------------------------------------------------------------*/ extern int satno(int sys, int prn) { if (prn <= 0) { return 0; } switch (sys) { case SYS_GPS: if (prn < MINPRNGPS || MAXPRNGPS < prn) { return 0; } return prn - MINPRNGPS + 1; case SYS_GLO: if (prn < MINPRNGLO || MAXPRNGLO < prn) { return 0; } return NSATGPS + prn - MINPRNGLO + 1; case SYS_GAL: if (prn < MINPRNGAL || MAXPRNGAL < prn) { return 0; } return NSATGPS + NSATGLO + prn - MINPRNGAL + 1; case SYS_QZS: if (prn < MINPRNQZS || MAXPRNQZS < prn) { return 0; } return NSATGPS + NSATGLO + NSATGAL + prn - MINPRNQZS + 1; case SYS_CMP: if (prn < MINPRNCMP || MAXPRNCMP < prn) { return 0; } return NSATGPS + NSATGLO + NSATGAL + NSATQZS + prn - MINPRNCMP + 1; case SYS_LEO: if (prn < MINPRNLEO || MAXPRNLEO < prn) { return 0; } return NSATGPS + NSATGLO + NSATGAL + NSATQZS + NSATCMP + prn - MINPRNLEO + 1; case SYS_SBS: if (prn < MINPRNSBS || MAXPRNSBS < prn) { return 0; } return NSATGPS + NSATGLO + NSATGAL + NSATQZS + NSATCMP + NSATLEO + prn - MINPRNSBS + 1; } return 0; } /* satellite number to satellite system ---------------------------------------- * convert satellite number to satellite system * args : int sat I satellite number (1-MAXSAT) * int *prn IO satellite prn/slot number (NULL: no output) * return : satellite system (SYS_GPS,SYS_GLO,...) *-----------------------------------------------------------------------------*/ extern int satsys(int sat, int* prn) { int sys = SYS_NONE; if (sat <= 0 || MAXSAT < sat) { sat = 0; } else if (sat <= NSATGPS) { sys = SYS_GPS; sat += MINPRNGPS - 1; } else if ((sat -= NSATGPS) <= NSATGLO) { sys = SYS_GLO; sat += MINPRNGLO - 1; } else if ((sat -= NSATGLO) <= NSATGAL) { sys = SYS_GAL; sat += MINPRNGAL - 1; } else if ((sat -= NSATGAL) <= NSATQZS) { sys = SYS_QZS; sat += MINPRNQZS - 1; } else if ((sat -= NSATQZS) <= NSATCMP) { sys = SYS_CMP; sat += MINPRNCMP - 1; } else if ((sat -= NSATCMP) <= NSATLEO) { sys = SYS_LEO; sat += MINPRNLEO - 1; } else if ((sat -= NSATLEO) <= NSATSBS) { sys = SYS_SBS; sat += MINPRNSBS - 1; } else { sat = 0; } if (prn) { *prn = sat; } return sys; } /* satellite id to satellite number -------------------------------------------- * convert satellite id to satellite number * args : char *id I satellite id (nn,Gnn,Rnn,Enn,Jnn,Cnn or Snn) * return : satellite number (0: error) * notes : 120-138 and 193-195 are also recognized as sbas and qzss *-----------------------------------------------------------------------------*/ extern int satid2no(const char* id) { int sys, prn; char code; if (sscanf(id, "%d", &prn) == 1) { if (MINPRNGPS <= prn && prn <= MAXPRNGPS) { sys = SYS_GPS; } else if (MINPRNSBS <= prn && prn <= MAXPRNSBS) { sys = SYS_SBS; } else if (MINPRNQZS <= prn && prn <= MAXPRNQZS) { sys = SYS_QZS; } else { return 0; } return satno(sys, prn); } if (sscanf(id, "%c%d", &code, &prn) < 2) { return 0; } switch (code) { case 'G': sys = SYS_GPS; prn += MINPRNGPS - 1; break; case 'R': sys = SYS_GLO; prn += MINPRNGLO - 1; break; case 'E': sys = SYS_GAL; prn += MINPRNGAL - 1; break; case 'J': sys = SYS_QZS; prn += MINPRNQZS - 1; break; case 'C': sys = SYS_CMP; prn += MINPRNCMP - 1; break; case 'L': sys = SYS_LEO; prn += MINPRNLEO - 1; break; case 'S': sys = SYS_SBS; prn += 100; break; default: return 0; } return satno(sys, prn); } /* satellite number to satellite id -------------------------------------------- * convert satellite number to satellite id * args : int sat I satellite number * char *id O satellite id (Gnn,Rnn,Enn,Jnn,Cnn or nnn) * return : none *-----------------------------------------------------------------------------*/ extern void satno2id(int sat, char* id) { int prn; switch (satsys(sat, &prn)) { case SYS_GPS: sprintf(id, "G%02d", prn - MINPRNGPS + 1); return; case SYS_GLO: sprintf(id, "R%02d", prn - MINPRNGLO + 1); return; case SYS_GAL: sprintf(id, "E%02d", prn - MINPRNGAL + 1); return; case SYS_QZS: sprintf(id, "J%02d", prn - MINPRNQZS + 1); return; case SYS_CMP: sprintf(id, "C%02d", prn - MINPRNCMP + 1); return; case SYS_LEO: sprintf(id, "L%02d", prn - MINPRNLEO + 1); return; case SYS_SBS: sprintf(id, "%03d", prn); return; } strcpy(id, ""); } /* test excluded satellite ----------------------------------------------------- * test excluded satellite * args : int sat I satellite number * int svh I sv health flag * prcopt_t *opt I processing options (NULL: not used) * return : status (1:excluded,0:not excluded) *-----------------------------------------------------------------------------*/ extern int satexclude(int sat, int svh, const prcopt_t* opt) { int sys = satsys(sat, NULL); if (svh < 0) { return 1; /* ephemeris unavailable */ } if (opt) { if (opt->exsats[sat - 1] == 1) { return 1; /* excluded satellite */ } if (opt->exsats[sat - 1] == 2) { return 0; /* included satellite */ } if (!(sys & opt->navsys)) { return 1; /* unselected sat sys */ } } if (sys == SYS_QZS) { svh &= 0xFE; /* mask QZSS LEX health */ } if (svh) { trace(3, "unhealthy satellite: sat=%3d svh=%02X\n", sat, svh); return 1; } return 0; } /* test SNR mask --------------------------------------------------------------- * test SNR mask * args : int base I rover or base-station (0:rover,1:base station) * int freq I frequency (0:L1,1:L2,2:L3,...) * double el I elevation angle (rad) * double snr I C/N0 (dBHz) * snrmask_t *mask I SNR mask * return : status (1:masked,0:unmasked) *-----------------------------------------------------------------------------*/ extern int testsnr(int base, int freq, double el, double snr, const snrmask_t* mask) { double minsnr, a; int i; if (!mask->ena[base] || freq < 0 || freq >= NFREQ) { return 0; } a = (el * R2D + 5.0) / 10.0; i = (int)floor(a); a -= i; if (i < 1) { minsnr = mask->mask[freq][0]; } else if (i > 8) { minsnr = mask->mask[freq][8]; } else { minsnr = (1.0 - a) * mask->mask[freq][i - 1] + a * mask->mask[freq][i]; } return snr < minsnr; } /* obs type string to obs code ------------------------------------------------- * convert obs code type string to obs code * args : char *str I obs code string ("1C","1P","1Y",...) * int *freq IO frequency (1:L1,2:L2,3:L5,4:L6,5:L7,6:L8,0:err) * (NULL: no output) * return : obs code (CODE_???) * notes : obs codes are based on reference [6] and qzss extension *-----------------------------------------------------------------------------*/ extern unsigned char obs2code(const char* obs, int* freq) { int i; if (freq) { *freq = 0; } for (i = 1; *obscodes[i]; ++i) { if (strcmp(obscodes[i], obs)) { continue; } if (freq) { *freq = obsfreqs[i]; } return (unsigned char)i; } return CODE_NONE; } /* obs code to obs code string ------------------------------------------------- * convert obs code to obs code string * args : unsigned char code I obs code (CODE_???) * int *freq IO frequency (1:L1,2:L2,3:L5,4:L6,5:L7,6:L8,0:err) * (NULL: no output) * return : obs code string ("1C","1P","1P",...) * notes : obs codes are based on reference [6] and qzss extension *-----------------------------------------------------------------------------*/ extern char* code2obs(unsigned char code, int* freq) { if (freq) { *freq = 0; } if (code <= CODE_NONE || MAXCODE < code) { return ""; } if (freq) { *freq = obsfreqs[code]; } return obscodes[code]; } /* set code priority ----------------------------------------------------------- * set code priority for multiple codes in a frequency * args : int sys I system (or of SYS_???) * int freq I frequency (1:L1,2:L2,3:L5,4:L6,5:L7,6:L8) * char *pri I priority of codes (series of code characters) * (higher priority precedes lower) * return : none *-----------------------------------------------------------------------------*/ extern void setcodepri(int sys, int freq, const char* pri) { trace(3, "setcodepri:sys=%d freq=%d pri=%s\n", sys, freq, pri); if (freq <= 0 || MAXFREQ < freq) { return; } if (sys & SYS_GPS) { strcpy(codepris[0][freq - 1], pri); } if (sys & SYS_GLO) { strcpy(codepris[1][freq - 1], pri); } if (sys & SYS_GAL) { strcpy(codepris[2][freq - 1], pri); } if (sys & SYS_QZS) { strcpy(codepris[3][freq - 1], pri); } if (sys & SYS_SBS) { strcpy(codepris[4][freq - 1], pri); } if (sys & SYS_CMP) { strcpy(codepris[5][freq - 1], pri); } } /* get code priority ----------------------------------------------------------- * get code priority for multiple codes in a frequency * args : int sys I system (SYS_???) * unsigned char code I obs code (CODE_???) * char *opt I code options (NULL:no option) * return : priority (15:highest-1:lowest,0:error) *-----------------------------------------------------------------------------*/ extern int getcodepri(int sys, unsigned char code, const char* opt) { const char *p, *optstr; char *obs, str[8] = ""; int i, j; switch (sys) { case SYS_GPS: i = 0; optstr = "-GL%2s"; break; case SYS_GLO: i = 1; optstr = "-RL%2s"; break; case SYS_GAL: i = 2; optstr = "-EL%2s"; break; case SYS_QZS: i = 3; optstr = "-JL%2s"; break; case SYS_SBS: i = 4; optstr = "-SL%2s"; break; case SYS_CMP: i = 5; optstr = "-CL%2s"; break; default: return 0; } obs = code2obs(code, &j); /* parse code options */ for (p = opt; p && (p = strchr(p, '-')); p++) { if (sscanf(p, optstr, str) < 1 || str[0] != obs[0]) { continue; } return str[1] == obs[1] ? 15 : 0; } /* search code priority */ return (p = strchr(codepris[i][j - 1], obs[1])) ? 14 - (int)(p - codepris[i][j - 1]) : 0; } /* extract unsigned/signed bits ------------------------------------------------ * extract unsigned/signed bits from byte data * args : unsigned char *buff I byte data * int pos I bit position from start of data (bits) * int len I bit length (bits) (len<=32) * return : extracted unsigned/signed bits *-----------------------------------------------------------------------------*/ extern unsigned int getbitu(const unsigned char* buff, int pos, int len) { unsigned int bits = 0; int i; for (i = pos; i < pos + len; ++i) { bits = (bits << 1) + ((buff[i / 8] >> (7 - i % 8)) & 1u); } return bits; } extern int getbits(const unsigned char* buff, int pos, int len) { unsigned int bits = getbitu(buff, pos, len); if (len <= 0 || 32 <= len || !(bits & (1u << (len - 1)))) { return (int)bits; } return (int)(bits | (~0u << len)); /* extend sign */ } /* set unsigned/signed bits ---------------------------------------------------- * set unsigned/signed bits to byte data * args : unsigned char *buff IO byte data * int pos I bit position from start of data (bits) * int len I bit length (bits) (len<=32) * (unsigned) int I unsigned/signed data * return : none *-----------------------------------------------------------------------------*/ extern void setbitu(unsigned char* buff, int pos, int len, unsigned int data) { if (len <= 0 || 32 < len) { return; } unsigned int mask = 1u << (len - 1); int i; for (i = pos; i < pos + len; ++i, mask >>= 1) { if (data & mask) { buff[i / 8] |= 1u << (7 - i % 8); } else { buff[i / 8] &= ~(1u << (7 - i % 8)); } } } extern void setbits(unsigned char* buff, int pos, int len, int data) { if (data < 0) { data |= 1 << (len - 1); } else { data &= ~(1 << (len - 1)); /* set sign bit */ } setbitu(buff, pos, len, (unsigned int)data); } /* crc-32 parity --------------------------------------------------------------- * compute crc-32 parity for novatel raw * args : unsigned char *buff I data * int len I data length (bytes) * return : crc-32 parity * notes : see NovAtel OEMV firmware manual 1.7 32-bit CRC *-----------------------------------------------------------------------------*/ extern unsigned int crc32(const unsigned char* buff, int len) { unsigned int crc = 0; int i, j; trace(4, "crc32: len=%d\n", len); for (i = 0; i < len; ++i) { crc ^= buff[i]; for (j = 0; j < 8; ++j) { if (crc & 1) { crc = (crc >> 1) ^ POLYCRC32; } else { crc >>= 1; } } } return crc; } /* crc-24q parity -------------------------------------------------------------- * compute crc-24q parity for sbas, rtcm3 * args : unsigned char *buff I data * int len I data length (bytes) * return : crc-24Q parity * notes : see reference [2] A.4.3.3 Parity *-----------------------------------------------------------------------------*/ extern unsigned int crc24q(const unsigned char* buff, int len) { unsigned int crc = 0; int i; trace(4, "crc24q: len=%d\n", len); for (i = 0; i < len; ++i) { crc = ((crc << 8) & 0xFFFFFF) ^ tbl_CRC24Q[(crc >> 16) ^ buff[i]]; } return crc; } /* crc-16 parity --------------------------------------------------------------- * compute crc-16 parity for binex, nvs * args : unsigned char *buff I data * int len I data length (bytes) * return : crc-16 parity * notes : see reference [10] A.3. *-----------------------------------------------------------------------------*/ extern unsigned short crc16(const unsigned char* buff, int len) { unsigned short crc = 0; int i; trace(4, "crc16: len=%d\n", len); for (i = 0; i < len; ++i) { crc = (crc << 8) ^ tbl_CRC16[((crc >> 8) ^ buff[i]) & 0xFF]; } return crc; } /* decode navigation data word ------------------------------------------------- * check party and decode navigation data word * args : unsigned int word I navigation data word (2+30bit) * (previous word D29*-30* + current word D1-30) * unsigned char *data O decoded navigation data without parity * (8bitx3) * return : status (1:ok,0:parity error) * notes : see reference [1] 20.3.5.2 user parity algorithm *-----------------------------------------------------------------------------*/ extern int decode_word(unsigned int word, unsigned char* data) { const unsigned int hamming[] = {0xBB1F3480, 0x5D8F9A40, 0xAEC7CD00, 0x5763E680, 0x6BB1F340, 0x8B7A89C0}; unsigned int parity = 0, w; int i; trace(5, "decodeword: word=%08x\n", word); if (word & 0x40000000) { word ^= 0x3FFFFFC0; } for (i = 0; i < 6; ++i) { parity <<= 1; for (w = (word & hamming[i]) >> 6; w; w >>= 1) { parity ^= w & 1; } } if (parity != (word & 0x3F)) { return 0; } for (i = 0; i < 3; ++i) { data[i] = (unsigned char)(word >> (22 - i * 8)); } return 1; } /* new matrix ------------------------------------------------------------------ * allocate memory of matrix * args : int n,m I number of rows and columns of matrix * return : matrix pointer (if n<=0 or m<=0, return NULL) *-----------------------------------------------------------------------------*/ extern double* mat(int n, int m) { double* p; if (n <= 0 || m <= 0) { return NULL; } if (!(p = (double*)malloc(sizeof(double) * n * m))) { fatalerr("matrix memory allocation error: n=%d,m=%d\n", n, m); } return p; } /* new integer matrix ---------------------------------------------------------- * allocate memory of integer matrix * args : int n,m I number of rows and columns of matrix * return : matrix pointer (if n<=0 or m<=0, return NULL) *-----------------------------------------------------------------------------*/ extern int* imat(int n, int m) { int* p; if (n <= 0 || m <= 0) { return NULL; } if (!(p = (int*)malloc(sizeof(int) * n * m))) { fatalerr("integer matrix memory allocation error: n=%d,m=%d\n", n, m); } return p; } /* zero matrix ----------------------------------------------------------------- * generate new zero matrix * args : int n,m I number of rows and columns of matrix * return : matrix pointer (if n<=0 or m<=0, return NULL) *-----------------------------------------------------------------------------*/ extern double* zeros(int n, int m) { double* p; #if NOCALLOC if ((p = mat(n, m))) { for (n = n * m - 1; n >= 0; --n) { p[n] = 0.0; } } #else if (n <= 0 || m <= 0) { return NULL; } if (!(p = (double*)calloc(sizeof(double), n * m))) { fatalerr("matrix memory allocation error: n=%d,m=%d\n", n, m); } #endif return p; } /* identity matrix ------------------------------------------------------------- * generate new identity matrix * args : int n I number of rows and columns of matrix * return : matrix pointer (if n<=0, return NULL) *-----------------------------------------------------------------------------*/ extern double* eye(int n) { double* p; int i; if ((p = zeros(n, n))) { for (i = 0; i < n; ++i) { p[i + i * n] = 1.0; } } return p; } /* inner product --------------------------------------------------------------- * inner product of vectors * args : double *a,*b I vector a,b (n x 1) * int n I size of vector a,b * return : a'*b *-----------------------------------------------------------------------------*/ extern double dot(const double* a, const double* b, int n) { double c = 0.0; while (--n >= 0) { c += a[n] * b[n]; } return c; } /* euclid norm ----------------------------------------------------------------- * euclid norm of vector * args : double *a I vector a (n x 1) * int n I size of vector a * return : || a || *-----------------------------------------------------------------------------*/ extern double norm(const double* a, int n) { return sqrt(dot(a, a, n)); } /* outer product of 3d vectors ------------------------------------------------- * outer product of 3d vectors * args : double *a,*b I vector a,b (3 x 1) * double *c O outer product (a x b) (3 x 1) * return : none *-----------------------------------------------------------------------------*/ extern void cross3(const double* a, const double* b, double* c) { c[0] = a[1] * b[2] - a[2] * b[1]; c[1] = a[2] * b[0] - a[0] * b[2]; c[2] = a[0] * b[1] - a[1] * b[0]; } /* normalize 3d vector --------------------------------------------------------- * normalize 3d vector * args : double *a I vector a (3 x 1) * double *b O normlized vector (3 x 1) || b || = 1 * return : status (1:ok,0:error) *-----------------------------------------------------------------------------*/ extern int normv3(const double* a, double* b) { double r; if ((r = norm(a, 3)) <= 0.0) { return 0; } b[0] = a[0] / r; b[1] = a[1] / r; b[2] = a[2] / r; return 1; } /* copy matrix ----------------------------------------------------------------- * copy matrix * args : double *A O destination matrix A (n x m) * double *B I source matrix B (n x m) * int n,m I number of rows and columns of matrix * return : none *-----------------------------------------------------------------------------*/ extern void matcpy(double* A, const double* B, int n, int m) { memcpy(A, B, sizeof(double) * n * m); } /* matrix routines -----------------------------------------------------------*/ #ifdef LAPACK /* with LAPACK/BLAS or MKL */ /* multiply matrix (wrapper of blas dgemm) ------------------------------------- * multiply matrix by matrix (C=alpha*A*B+beta*C) * args : char *tr I transpose flags ("N":normal,"T":transpose) * int n,k,m I size of (transposed) matrix A,B * double alpha I alpha * double *A,*B I (transposed) matrix A (n x m), B (m x k) * double beta I beta * double *C IO matrix C (n x k) * return : none *-----------------------------------------------------------------------------*/ extern void matmul(const char* tr, int n, int k, int m, double alpha, const double* A, const double* B, double beta, double* C) { int lda = tr[0] == 'T' ? m : n, ldb = tr[1] == 'T' ? k : m; dgemm_((char*)tr, (char*)tr + 1, &n, &k, &m, &alpha, (double*)A, &lda, (double*)B, &ldb, &beta, C, &n); } /* inverse of matrix ----------------------------------------------------------- * inverse of matrix (A=A^-1) * args : double *A IO matrix (n x n) * int n I size of matrix A * return : status (0:ok,0>:error) *-----------------------------------------------------------------------------*/ extern int matinv(double* A, int n) { double* work; int info, lwork = n * 16, *ipiv = imat(n, 1); work = mat(lwork, 1); dgetrf_(&n, &n, A, &n, ipiv, &info); if (!info) { dgetri_(&n, A, &n, ipiv, work, &lwork, &info); } free(ipiv); free(work); return info; } /* solve linear equation ------------------------------------------------------- * solve linear equation (X=A\Y or X=A'\Y) * args : char *tr I transpose flag ("N":normal,"T":transpose) * double *A I input matrix A (n x n) * double *Y I input matrix Y (n x m) * int n,m I size of matrix A,Y * double *X O X=A\Y or X=A'\Y (n x m) * return : status (0:ok,0>:error) * notes : matirix stored by column-major order (fortran convention) * X can be same as Y *-----------------------------------------------------------------------------*/ extern int solve(const char* tr, const double* A, const double* Y, int n, int m, double* X) { double* B = mat(n, n); int info, *ipiv = imat(n, 1); matcpy(B, A, n, n); matcpy(X, Y, n, m); dgetrf_(&n, &n, B, &n, ipiv, &info); if (!info) { dgetrs_((char*)tr, &n, &m, B, &n, ipiv, X, &n, &info); } free(ipiv); free(B); return info; } #else /* without LAPACK/BLAS or MKL */ /* multiply matrix -----------------------------------------------------------*/ extern void matmul(const char* tr, int n, int k, int m, double alpha, const double* A, const double* B, double beta, double* C) { double d; int i, j, x, f = tr[0] == 'N' ? (tr[1] == 'N' ? 1 : 2) : (tr[1] == 'N' ? 3 : 4); for (i = 0; i < n; ++i) for (j = 0; j < k; ++j) { d = 0.0; switch (f) { case 1: for (x = 0; x < m; x++) { d += A[i + x * n] * B[x + j * m]; } break; case 2: for (x = 0; x < m; x++) { d += A[i + x * n] * B[j + x * k]; } break; case 3: for (x = 0; x < m; x++) { d += A[x + i * m] * B[x + j * m]; } break; case 4: for (x = 0; x < m; x++) { d += A[x + i * m] * B[j + x * k]; } break; } if (beta == 0.0) { C[i + j * n] = alpha * d; } else { C[i + j * n] = alpha * d + beta * C[i + j * n]; } } } /* LU decomposition ----------------------------------------------------------*/ static int ludcmp(double* A, int n, int* indx, double* d) { double big, s, tmp, *vv = mat(n, 1); int i, imax = 0, j, k; *d = 1.0; for (i = 0; i < n; ++i) { big = 0.0; for (j = 0; j < n; ++j) { if ((tmp = fabs(A[i + j * n])) > big) { big = tmp; } } if (big > 0.0) { vv[i] = 1.0 / big; } else { free(vv); return -1; } } for (j = 0; j < n; ++j) { for (i = 0; i < j; ++i) { s = A[i + j * n]; for (k = 0; k < i; ++k) { s -= A[i + k * n] * A[k + j * n]; } A[i + j * n] = s; } big = 0.0; for (i = j; i < n; ++i) { s = A[i + j * n]; for (k = 0; k < j; ++k) { s -= A[i + k * n] * A[k + j * n]; } A[i + j * n] = s; if ((tmp = vv[i] * fabs(s)) >= big) { big = tmp; imax = i; } } if (j != imax) { for (k = 0; k < n; ++k) { tmp = A[imax + k * n]; A[imax + k * n] = A[j + k * n]; A[j + k * n] = tmp; } *d = -(*d); vv[imax] = vv[j]; } indx[j] = imax; if (A[j + j * n] == 0.0) { free(vv); return -1; } if (j != n - 1) { tmp = 1.0 / A[j + j * n]; for (i = j + 1; i < n; ++i) { A[i + j * n] *= tmp; } } } free(vv); return 0; } /* LU back-substitution ------------------------------------------------------*/ static void lubksb(const double* A, int n, const int* indx, double* b) { double s; int i, ii = -1, ip, j; for (i = 0; i < n; ++i) { ip = indx[i]; s = b[ip]; b[ip] = b[i]; if (ii >= 0) { for (j = ii; j < i; ++j) { s -= A[i + j * n] * b[j]; } } else if (s) { ii = i; } b[i] = s; } for (i = n - 1; i >= 0; --i) { s = b[i]; for (j = i + 1; j < n; ++j) { s -= A[i + j * n] * b[j]; } b[i] = s / A[i + i * n]; } } /* inverse of matrix ---------------------------------------------------------*/ extern int matinv(double* A, int n) { double d, *B; int i, j, *indx; indx = imat(n, 1); B = mat(n, n); matcpy(B, A, n, n); if (ludcmp(B, n, indx, &d)) { free(indx); free(B); return -1; } for (j = 0; j < n; ++j) { for (i = 0; i < n; ++i) { A[i + j * n] = 0.0; } A[j + j * n] = 1.0; lubksb(B, n, indx, A + j * n); } free(indx); free(B); return 0; } /* solve linear equation -----------------------------------------------------*/ extern int solve(const char* tr, const double* A, const double* Y, int n, int m, double* X) { double* B = mat(n, n); int info; matcpy(B, A, n, n); if (!(info = matinv(B, n))) { matmul(tr[0] == 'N' ? "NN" : "TN", n, m, n, 1.0, B, Y, 0.0, X); } free(B); return info; } #endif /* end of matrix routines ----------------------------------------------------*/ /* least square estimation ----------------------------------------------------- * least square estimation by solving normal equation (x=(A*A')^-1*A*y) * args : double *A I transpose of (weighted) design matrix (n x m) * double *y I (weighted) measurements (m x 1) * int n,m I number of parameters and measurements (n<=m) * double *x O estmated parameters (n x 1) * double *Q O esimated parameters covariance matrix (n x n) * return : status (0:ok,0>:error) * notes : for weighted least square, replace A and y by A*w and w*y (w=W^(1/2)) * matirix stored by column-major order (fortran convention) *-----------------------------------------------------------------------------*/ extern int lsq(const double* A, const double* y, int n, int m, double* x, double* Q) { double* Ay; int info; if (m < n) { return -1; } Ay = mat(n, 1); matmul("NN", n, 1, m, 1.0, A, y, 0.0, Ay); /* Ay=A*y */ matmul("NT", n, n, m, 1.0, A, A, 0.0, Q); /* Q=A*A' */ if (!(info = matinv(Q, n))) { matmul("NN", n, 1, n, 1.0, Q, Ay, 0.0, x); /* x=Q^-1*Ay */ } free(Ay); return info; } /* kalman filter --------------------------------------------------------------- * kalman filter state update as follows: * * K=P*H*(H'*P*H+R)^-1, xp=x+K*v, Pp=(I-K*H')*P * * args : double *x I states vector (n x 1) * double *P I covariance matrix of states (n x n) * double *H I transpose of design matrix (n x m) * double *v I innovation (measurement - model) (m x 1) * double *R I covariance matrix of measurement error (m x m) * int n,m I number of states and measurements * double *xp O states vector after update (n x 1) * double *Pp O covariance matrix of states after update (n x n) * return : status (0:ok,<0:error) * notes : matirix stored by column-major order (fortran convention) * if state x[i]==0.0, not updates state x[i]/P[i+i*n] *-----------------------------------------------------------------------------*/ static int filter_(const double* x, const double* P, const double* H, const double* v, const double* R, int n, int m, double* xp, double* Pp) { double *F = mat(n, m), *Q = mat(m, m), *K = mat(n, m), *I = eye(n); int info; matcpy(Q, R, m, m); matcpy(xp, x, n, 1); matmul("NN", n, m, n, 1.0, P, H, 0.0, F); /* Q=H'*P*H+R */ matmul("TN", m, m, n, 1.0, H, F, 1.0, Q); if (!(info = matinv(Q, m))) { matmul("NN", n, m, m, 1.0, F, Q, 0.0, K); /* K=P*H*Q^-1 */ matmul("NN", n, 1, m, 1.0, K, v, 1.0, xp); /* xp=x+K*v */ matmul("NT", n, n, m, -1.0, K, H, 1.0, I); /* Pp=(I-K*H')*P */ matmul("NN", n, n, n, 1.0, I, P, 0.0, Pp); } free(F); free(Q); free(K); free(I); return info; } extern int filter(double* x, double* P, const double* H, const double* v, const double* R, int n, int m) { double *x_, *xp_, *P_, *Pp_, *H_; int i, j, k, info, *ix; ix = imat(n, 1); for (i = k = 0; i < n; ++i) { if (x[i] != 0.0 && P[i + i * n] > 0.0) { ix[k++] = i; } } x_ = mat(k, 1); xp_ = mat(k, 1); P_ = mat(k, k); Pp_ = mat(k, k); H_ = mat(k, m); for (i = 0; i < k; ++i) { x_[i] = x[ix[i]]; for (j = 0; j < k; ++j) { P_[i + j * k] = P[ix[i] + ix[j] * n]; } for (j = 0; j < m; ++j) { H_[i + j * k] = H[ix[i] + j * n]; } } info = filter_(x_, P_, H_, v, R, k, m, xp_, Pp_); for (i = 0; i < k; ++i) { x[ix[i]] = xp_[i]; for (j = 0; j < k; ++j) { P[ix[i] + ix[j] * n] = Pp_[i + j * k]; } } free(ix); free(x_); free(xp_); free(P_); free(Pp_); free(H_); return info; } /* smoother -------------------------------------------------------------------- * combine forward and backward filters by fixed-interval smoother as follows: * * xs=Qs*(Qf^-1*xf+Qb^-1*xb), Qs=(Qf^-1+Qb^-1)^-1) * * args : double *xf I forward solutions (n x 1) * args : double *Qf I forward solutions covariance matrix (n x n) * double *xb I backward solutions (n x 1) * double *Qb I backward solutions covariance matrix (n x n) * int n I number of solutions * double *xs O smoothed solutions (n x 1) * double *Qs O smoothed solutions covariance matrix (n x n) * return : status (0:ok,0>:error) * notes : see reference [4] 5.2 * matirix stored by column-major order (fortran convention) *-----------------------------------------------------------------------------*/ extern int smoother(const double* xf, const double* Qf, const double* xb, const double* Qb, int n, double* xs, double* Qs) { double *invQf = mat(n, n), *invQb = mat(n, n), *xx = mat(n, 1); int i, info = -1; if (!invQf || !invQb || !xx) { return info; } matcpy(invQf, Qf, n, n); matcpy(invQb, Qb, n, n); if (!matinv(invQf, n) && !matinv(invQb, n)) { for (i = 0; i < n * n; ++i) { Qs[i] = invQf[i] + invQb[i]; } if (!(info = matinv(Qs, n))) { matmul("NN", n, 1, n, 1.0, invQf, xf, 0.0, xx); matmul("NN", n, 1, n, 1.0, invQb, xb, 1.0, xx); matmul("NN", n, 1, n, 1.0, Qs, xx, 0.0, xs); } } free(invQf); free(invQb); free(xx); return info; } /* print matrix ---------------------------------------------------------------- * print matrix to stdout * args : double *A I matrix A (n x m) * int n,m I number of rows and columns of A * int p,q I total columns, columns under decimal point * (FILE *fp I output file pointer) * return : none * notes : matirix stored by column-major order (fortran convention) *-----------------------------------------------------------------------------*/ extern void matfprint(const double A[], int n, int m, int p, int q, FILE* fp) { int i, j; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { fprintf(fp, " %*.*f", p, q, A[i + j * n]); } fprintf(fp, "\n"); } } extern void matprint(const double A[], int n, int m, int p, int q) { matfprint(A, n, m, p, q, stdout); } /* string to number ------------------------------------------------------------ * convert substring in string to number * args : char *s I string ("... nnn.nnn ...") * int i,n I substring position and width * return : converted number (0.0:error) *-----------------------------------------------------------------------------*/ extern double str2num(const char* s, int i, int n) { double value; char str[256], *p = str; if (i < 0 || (int)strlen(s) < i || (int)sizeof(str) - 1 < n) { return 0.0; } for (s += i; *s && --n >= 0; s++) { *p++ = *s == 'd' || *s == 'D' ? 'E' : *s; } *p = '\0'; return sscanf(str, "%lf", &value) == 1 ? value : 0.0; } /* string to time -------------------------------------------------------------- * convert substring in string to gtime_t struct * args : char *s I string ("... yyyy mm dd hh mm ss ...") * int i,n I substring position and width * gtime_t *t O gtime_t struct * return : status (0:ok,0>:error) *-----------------------------------------------------------------------------*/ extern int str2time(const char* s, int i, int n, gtime_t* t) { double ep[6]; char str[256], *p = str; if (i < 0 || (int)strlen(s) < i || (int)sizeof(str) - 1 < i) { return -1; } for (s += i; *s && --n >= 0;) { *p++ = *s++; } *p = '\0'; if (sscanf(str, "%lf %lf %lf %lf %lf %lf", ep, ep + 1, ep + 2, ep + 3, ep + 4, ep + 5) < 6) { return -1; } if (ep[0] < 100.0) { ep[0] += ep[0] < 80.0 ? 2000.0 : 1900.0; } *t = epoch2time(ep); return 0; } /* convert calendar day/time to time ------------------------------------------- * convert calendar day/time to gtime_t struct * args : double *ep I day/time {year,month,day,hour,min,sec} * return : gtime_t struct * notes : proper in 1970-2037 or 1970-2099 (64bit time_t) *-----------------------------------------------------------------------------*/ extern gtime_t epoch2time(const double* ep) { const int doy[] = {1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}; gtime_t time = {0}; int days, sec, year = (int)ep[0], mon = (int)ep[1], day = (int)ep[2]; if (year < 1970 || 2099 < year || mon < 1 || 12 < mon) { return time; } /* leap year if year%4==0 in 1901-2099 */ days = (year - 1970) * 365 + (year - 1969) / 4 + doy[mon - 1] + day - 2 + (year % 4 == 0 && mon >= 3 ? 1 : 0); sec = (int)floor(ep[5]); time.time = (time_t)days * 86400 + (int)ep[3] * 3600 + (int)ep[4] * 60 + sec; time.sec = ep[5] - sec; return time; } /* time to calendar day/time --------------------------------------------------- * convert gtime_t struct to calendar day/time * args : gtime_t t I gtime_t struct * double *ep O day/time {year,month,day,hour,min,sec} * return : none * notes : proper in 1970-2037 or 1970-2099 (64bit time_t) *-----------------------------------------------------------------------------*/ extern void time2epoch(gtime_t t, double* ep) { const int mday[] = {/* # of days in a month */ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int days, sec, mon, day; /* leap year if year%4==0 in 1901-2099 */ days = (int)(t.time / 86400); sec = (int)(t.time - (time_t)days * 86400); for (day = days % 1461, mon = 0; mon < 48; mon++) { if (day >= mday[mon]) { day -= mday[mon]; } else { break; } } ep[0] = 1970 + days / 1461 * 4 + mon / 12; ep[1] = mon % 12 + 1; ep[2] = day + 1; ep[3] = sec / 3600; ep[4] = sec % 3600 / 60; ep[5] = sec % 60 + t.sec; } /* gps time to time ------------------------------------------------------------ * convert week and tow in gps time to gtime_t struct * args : int week I week number in gps time * double sec I time of week in gps time (s) * return : gtime_t struct *-----------------------------------------------------------------------------*/ extern gtime_t gpst2time(int week, double sec) { gtime_t t = epoch2time(gpst0); if (sec < -1E9 || 1E9 < sec) { sec = 0.0; } t.time += 86400 * 7 * week + (int)sec; t.sec = sec - (int)sec; return t; } /* time to gps time ------------------------------------------------------------ * convert gtime_t struct to week and tow in gps time * args : gtime_t t I gtime_t struct * int *week IO week number in gps time (NULL: no output) * return : time of week in gps time (s) *-----------------------------------------------------------------------------*/ extern double time2gpst(gtime_t t, int* week) { gtime_t t0 = epoch2time(gpst0); time_t sec = t.time - t0.time; int w = (int)(sec / (86400 * 7)); if (week) { *week = w; } return (double)(sec - w * 86400 * 7) + t.sec; } /* galileo system time to time ------------------------------------------------- * convert week and tow in galileo system time (gst) to gtime_t struct * args : int week I week number in gst * double sec I time of week in gst (s) * return : gtime_t struct *-----------------------------------------------------------------------------*/ extern gtime_t gst2time(int week, double sec) { gtime_t t = epoch2time(gst0); if (sec < -1E9 || 1E9 < sec) { sec = 0.0; } t.time += 86400 * 7 * week + (int)sec; t.sec = sec - (int)sec; return t; } /* time to galileo system time ------------------------------------------------- * convert gtime_t struct to week and tow in galileo system time (gst) * args : gtime_t t I gtime_t struct * int *week IO week number in gst (NULL: no output) * return : time of week in gst (s) *-----------------------------------------------------------------------------*/ extern double time2gst(gtime_t t, int* week) { gtime_t t0 = epoch2time(gst0); time_t sec = t.time - t0.time; int w = (int)(sec / (86400 * 7)); if (week) { *week = w; } return (double)(sec - w * 86400 * 7) + t.sec; } /* beidou time (bdt) to time --------------------------------------------------- * convert week and tow in beidou time (bdt) to gtime_t struct * args : int week I week number in bdt * double sec I time of week in bdt (s) * return : gtime_t struct *-----------------------------------------------------------------------------*/ extern gtime_t bdt2time(int week, double sec) { gtime_t t = epoch2time(bdt0); if (sec < -1E9 || 1E9 < sec) { sec = 0.0; } t.time += 86400 * 7 * week + (int)sec; t.sec = sec - (int)sec; return t; } /* time to beidouo time (bdt) -------------------------------------------------- * convert gtime_t struct to week and tow in beidou time (bdt) * args : gtime_t t I gtime_t struct * int *week IO week number in bdt (NULL: no output) * return : time of week in bdt (s) *-----------------------------------------------------------------------------*/ extern double time2bdt(gtime_t t, int* week) { gtime_t t0 = epoch2time(bdt0); time_t sec = t.time - t0.time; int w = (int)(sec / (86400 * 7)); if (week) { *week = w; } return (double)(sec - w * 86400 * 7) + t.sec; } /* add time -------------------------------------------------------------------- * add time to gtime_t struct * args : gtime_t t I gtime_t struct * double sec I time to add (s) * return : gtime_t struct (t+sec) *-----------------------------------------------------------------------------*/ extern gtime_t timeadd(gtime_t t, double sec) { double tt; t.sec += sec; tt = floor(t.sec); t.time += (int)tt; t.sec -= tt; return t; } /* time difference ------------------------------------------------------------- * difference between gtime_t structs * args : gtime_t t1,t2 I gtime_t structs * return : time difference (t1-t2) (s) *-----------------------------------------------------------------------------*/ extern double timediff(gtime_t t1, gtime_t t2) { return difftime(t1.time, t2.time) + t1.sec - t2.sec; } /* get current time in utc ----------------------------------------------------- * get current time in utc * args : none * return : current time in utc *-----------------------------------------------------------------------------*/ static double timeoffset_ = 0.0; /* time offset (s) */ extern gtime_t timeget(void) { double ep[6] = {0}; #ifdef WIN32 SYSTEMTIME ts; GetSystemTime(&ts); /* utc */ ep[0] = ts.wYear; ep[1] = ts.wMonth; ep[2] = ts.wDay; ep[3] = ts.wHour; ep[4] = ts.wMinute; ep[5] = ts.wSecond + ts.wMilliseconds * 1E-3; #else struct timeval tv; struct tm* tt; if (!gettimeofday(&tv, NULL) && (tt = gmtime(&tv.tv_sec))) { ep[0] = tt->tm_year + 1900; ep[1] = tt->tm_mon + 1; ep[2] = tt->tm_mday; ep[3] = tt->tm_hour; ep[4] = tt->tm_min; ep[5] = tt->tm_sec + tv.tv_usec * 1E-6; } #endif return timeadd(epoch2time(ep), timeoffset_); } /* set current time in utc ----------------------------------------------------- * set current time in utc * args : gtime_t I current time in utc * return : none * notes : just set time offset between cpu time and current time * the time offset is reflected to only timeget() * not reentrant *-----------------------------------------------------------------------------*/ extern void timeset(gtime_t t) { timeoffset_ += timediff(t, timeget()); } /* read leap seconds table ----------------------------------------------------- * read leap seconds table * args : char *file I leap seconds table file * return : status (1:ok,0:error) * notes : (1) The records in the table file cosist of the following fields: * year month day hour min sec UTC-GPST(s) * (2) The date and time indicate the start UTC time for the UTC-GPST * (3) The date and time should be descending order. *-----------------------------------------------------------------------------*/ extern int read_leaps(const char* file) { FILE* fp; char buff[256], *p; int i, n = 0, ep[6], ls; if (!(fp = fopen(file, "r"))) { return 0; } while (fgets(buff, sizeof(buff), fp) && n < MAXLEAPS) { if ((p = strchr(buff, '#'))) { *p = '\0'; } if (sscanf(buff, "%d %d %d %d %d %d %d", ep, ep + 1, ep + 2, ep + 3, ep + 4, ep + 5, &ls) < 7) { continue; } for (i = 0; i < 6; ++i) { leaps[n][i] = ep[i]; } leaps[n++][6] = ls; } for (i = 0; i < 7; ++i) { leaps[n][i] = 0.0; } fclose(fp); return 1; } /* gpstime to utc -------------------------------------------------------------- * convert gpstime to utc considering leap seconds * args : gtime_t t I time expressed in gpstime * return : time expressed in utc * notes : ignore slight time offset under 100 ns *-----------------------------------------------------------------------------*/ extern gtime_t gpst2utc(gtime_t t) { gtime_t tu; int i; for (i = 0; leaps[i][0] > 0; ++i) { tu = timeadd(t, leaps[i][6]); if (timediff(tu, epoch2time(leaps[i])) >= 0.0) { return tu; } } return t; } /* utc to gpstime -------------------------------------------------------------- * convert utc to gpstime considering leap seconds * args : gtime_t t I time expressed in utc * return : time expressed in gpstime * notes : ignore slight time offset under 100 ns *-----------------------------------------------------------------------------*/ extern gtime_t utc2gpst(gtime_t t) { int i; for (i = 0; leaps[i][0] > 0; ++i) { if (timediff(t, epoch2time(leaps[i])) >= 0.0) { return timeadd(t, -leaps[i][6]); } } return t; } /* gpstime to bdt -------------------------------------------------------------- * convert gpstime to bdt (beidou navigation satellite system time) * args : gtime_t t I time expressed in gpstime * return : time expressed in bdt * notes : ref [8] 3.3, 2006/1/1 00:00 BDT = 2006/1/1 00:00 UTC * no leap seconds in BDT * ignore slight time offset under 100 ns *-----------------------------------------------------------------------------*/ extern gtime_t gpst2bdt(gtime_t t) { return timeadd(t, -14.0); } /* bdt to gpstime -------------------------------------------------------------- * convert bdt (beidou navigation satellite system time) to gpstime * args : gtime_t t I time expressed in bdt * return : time expressed in gpstime * notes : see gpst2bdt() *-----------------------------------------------------------------------------*/ extern gtime_t bdt2gpst(gtime_t t) { return timeadd(t, 14.0); } /* time to day and sec -------------------------------------------------------*/ static double time2sec(gtime_t time, gtime_t* day) { double ep[6], sec; time2epoch(time, ep); sec = ep[3] * 3600.0 + ep[4] * 60.0 + ep[5]; ep[3] = ep[4] = ep[5] = 0.0; *day = epoch2time(ep); return sec; } /* utc to gmst ----------------------------------------------------------------- * convert utc to gmst (Greenwich mean sidereal time) * args : gtime_t t I time expressed in utc * double ut1_utc I UT1-UTC (s) * return : gmst (rad) *-----------------------------------------------------------------------------*/ extern double utc2gmst(gtime_t t, double ut1_utc) { const double ep2000[] = {2000, 1, 1, 12, 0, 0}; gtime_t tut, tut0; double ut, t1, t2, t3, gmst0, gmst; tut = timeadd(t, ut1_utc); ut = time2sec(tut, &tut0); t1 = timediff(tut0, epoch2time(ep2000)) / 86400.0 / 36525.0; t2 = t1 * t1; t3 = t2 * t1; gmst0 = 24110.54841 + 8640184.812866 * t1 + 0.093104 * t2 - 6.2E-6 * t3; gmst = gmst0 + 1.002737909350795 * ut; return fmod(gmst, 86400.0) * PI / 43200.0; /* 0 <= gmst <= 2*PI */ } /* time to string -------------------------------------------------------------- * convert gtime_t struct to string * args : gtime_t t I gtime_t struct * char *s O string ("yyyy/mm/dd hh:mm:ss.ssss") * int n I number of decimals * return : none *-----------------------------------------------------------------------------*/ extern void time2str(gtime_t t, char* s, int n) { double ep[6]; if (n < 0) { n = 0; } else if (n > 12) { n = 12; } if (1.0 - t.sec < 0.5 / pow(10.0, n)) { t.time++; t.sec = 0.0; } time2epoch(t, ep); sprintf(s, "%04.0f/%02.0f/%02.0f %02.0f:%02.0f:%0*.*f", ep[0], ep[1], ep[2], ep[3], ep[4], n <= 0 ? 2 : n + 3, n <= 0 ? 0 : n, ep[5]); } /* get time string ------------------------------------------------------------- * get time string * args : gtime_t t I gtime_t struct * int n I number of decimals * return : time string * notes : not reentrant, do not use multiple in a function *-----------------------------------------------------------------------------*/ extern char* time_str(gtime_t t, int n) { static char buff[64]; time2str(t, buff, n); return buff; } /* time to day of year --------------------------------------------------------- * convert time to day of year * args : gtime_t t I gtime_t struct * return : day of year (days) *-----------------------------------------------------------------------------*/ extern double time2doy(gtime_t t) { double ep[6]; time2epoch(t, ep); ep[1] = ep[2] = 1.0; ep[3] = ep[4] = ep[5] = 0.0; return timediff(t, epoch2time(ep)) / 86400.0 + 1.0; } /* adjust gps week number ------------------------------------------------------ * adjust gps week number using cpu time * args : int week I not-adjusted gps week number * return : adjusted gps week number *-----------------------------------------------------------------------------*/ extern int adjgpsweek(int week) { int w; (void)time2gpst(utc2gpst(timeget()), &w); if (w < 1560) { w = 1560; /* use 2009/12/1 if time is earlier than 2009/12/1 */ } return week + (w - week + 512) / 1024 * 1024; } /* get tick time --------------------------------------------------------------- * get current tick in ms * args : none * return : current tick in ms *-----------------------------------------------------------------------------*/ extern unsigned int tickget(void) { #ifdef WIN32 return (unsigned int)timeGetTime(); #else struct timespec tp = {0}; struct timeval tv = {0}; #ifdef CLOCK_MONOTONIC_RAW /* linux kernel > 2.6.28 */ if (!clock_gettime(CLOCK_MONOTONIC_RAW, &tp)) { return tp.tv_sec * 1000u + tp.tv_nsec / 1000000u; } else { gettimeofday(&tv, NULL); return tv.tv_sec * 1000u + tv.tv_usec / 1000u; } #else gettimeofday(&tv, NULL); return tv.tv_sec * 1000u + tv.tv_usec / 1000u; #endif #endif /* WIN32 */ } /* sleep ms -------------------------------------------------------------------- * sleep ms * args : int ms I miliseconds to sleep (<0:no sleep) * return : none *-----------------------------------------------------------------------------*/ extern void sleepms(int ms) { #ifdef WIN32 if (ms < 5) { Sleep(1); } else { Sleep(ms); } #else struct timespec ts; if (ms <= 0) { return; } ts.tv_sec = (time_t)(ms / 1000); ts.tv_nsec = (long)(ms % 1000 * 1000000); nanosleep(&ts, NULL); #endif } /* convert degree to deg-min-sec ----------------------------------------------- * convert degree to degree-minute-second * args : double deg I degree * double *dms O degree-minute-second {deg,min,sec} * return : none *-----------------------------------------------------------------------------*/ extern void deg2dms(double deg, double* dms) { double sign = deg < 0.0 ? -1.0 : 1.0, a = fabs(deg); dms[0] = floor(a); a = (a - dms[0]) * 60.0; dms[1] = floor(a); a = (a - dms[1]) * 60.0; dms[2] = a; dms[0] *= sign; } /* convert deg-min-sec to degree ----------------------------------------------- * convert degree-minute-second to degree * args : double *dms I degree-minute-second {deg,min,sec} * return : degree *-----------------------------------------------------------------------------*/ extern double dms2deg(const double* dms) { double sign = dms[0] < 0.0 ? -1.0 : 1.0; return sign * (fabs(dms[0]) + dms[1] / 60.0 + dms[2] / 3600.0); } /* transform ecef to geodetic postion ------------------------------------------ * transform ecef position to geodetic position * args : double *r I ecef position {x,y,z} (m) * double *pos O geodetic position {lat,lon,h} (rad,m) * return : none * notes : WGS84, ellipsoidal height *-----------------------------------------------------------------------------*/ extern void ecef2pos(const double* r, double* pos) { double e2 = FE_WGS84 * (2.0 - FE_WGS84), r2 = dot(r, r, 2), z, zk, v = RE_WGS84, sinp; for (z = r[2], zk = 0.0; fabs(z - zk) >= 1E-4;) { zk = z; sinp = z / sqrt(r2 + z * z); v = RE_WGS84 / sqrt(1.0 - e2 * sinp * sinp); z = r[2] + v * e2 * sinp; } pos[0] = r2 > 1E-12 ? atan(z / sqrt(r2)) : (r[2] > 0.0 ? PI / 2.0 : -PI / 2.0); pos[1] = r2 > 1E-12 ? atan2(r[1], r[0]) : 0.0; pos[2] = sqrt(r2 + z * z) - v; } /* transform geodetic to ecef position ----------------------------------------- * transform geodetic position to ecef position * args : double *pos I geodetic position {lat,lon,h} (rad,m) * double *r O ecef position {x,y,z} (m) * return : none * notes : WGS84, ellipsoidal height *-----------------------------------------------------------------------------*/ extern void pos2ecef(const double* pos, double* r) { double sinp = sin(pos[0]), cosp = cos(pos[0]), sinl = sin(pos[1]), cosl = cos(pos[1]); double e2 = FE_WGS84 * (2.0 - FE_WGS84), v = RE_WGS84 / sqrt(1.0 - e2 * sinp * sinp); r[0] = (v + pos[2]) * cosp * cosl; r[1] = (v + pos[2]) * cosp * sinl; r[2] = (v * (1.0 - e2) + pos[2]) * sinp; } /* ecef to local coordinate transfromation matrix ------------------------------ * compute ecef to local coordinate transfromation matrix * args : double *pos I geodetic position {lat,lon} (rad) * double *E O ecef to local coord transformation matrix (3x3) * return : none * notes : matirix stored by column-major order (fortran convention) *-----------------------------------------------------------------------------*/ extern void xyz2enu(const double* pos, double* E) { double sinp = sin(pos[0]), cosp = cos(pos[0]), sinl = sin(pos[1]), cosl = cos(pos[1]); E[0] = -sinl; E[3] = cosl; E[6] = 0.0; E[1] = -sinp * cosl; E[4] = -sinp * sinl; E[7] = cosp; E[2] = cosp * cosl; E[5] = cosp * sinl; E[8] = sinp; } /* transform ecef vector to local tangental coordinate ------------------------- * transform ecef vector to local tangental coordinate * args : double *pos I geodetic position {lat,lon} (rad) * double *r I vector in ecef coordinate {x,y,z} * double *e O vector in local tangental coordinate {e,n,u} * return : none *-----------------------------------------------------------------------------*/ extern void ecef2enu(const double* pos, const double* r, double* e) { double E[9]; xyz2enu(pos, E); matmul("NN", 3, 1, 3, 1.0, E, r, 0.0, e); } /* transform local vector to ecef coordinate ----------------------------------- * transform local tangental coordinate vector to ecef * args : double *pos I geodetic position {lat,lon} (rad) * double *e I vector in local tangental coordinate {e,n,u} * double *r O vector in ecef coordinate {x,y,z} * return : none *-----------------------------------------------------------------------------*/ extern void enu2ecef(const double* pos, const double* e, double* r) { double E[9]; xyz2enu(pos, E); matmul("TN", 3, 1, 3, 1.0, E, e, 0.0, r); } /* transform covariance to local tangental coordinate -------------------------- * transform ecef covariance to local tangental coordinate * args : double *pos I geodetic position {lat,lon} (rad) * double *P I covariance in ecef coordinate * double *Q O covariance in local tangental coordinate * return : none *-----------------------------------------------------------------------------*/ extern void covenu(const double* pos, const double* P, double* Q) { double E[9], EP[9]; xyz2enu(pos, E); matmul("NN", 3, 3, 3, 1.0, E, P, 0.0, EP); matmul("NT", 3, 3, 3, 1.0, EP, E, 0.0, Q); } /* transform local enu coordinate covariance to xyz-ecef ----------------------- * transform local enu covariance to xyz-ecef coordinate * args : double *pos I geodetic position {lat,lon} (rad) * double *Q I covariance in local enu coordinate * double *P O covariance in xyz-ecef coordinate * return : none *-----------------------------------------------------------------------------*/ extern void covecef(const double* pos, const double* Q, double* P) { double E[9], EQ[9]; xyz2enu(pos, E); matmul("TN", 3, 3, 3, 1.0, E, Q, 0.0, EQ); matmul("NN", 3, 3, 3, 1.0, EQ, E, 0.0, P); } /* coordinate rotation matrix ------------------------------------------------*/ #define Rx(t, X) \ do { \ (X)[0] = 1.0; \ (X)[1] = (X)[2] = (X)[3] = (X)[6] = 0.0; \ (X)[4] = (X)[8] = cos(t); \ (X)[7] = sin(t); \ (X)[5] = -(X)[7]; \ } while (0) #define Ry(t, X) \ do { \ (X)[4] = 1.0; \ (X)[1] = (X)[3] = (X)[5] = (X)[7] = 0.0; \ (X)[0] = (X)[8] = cos(t); \ (X)[2] = sin(t); \ (X)[6] = -(X)[2]; \ } while (0) #define Rz(t, X) \ do { \ (X)[8] = 1.0; \ (X)[2] = (X)[5] = (X)[6] = (X)[7] = 0.0; \ (X)[0] = (X)[4] = cos(t); \ (X)[3] = sin(t); \ (X)[1] = -(X)[3]; \ } while (0) /* astronomical arguments: f={l,l',F,D,OMG} (rad) ----------------------------*/ static void ast_args(double t, double* f) { static const double fc[][5] = { /* coefficients for iau 1980 nutation */ {134.96340251, 1717915923.2178, 31.8792, 0.051635, -0.00024470}, {357.52910918, 129596581.0481, -0.5532, 0.000136, -0.00001149}, {93.27209062, 1739527262.8478, -12.7512, -0.001037, 0.00000417}, {297.85019547, 1602961601.2090, -6.3706, 0.006593, -0.00003169}, {125.04455501, -6962890.2665, 7.4722, 0.007702, -0.00005939}}; double tt[4]; int i, j; for (tt[0] = t, i = 1; i < 4; ++i) { tt[i] = tt[i - 1] * t; } for (i = 0; i < 5; ++i) { f[i] = fc[i][0] * 3600.0; for (j = 0; j < 4; ++j) { f[i] += fc[i][j + 1] * tt[j]; } f[i] = fmod(f[i] * AS2R, 2.0 * PI); } } /* iau 1980 nutation ---------------------------------------------------------*/ static void nut_iau1980(double t, const double* f, double* dpsi, double* deps) { static const double nut[106][10] = { {0, 0, 0, 0, 1, -6798.4, -171996, -174.2, 92025, 8.9}, {0, 0, 2, -2, 2, 182.6, -13187, -1.6, 5736, -3.1}, {0, 0, 2, 0, 2, 13.7, -2274, -0.2, 977, -0.5}, {0, 0, 0, 0, 2, -3399.2, 2062, 0.2, -895, 0.5}, {0, -1, 0, 0, 0, -365.3, -1426, 3.4, 54, -0.1}, {1, 0, 0, 0, 0, 27.6, 712, 0.1, -7, 0.0}, {0, 1, 2, -2, 2, 121.7, -517, 1.2, 224, -0.6}, {0, 0, 2, 0, 1, 13.6, -386, -0.4, 200, 0.0}, {1, 0, 2, 0, 2, 9.1, -301, 0.0, 129, -0.1}, {0, -1, 2, -2, 2, 365.2, 217, -0.5, -95, 0.3}, {-1, 0, 0, 2, 0, 31.8, 158, 0.0, -1, 0.0}, {0, 0, 2, -2, 1, 177.8, 129, 0.1, -70, 0.0}, {-1, 0, 2, 0, 2, 27.1, 123, 0.0, -53, 0.0}, {1, 0, 0, 0, 1, 27.7, 63, 0.1, -33, 0.0}, {0, 0, 0, 2, 0, 14.8, 63, 0.0, -2, 0.0}, {-1, 0, 2, 2, 2, 9.6, -59, 0.0, 26, 0.0}, {-1, 0, 0, 0, 1, -27.4, -58, -0.1, 32, 0.0}, {1, 0, 2, 0, 1, 9.1, -51, 0.0, 27, 0.0}, {-2, 0, 0, 2, 0, -205.9, -48, 0.0, 1, 0.0}, {-2, 0, 2, 0, 1, 1305.5, 46, 0.0, -24, 0.0}, {0, 0, 2, 2, 2, 7.1, -38, 0.0, 16, 0.0}, {2, 0, 2, 0, 2, 6.9, -31, 0.0, 13, 0.0}, {2, 0, 0, 0, 0, 13.8, 29, 0.0, -1, 0.0}, {1, 0, 2, -2, 2, 23.9, 29, 0.0, -12, 0.0}, {0, 0, 2, 0, 0, 13.6, 26, 0.0, -1, 0.0}, {0, 0, 2, -2, 0, 173.3, -22, 0.0, 0, 0.0}, {-1, 0, 2, 0, 1, 27.0, 21, 0.0, -10, 0.0}, {0, 2, 0, 0, 0, 182.6, 17, -0.1, 0, 0.0}, {0, 2, 2, -2, 2, 91.3, -16, 0.1, 7, 0.0}, {-1, 0, 0, 2, 1, 32.0, 16, 0.0, -8, 0.0}, {0, 1, 0, 0, 1, 386.0, -15, 0.0, 9, 0.0}, {1, 0, 0, -2, 1, -31.7, -13, 0.0, 7, 0.0}, {0, -1, 0, 0, 1, -346.6, -12, 0.0, 6, 0.0}, {2, 0, -2, 0, 0, -1095.2, 11, 0.0, 0, 0.0}, {-1, 0, 2, 2, 1, 9.5, -10, 0.0, 5, 0.0}, {1, 0, 2, 2, 2, 5.6, -8, 0.0, 3, 0.0}, {0, -1, 2, 0, 2, 14.2, -7, 0.0, 3, 0.0}, {0, 0, 2, 2, 1, 7.1, -7, 0.0, 3, 0.0}, {1, 1, 0, -2, 0, -34.8, -7, 0.0, 0, 0.0}, {0, 1, 2, 0, 2, 13.2, 7, 0.0, -3, 0.0}, {-2, 0, 0, 2, 1, -199.8, -6, 0.0, 3, 0.0}, {0, 0, 0, 2, 1, 14.8, -6, 0.0, 3, 0.0}, {2, 0, 2, -2, 2, 12.8, 6, 0.0, -3, 0.0}, {1, 0, 0, 2, 0, 9.6, 6, 0.0, 0, 0.0}, {1, 0, 2, -2, 1, 23.9, 6, 0.0, -3, 0.0}, {0, 0, 0, -2, 1, -14.7, -5, 0.0, 3, 0.0}, {0, -1, 2, -2, 1, 346.6, -5, 0.0, 3, 0.0}, {2, 0, 2, 0, 1, 6.9, -5, 0.0, 3, 0.0}, {1, -1, 0, 0, 0, 29.8, 5, 0.0, 0, 0.0}, {1, 0, 0, -1, 0, 411.8, -4, 0.0, 0, 0.0}, {0, 0, 0, 1, 0, 29.5, -4, 0.0, 0, 0.0}, {0, 1, 0, -2, 0, -15.4, -4, 0.0, 0, 0.0}, {1, 0, -2, 0, 0, -26.9, 4, 0.0, 0, 0.0}, {2, 0, 0, -2, 1, 212.3, 4, 0.0, -2, 0.0}, {0, 1, 2, -2, 1, 119.6, 4, 0.0, -2, 0.0}, {1, 1, 0, 0, 0, 25.6, -3, 0.0, 0, 0.0}, {1, -1, 0, -1, 0, -3232.9, -3, 0.0, 0, 0.0}, {-1, -1, 2, 2, 2, 9.8, -3, 0.0, 1, 0.0}, {0, -1, 2, 2, 2, 7.2, -3, 0.0, 1, 0.0}, {1, -1, 2, 0, 2, 9.4, -3, 0.0, 1, 0.0}, {3, 0, 2, 0, 2, 5.5, -3, 0.0, 1, 0.0}, {-2, 0, 2, 0, 2, 1615.7, -3, 0.0, 1, 0.0}, {1, 0, 2, 0, 0, 9.1, 3, 0.0, 0, 0.0}, {-1, 0, 2, 4, 2, 5.8, -2, 0.0, 1, 0.0}, {1, 0, 0, 0, 2, 27.8, -2, 0.0, 1, 0.0}, {-1, 0, 2, -2, 1, -32.6, -2, 0.0, 1, 0.0}, {0, -2, 2, -2, 1, 6786.3, -2, 0.0, 1, 0.0}, {-2, 0, 0, 0, 1, -13.7, -2, 0.0, 1, 0.0}, {2, 0, 0, 0, 1, 13.8, 2, 0.0, -1, 0.0}, {3, 0, 0, 0, 0, 9.2, 2, 0.0, 0, 0.0}, {1, 1, 2, 0, 2, 8.9, 2, 0.0, -1, 0.0}, {0, 0, 2, 1, 2, 9.3, 2, 0.0, -1, 0.0}, {1, 0, 0, 2, 1, 9.6, -1, 0.0, 0, 0.0}, {1, 0, 2, 2, 1, 5.6, -1, 0.0, 1, 0.0}, {1, 1, 0, -2, 1, -34.7, -1, 0.0, 0, 0.0}, {0, 1, 0, 2, 0, 14.2, -1, 0.0, 0, 0.0}, {0, 1, 2, -2, 0, 117.5, -1, 0.0, 0, 0.0}, {0, 1, -2, 2, 0, -329.8, -1, 0.0, 0, 0.0}, {1, 0, -2, 2, 0, 23.8, -1, 0.0, 0, 0.0}, {1, 0, -2, -2, 0, -9.5, -1, 0.0, 0, 0.0}, {1, 0, 2, -2, 0, 32.8, -1, 0.0, 0, 0.0}, {1, 0, 0, -4, 0, -10.1, -1, 0.0, 0, 0.0}, {2, 0, 0, -4, 0, -15.9, -1, 0.0, 0, 0.0}, {0, 0, 2, 4, 2, 4.8, -1, 0.0, 0, 0.0}, {0, 0, 2, -1, 2, 25.4, -1, 0.0, 0, 0.0}, {-2, 0, 2, 4, 2, 7.3, -1, 0.0, 1, 0.0}, {2, 0, 2, 2, 2, 4.7, -1, 0.0, 0, 0.0}, {0, -1, 2, 0, 1, 14.2, -1, 0.0, 0, 0.0}, {0, 0, -2, 0, 1, -13.6, -1, 0.0, 0, 0.0}, {0, 0, 4, -2, 2, 12.7, 1, 0.0, 0, 0.0}, {0, 1, 0, 0, 2, 409.2, 1, 0.0, 0, 0.0}, {1, 1, 2, -2, 2, 22.5, 1, 0.0, -1, 0.0}, {3, 0, 2, -2, 2, 8.7, 1, 0.0, 0, 0.0}, {-2, 0, 2, 2, 2, 14.6, 1, 0.0, -1, 0.0}, {-1, 0, 0, 0, 2, -27.3, 1, 0.0, -1, 0.0}, {0, 0, -2, 2, 1, -169.0, 1, 0.0, 0, 0.0}, {0, 1, 2, 0, 1, 13.1, 1, 0.0, 0, 0.0}, {-1, 0, 4, 0, 2, 9.1, 1, 0.0, 0, 0.0}, {2, 1, 0, -2, 0, 131.7, 1, 0.0, 0, 0.0}, {2, 0, 0, 2, 0, 7.1, 1, 0.0, 0, 0.0}, {2, 0, 2, -2, 1, 12.8, 1, 0.0, -1, 0.0}, {2, 0, -2, 0, 1, -943.2, 1, 0.0, 0, 0.0}, {1, -1, 0, -2, 0, -29.3, 1, 0.0, 0, 0.0}, {-1, 0, 0, 1, 1, -388.3, 1, 0.0, 0, 0.0}, {-1, -1, 0, 2, 1, 35.0, 1, 0.0, 0, 0.0}, {0, 1, 0, 1, 0, 27.3, 1, 0.0, 0, 0.0}}; double ang; int i, j; *dpsi = *deps = 0.0; for (i = 0; i < 106; ++i) { ang = 0.0; for (j = 0; j < 5; ++j) { ang += nut[i][j] * f[j]; } *dpsi += (nut[i][6] + nut[i][7] * t) * sin(ang); *deps += (nut[i][8] + nut[i][9] * t) * cos(ang); } *dpsi *= 1E-4 * AS2R; /* 0.1 mas -> rad */ *deps *= 1E-4 * AS2R; } /* eci to ecef transformation matrix ------------------------------------------- * compute eci to ecef transformation matrix * args : gtime_t tutc I time in utc * double *erpv I erp values {xp,yp,ut1_utc,lod} (rad,rad,s,s/d) * double *U O eci to ecef transformation matrix (3 x 3) * double *gmst IO greenwich mean sidereal time (rad) * (NULL: no output) * return : none * note : see ref [3] chap 5 * not thread-safe *-----------------------------------------------------------------------------*/ extern void eci2ecef(gtime_t tutc, const double* erpv, double* U, double* gmst) { const double ep2000[] = {2000, 1, 1, 12, 0, 0}; static gtime_t tutc_; static double U_[9], gmst_; gtime_t tgps; double eps, ze, th, z, t, t2, t3, dpsi, deps, gast, f[5]; double R1[9], R2[9], R3[9], R[9], W[9], N[9], P[9], NP[9]; int i; trace(3, "eci2ecef: tutc=%s\n", time_str(tutc, 3)); if (fabs(timediff(tutc, tutc_)) < 0.01) { /* read cache */ for (i = 0; i < 9; ++i) { U[i] = U_[i]; } if (gmst) { *gmst = gmst_; } return; } tutc_ = tutc; /* terrestrial time */ tgps = utc2gpst(tutc_); t = (timediff(tgps, epoch2time(ep2000)) + 19.0 + 32.184) / 86400.0 / 36525.0; t2 = t * t; t3 = t2 * t; /* astronomical arguments */ ast_args(t, f); /* iau 1976 precession */ ze = (2306.2181 * t + 0.30188 * t2 + 0.017998 * t3) * AS2R; th = (2004.3109 * t - 0.42665 * t2 - 0.041833 * t3) * AS2R; z = (2306.2181 * t + 1.09468 * t2 + 0.018203 * t3) * AS2R; eps = (84381.448 - 46.8150 * t - 0.00059 * t2 + 0.001813 * t3) * AS2R; Rz(-z, R1); Ry(th, R2); Rz(-ze, R3); matmul("NN", 3, 3, 3, 1.0, R1, R2, 0.0, R); matmul("NN", 3, 3, 3, 1.0, R, R3, 0.0, P); /* P=Rz(-z)*Ry(th)*Rz(-ze) */ /* iau 1980 nutation */ nut_iau1980(t, f, &dpsi, &deps); Rx(-eps - deps, R1); Rz(-dpsi, R2); Rx(eps, R3); matmul("NN", 3, 3, 3, 1.0, R1, R2, 0.0, R); matmul("NN", 3, 3, 3, 1.0, R, R3, 0.0, N); /* N=Rx(-eps)*Rz(-dspi)*Rx(eps) */ /* greenwich aparent sidereal time (rad) */ gmst_ = utc2gmst(tutc_, erpv[2]); gast = gmst_ + dpsi * cos(eps); gast += (0.00264 * sin(f[4]) + 0.000063 * sin(2.0 * f[4])) * AS2R; /* eci to ecef transformation matrix */ Ry(-erpv[0], R1); Rx(-erpv[1], R2); Rz(gast, R3); matmul("NN", 3, 3, 3, 1.0, R1, R2, 0.0, W); matmul("NN", 3, 3, 3, 1.0, W, R3, 0.0, R); /* W=Ry(-xp)*Rx(-yp) */ matmul("NN", 3, 3, 3, 1.0, N, P, 0.0, NP); matmul("NN", 3, 3, 3, 1.0, R, NP, 0.0, U_); /* U=W*Rz(gast)*N*P */ for (i = 0; i < 9; ++i) { U[i] = U_[i]; } if (gmst) { *gmst = gmst_; } trace(5, "gmst=%.12f gast=%.12f\n", gmst_, gast); trace(5, "P=\n"); tracemat(5, P, 3, 3, 15, 12); trace(5, "N=\n"); tracemat(5, N, 3, 3, 15, 12); trace(5, "W=\n"); tracemat(5, W, 3, 3, 15, 12); trace(5, "U=\n"); tracemat(5, U, 3, 3, 15, 12); } /* decode antenna parameter field --------------------------------------------*/ static int decodef(char* p, int n, double* v) { int i; for (i = 0; i < n; ++i) { v[i] = 0.0; } for (i = 0, p = strtok(p, " "); p && i < n; p = strtok(NULL, " ")) { v[i++] = atof(p) * 1E-3; } return i; } /* add antenna parameter -----------------------------------------------------*/ static void addpcv(const pcv_t* pcv, pcvs_t* pcvs) { pcv_t* pcvs_pcv; if (pcvs->nmax <= pcvs->n) { pcvs->nmax += 256; if (!(pcvs_pcv = (pcv_t*)realloc(pcvs->pcv, sizeof(pcv_t) * pcvs->nmax))) { trace(1, "addpcv: memory allocation error\n"); free(pcvs->pcv); pcvs->pcv = NULL; pcvs->n = pcvs->nmax = 0; return; } pcvs->pcv = pcvs_pcv; } pcvs->pcv[pcvs->n++] = *pcv; } /* read ngs antenna parameter file -------------------------------------------*/ static int readngspcv(const char* file, pcvs_t* pcvs) { FILE* fp; static const pcv_t pcv0 = {0}; pcv_t pcv = {0}; double neu[3]; int n = 0; char buff[256]; if (!(fp = fopen(file, "r"))) { trace(2, "ngs pcv file open error: %s\n", file); return 0; } while (fgets(buff, sizeof(buff), fp)) { if (strlen(buff) >= 62 && buff[61] == '|') { continue; } if (buff[0] != ' ') { n = 0; /* start line */ } if (++n == 1) { pcv = pcv0; strncpy(pcv.type, buff, 61); pcv.type[61] = '\0'; } else if (n == 2) { if (decodef(buff, 3, neu) < 3) { continue; } pcv.off[0][0] = neu[1]; pcv.off[0][1] = neu[0]; pcv.off[0][2] = neu[2]; } else if (n == 3) { decodef(buff, 10, pcv.var[0]); } else if (n == 4) { decodef(buff, 9, pcv.var[0] + 10); } else if (n == 5) { if (decodef(buff, 3, neu) < 3) { continue; ; } pcv.off[1][0] = neu[1]; pcv.off[1][1] = neu[0]; pcv.off[1][2] = neu[2]; } else if (n == 6) { decodef(buff, 10, pcv.var[1]); } else if (n == 7) { decodef(buff, 9, pcv.var[1] + 10); addpcv(&pcv, pcvs); } } fclose(fp); return 1; } /* read antex file ----------------------------------------------------------*/ static int readantex(const char* file, pcvs_t* pcvs) { FILE* fp; static const pcv_t pcv0 = {0}; pcv_t pcv = {0}; double neu[3]; int i, f, freq = 0, state = 0, freqs[] = {1, 2, 5, 6, 7, 8, 0}; char buff[256]; trace(3, "readantex: file=%s\n", file); if (!(fp = fopen(file, "r"))) { trace(2, "antex pcv file open error: %s\n", file); return 0; } while (fgets(buff, sizeof(buff), fp)) { if (strlen(buff) < 60 || strstr(buff + 60, "COMMENT")) { continue; } if (strstr(buff + 60, "START OF ANTENNA")) { pcv = pcv0; state = 1; } if (strstr(buff + 60, "END OF ANTENNA")) { addpcv(&pcv, pcvs); state = 0; } if (!state) { continue; } if (strstr(buff + 60, "TYPE / SERIAL NO")) { strncpy(pcv.type, buff, 20); pcv.type[20] = '\0'; strncpy(pcv.code, buff + 20, 20); pcv.code[20] = '\0'; if (!strncmp(pcv.code + 3, " ", 8)) { pcv.sat = satid2no(pcv.code); } } else if (strstr(buff + 60, "VALID FROM")) { if (!str2time(buff, 0, 43, &pcv.ts)) { continue; } } else if (strstr(buff + 60, "VALID UNTIL")) { if (!str2time(buff, 0, 43, &pcv.te)) { continue; } } else if (strstr(buff + 60, "START OF FREQUENCY")) { if (sscanf(buff + 4, "%d", &f) < 1) { continue; } for (i = 0; i < NFREQ; ++i) { if (freqs[i] == f) { break; } } if (i < NFREQ) { freq = i + 1; } } else if (strstr(buff + 60, "END OF FREQUENCY")) { freq = 0; } else if (strstr(buff + 60, "NORTH / EAST / UP")) { if (freq < 1 || NFREQ < freq) { continue; } if (decodef(buff, 3, neu) < 3) { continue; } pcv.off[freq - 1][0] = neu[pcv.sat ? 0 : 1]; /* x or e */ pcv.off[freq - 1][1] = neu[pcv.sat ? 1 : 0]; /* y or n */ pcv.off[freq - 1][2] = neu[2]; /* z or u */ } else if (strstr(buff, "NOAZI")) { if (freq < 1 || NFREQ < freq) { continue; } if ((i = decodef(buff + 8, 19, pcv.var[freq - 1])) <= 0) { continue; } for (; i < 19; ++i) { pcv.var[freq - 1][i] = pcv.var[freq - 1][i - 1]; } } } fclose(fp); return 1; } /* read antenna parameters *------------------------------------------------------ * read antenna parameters * args : char *file I antenna parameter file (antex) * pcvs_t *pcvs IO antenna parameters * return : status (1:ok,0:file open error) * notes : file with the externsion .atx or .ATX is recognized as antex * file except for antex is recognized ngs antenna parameters * see reference [3] * only support non-azimuth-depedent parameters *-----------------------------------------------------------------------------*/ extern int readpcv(const char* file, pcvs_t* pcvs) { pcv_t* pcv; char* ext; int i, stat; trace(3, "readpcv: file=%s\n", file); if (!(ext = strrchr(file, '.'))) { ext = ""; } if (!strcmp(ext, ".atx") || !strcmp(ext, ".ATX")) { stat = readantex(file, pcvs); } else { stat = readngspcv(file, pcvs); } for (i = 0; i < pcvs->n; ++i) { pcv = pcvs->pcv + i; trace( 4, "sat=%2d type=%20s code=%s off=%8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\n", pcv->sat, pcv->type, pcv->code, pcv->off[0][0], pcv->off[0][1], pcv->off[0][2], pcv->off[1][0], pcv->off[1][1], pcv->off[1][2]); } return stat; } /* search antenna parameter ---------------------------------------------------- * read satellite antenna phase center position * args : int sat I satellite number (0: receiver antenna) * char *type I antenna type for receiver antenna * gtime_t time I time to search parameters * pcvs_t *pcvs IO antenna parameters * return : antenna parameter (NULL: no antenna) *-----------------------------------------------------------------------------*/ extern pcv_t* searchpcv(int sat, const char* type, gtime_t time, const pcvs_t* pcvs) { pcv_t* pcv; char buff[MAXANT], *types[2], *p; int i, j, n = 0; trace(3, "searchpcv: sat=%2d type=%s\n", sat, type); if (sat) { /* search satellite antenna */ for (i = 0; i < pcvs->n; ++i) { pcv = pcvs->pcv + i; if (pcv->sat != sat) { continue; } if (pcv->ts.time != 0 && timediff(pcv->ts, time) > 0.0) { continue; } if (pcv->te.time != 0 && timediff(pcv->te, time) < 0.0) { continue; } return pcv; } } else { strcpy(buff, type); for (p = strtok(buff, " "); p && n < 2; p = strtok(NULL, " ")) { types[n++] = p; } if (n <= 0) { return NULL; } /* search receiver antenna with radome at first */ for (i = 0; i < pcvs->n; ++i) { pcv = pcvs->pcv + i; for (j = 0; j < n; ++j) { if (!strstr(pcv->type, types[j])) { break; } } if (j >= n) { return pcv; } } /* search receiver antenna without radome */ for (i = 0; i < pcvs->n; ++i) { pcv = pcvs->pcv + i; if (strstr(pcv->type, types[0]) != pcv->type) { continue; } trace(2, "pcv without radome is used type=%s\n", type); return pcv; } } return NULL; } /* read station positions ------------------------------------------------------ * read positions from station position file * args : char *file I station position file containing * lat(deg) lon(deg) height(m) name in a line * char *rcvs I station name * double *pos O station position {lat,lon,h} (rad/m) * (all 0 if search error) * return : none *-----------------------------------------------------------------------------*/ extern void readpos(const char* file, const char* rcv, double* pos) { static double poss[2048][3]; static char stas[2048][16]; FILE* fp; int i, j, len, np = 0; char buff[256], str[256]; trace(3, "readpos: file=%s\n", file); if (!(fp = fopen(file, "r"))) { fprintf(stderr, "reference position file open error : %s\n", file); return; } while (np < 2048 && fgets(buff, sizeof(buff), fp)) { if (buff[0] == '%' || buff[0] == '#') { continue; } if (sscanf(buff, "%lf %lf %lf %255s", &poss[np][0], &poss[np][1], &poss[np][2], str) < 4) { continue; } strncpy(stas[np], str, 15); stas[np++][15] = '\0'; } fclose(fp); len = (int)strlen(rcv); for (i = 0; i < np; ++i) { if (strncmp(stas[i], rcv, len)) { continue; } for (j = 0; j < 3; ++j) { pos[j] = poss[i][j]; } pos[0] *= D2R; pos[1] *= D2R; return; } pos[0] = pos[1] = pos[2] = 0.0; } /* read blq record -----------------------------------------------------------*/ static int readblqrecord(FILE* fp, double* odisp) { double v[11]; char buff[256]; int i, n = 0; while (fgets(buff, sizeof(buff), fp)) { if (!strncmp(buff, "$$", 2)) { continue; } if (sscanf(buff, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", v, v + 1, v + 2, v + 3, v + 4, v + 5, v + 6, v + 7, v + 8, v + 9, v + 10) < 11) { continue; } for (i = 0; i < 11; ++i) { odisp[n + i * 6] = v[i]; } if (++n == 6) { return 1; } } return 0; } /* read blq ocean tide loading parameters -------------------------------------- * read blq ocean tide loading parameters * args : char *file I BLQ ocean tide loading parameter file * char *sta I station name * double *odisp O ocean tide loading parameters * return : status (1:ok,0:file open error) *-----------------------------------------------------------------------------*/ extern int readblq(const char* file, const char* sta, double* odisp) { FILE* fp; char buff[256], staname[32] = "", name[32], *p; /* station name to upper case */ sscanf(sta, "%16s", staname); for (p = staname; (*p = (char)toupper((int)(*p))); p++) ; if (!(fp = fopen(file, "r"))) { trace(2, "blq file open error: file=%s\n", file); return 0; } while (fgets(buff, sizeof(buff), fp)) { if (!strncmp(buff, "$$", 2) || strlen(buff) < 2) { continue; } if (sscanf(buff + 2, "%16s", name) < 1) { continue; } for (p = name; (*p = (char)toupper((int)(*p))); p++) ; if (strcmp(name, staname)) { continue; } /* read blq record */ if (readblqrecord(fp, odisp)) { fclose(fp); return 1; } } fclose(fp); trace(2, "no otl parameters: sta=%s file=%s\n", sta, file); return 0; } /* read earth rotation parameters ---------------------------------------------- * read earth rotation parameters * args : char *file I IGS ERP file (IGS ERP ver.2) * erp_t *erp O earth rotation parameters * return : status (1:ok,0:file open error) *-----------------------------------------------------------------------------*/ extern int readerp(const char* file, erp_t* erp) { FILE* fp; erpd_t* erp_data; double v[14] = {0}; char buff[256]; trace(3, "readerp: file=%s\n", file); if (!(fp = fopen(file, "r"))) { trace(2, "erp file open error: file=%s\n", file); return 0; } while (fgets(buff, sizeof(buff), fp)) { if (sscanf(buff, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", v, v + 1, v + 2, v + 3, v + 4, v + 5, v + 6, v + 7, v + 8, v + 9, v + 10, v + 11, v + 12, v + 13) < 5) { continue; } if (erp->n >= erp->nmax) { erp->nmax = erp->nmax <= 0 ? 128 : erp->nmax * 2; erp_data = (erpd_t*)realloc(erp->data, sizeof(erpd_t) * erp->nmax); if (!erp_data) { free(erp->data); erp->data = NULL; erp->n = erp->nmax = 0; fclose(fp); return 0; } erp->data = erp_data; } erp->data[erp->n].mjd = v[0]; erp->data[erp->n].xp = v[1] * 1E-6 * AS2R; erp->data[erp->n].yp = v[2] * 1E-6 * AS2R; erp->data[erp->n].ut1_utc = v[3] * 1E-7; erp->data[erp->n].lod = v[4] * 1E-7; erp->data[erp->n].xpr = v[12] * 1E-6 * AS2R; erp->data[erp->n++].ypr = v[13] * 1E-6 * AS2R; } fclose(fp); return 1; } /* get earth rotation parameter values ----------------------------------------- * get earth rotation parameter values * args : erp_t *erp I earth rotation parameters * gtime_t time I time (gpst) * double *erpv O erp values {xp,yp,ut1_utc,lod} (rad,rad,s,s/d) * return : status (1:ok,0:error) *-----------------------------------------------------------------------------*/ extern int geterp(const erp_t* erp, gtime_t time, double* erpv) { const double ep[] = {2000, 1, 1, 12, 0, 0}; double mjd, day, a; int i = 0, j, k; trace(4, "geterp:\n"); if (erp->n <= 0) { return 0; } mjd = 51544.5 + (timediff(gpst2utc(time), epoch2time(ep))) / 86400.0; if (mjd <= erp->data[0].mjd) { day = mjd - erp->data[0].mjd; erpv[0] = erp->data[0].xp + erp->data[0].xpr * day; erpv[1] = erp->data[0].yp + erp->data[0].ypr * day; erpv[2] = erp->data[0].ut1_utc - erp->data[0].lod * day; erpv[3] = erp->data[0].lod; return 1; } if (mjd >= erp->data[erp->n - 1].mjd) { day = mjd - erp->data[erp->n - 1].mjd; erpv[0] = erp->data[erp->n - 1].xp + erp->data[erp->n - 1].xpr * day; erpv[1] = erp->data[erp->n - 1].yp + erp->data[erp->n - 1].ypr * day; erpv[2] = erp->data[erp->n - 1].ut1_utc - erp->data[erp->n - 1].lod * day; erpv[3] = erp->data[erp->n - 1].lod; return 1; } for (j = 0, k = erp->n - 1; j < k - 1;) { i = (j + k) / 2; if (mjd < erp->data[i].mjd) { k = i; } else { j = i; } } if (erp->data[j].mjd == erp->data[j + 1].mjd) { a = 0.5; } else { a = (mjd - erp->data[j].mjd) / (erp->data[j + 1].mjd - erp->data[j].mjd); } erpv[0] = (1.0 - a) * erp->data[j].xp + a * erp->data[j + 1].xp; erpv[1] = (1.0 - a) * erp->data[j].yp + a * erp->data[j + 1].yp; erpv[2] = (1.0 - a) * erp->data[j].ut1_utc + a * erp->data[j + 1].ut1_utc; erpv[3] = (1.0 - a) * erp->data[j].lod + a * erp->data[j + 1].lod; return 1; } /* compare ephemeris ---------------------------------------------------------*/ static int cmpeph(const void* p1, const void* p2) { eph_t *q1 = (eph_t *)p1, *q2 = (eph_t *)p2; return q1->ttr.time != q2->ttr.time ? (int)(q1->ttr.time - q2->ttr.time) : (q1->toe.time != q2->toe.time ? (int)(q1->toe.time - q2->toe.time) : q1->sat - q2->sat); } /* sort and unique ephemeris -------------------------------------------------*/ static void uniqeph(nav_t* nav) { eph_t* nav_eph; int i, j; trace(3, "uniqeph: n=%d\n", nav->n); if (nav->n <= 0) { return; } qsort(nav->eph, nav->n, sizeof(eph_t), cmpeph); for (i = 1, j = 0; i < nav->n; ++i) { if (nav->eph[i].sat != nav->eph[j].sat || nav->eph[i].iode != nav->eph[j].iode) { nav->eph[++j] = nav->eph[i]; } } nav->n = j + 1; if (!(nav_eph = (eph_t*)realloc(nav->eph, sizeof(eph_t) * nav->n))) { trace(1, "uniqeph malloc error n=%d\n", nav->n); free(nav->eph); nav->eph = NULL; nav->n = nav->nmax = 0; return; } nav->eph = nav_eph; nav->nmax = nav->n; trace(4, "uniqeph: n=%d\n", nav->n); } /* compare glonass ephemeris -------------------------------------------------*/ static int cmpgeph(const void* p1, const void* p2) { geph_t *q1 = (geph_t *)p1, *q2 = (geph_t *)p2; return q1->tof.time != q2->tof.time ? (int)(q1->tof.time - q2->tof.time) : (q1->toe.time != q2->toe.time ? (int)(q1->toe.time - q2->toe.time) : q1->sat - q2->sat); } /* sort and unique glonass ephemeris -----------------------------------------*/ static void uniqgeph(nav_t* nav) { geph_t* nav_geph; int i, j; trace(3, "uniqgeph: ng=%d\n", nav->ng); if (nav->ng <= 0) { return; } qsort(nav->geph, nav->ng, sizeof(geph_t), cmpgeph); for (i = j = 0; i < nav->ng; ++i) { if (nav->geph[i].sat != nav->geph[j].sat || nav->geph[i].toe.time != nav->geph[j].toe.time || nav->geph[i].svh != nav->geph[j].svh) { nav->geph[++j] = nav->geph[i]; } } nav->ng = j + 1; if (!(nav_geph = (geph_t*)realloc(nav->geph, sizeof(geph_t) * nav->ng))) { trace(1, "uniqgeph malloc error ng=%d\n", nav->ng); free(nav->geph); nav->geph = NULL; nav->ng = nav->ngmax = 0; return; } nav->geph = nav_geph; nav->ngmax = nav->ng; trace(4, "uniqgeph: ng=%d\n", nav->ng); } /* compare sbas ephemeris ----------------------------------------------------*/ static int cmpseph(const void* p1, const void* p2) { seph_t *q1 = (seph_t *)p1, *q2 = (seph_t *)p2; return q1->tof.time != q2->tof.time ? (int)(q1->tof.time - q2->tof.time) : (q1->t0.time != q2->t0.time ? (int)(q1->t0.time - q2->t0.time) : q1->sat - q2->sat); } /* sort and unique sbas ephemeris --------------------------------------------*/ static void uniqseph(nav_t* nav) { seph_t* nav_seph; int i, j; trace(3, "uniqseph: ns=%d\n", nav->ns); if (nav->ns <= 0) { return; } qsort(nav->seph, nav->ns, sizeof(seph_t), cmpseph); for (i = j = 0; i < nav->ns; ++i) { if (nav->seph[i].sat != nav->seph[j].sat || nav->seph[i].t0.time != nav->seph[j].t0.time) { nav->seph[++j] = nav->seph[i]; } } nav->ns = j + 1; if (!(nav_seph = (seph_t*)realloc(nav->seph, sizeof(seph_t) * nav->ns))) { trace(1, "uniqseph malloc error ns=%d\n", nav->ns); free(nav->seph); nav->seph = NULL; nav->ns = nav->nsmax = 0; return; } nav->seph = nav_seph; nav->nsmax = nav->ns; trace(4, "uniqseph: ns=%d\n", nav->ns); } /* unique ephemerides ---------------------------------------------------------- * unique ephemerides in navigation data and update carrier wave length * args : nav_t *nav IO navigation data * return : number of epochs *-----------------------------------------------------------------------------*/ extern void uniqnav(nav_t* nav) { int i, j; trace(3, "uniqnav: neph=%d ngeph=%d nseph=%d\n", nav->n, nav->ng, nav->ns); /* unique ephemeris */ uniqeph(nav); uniqgeph(nav); uniqseph(nav); /* update carrier wave length */ for (i = 0; i < MAXSAT; ++i) for (j = 0; j < NFREQ; ++j) { nav->lam[i][j] = satwavelen(i + 1, j, nav); } } /* compare observation data -------------------------------------------------*/ static int cmpobs(const void* p1, const void* p2) { obsd_t *q1 = (obsd_t *)p1, *q2 = (obsd_t *)p2; double tt = timediff(q1->time, q2->time); if (fabs(tt) > DTTOL) { return tt < 0 ? -1 : 1; } if (q1->rcv != q2->rcv) { return (int)q1->rcv - (int)q2->rcv; } return (int)q1->sat - (int)q2->sat; } /* sort and unique observation data -------------------------------------------- * sort and unique observation data by time, rcv, sat * args : obs_t *obs IO observation data * return : number of epochs *-----------------------------------------------------------------------------*/ extern int sortobs(obs_t* obs) { int i, j, n; trace(3, "sortobs: nobs=%d\n", obs->n); if (obs->n <= 0) { return 0; } qsort(obs->data, obs->n, sizeof(obsd_t), cmpobs); /* delete duplicated data */ for (i = j = 0; i < obs->n; ++i) { if (obs->data[i].sat != obs->data[j].sat || obs->data[i].rcv != obs->data[j].rcv || timediff(obs->data[i].time, obs->data[j].time) != 0.0) { obs->data[++j] = obs->data[i]; } } obs->n = j + 1; for (i = n = 0; i < obs->n; i = j, n++) { for (j = i + 1; j < obs->n; ++j) { if (timediff(obs->data[j].time, obs->data[i].time) > DTTOL) { break; } } } return n; } /* screen by time -------------------------------------------------------------- * screening by time start, time end, and time interval * args : gtime_t time I time * gtime_t ts I time start (ts.time==0:no screening by ts) * gtime_t te I time end (te.time==0:no screening by te) * double tint I time interval (s) (0.0:no screen by tint) * return : 1:on condition, 0:not on condition *-----------------------------------------------------------------------------*/ extern int screent(gtime_t time, gtime_t ts, gtime_t te, double tint) { return (tint <= 0.0 || fmod(time2gpst(time, NULL) + DTTOL, tint) <= DTTOL * 2.0) && (ts.time == 0 || timediff(time, ts) >= -DTTOL) && (te.time == 0 || timediff(time, te) < DTTOL); } /* read/save navigation data --------------------------------------------------- * save or load navigation data * args : char file I file path * nav_t nav O/I navigation data * return : status (1:ok,0:no file) *-----------------------------------------------------------------------------*/ extern int readnav(const char* file, nav_t* nav) { FILE* fp; eph_t eph0 = {0}; char buff[4096], *p; int i, sat; trace(3, "loadnav: file=%s\n", file); if (!(fp = fopen(file, "r"))) { return 0; } while (fgets(buff, sizeof(buff), fp)) { if (!strncmp(buff, "IONUTC", 6)) { for (i = 0; i < 8; ++i) { nav->ion_gps[i] = 0.0; } for (i = 0; i < 4; ++i) { nav->utc_gps[i] = 0.0; } nav->leaps = 0; sscanf(buff, "IONUTC,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%d", &nav->ion_gps[0], &nav->ion_gps[1], &nav->ion_gps[2], &nav->ion_gps[3], &nav->ion_gps[4], &nav->ion_gps[5], &nav->ion_gps[6], &nav->ion_gps[7], &nav->utc_gps[0], &nav->utc_gps[1], &nav->utc_gps[2], &nav->utc_gps[3], &nav->leaps); continue; } if ((p = strchr(buff, ','))) { *p = '\0'; } else { continue; } if (!(sat = satid2no(buff))) { continue; } nav->eph[sat - 1] = eph0; nav->eph[sat - 1].sat = sat; sscanf( p + 1, "%d,%d,%d,%d,%ld,%ld,%ld,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf," "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%d,%d", &nav->eph[sat - 1].iode, &nav->eph[sat - 1].iodc, &nav->eph[sat - 1].sva, &nav->eph[sat - 1].svh, &nav->eph[sat - 1].toe.time, &nav->eph[sat - 1].toc.time, &nav->eph[sat - 1].ttr.time, &nav->eph[sat - 1].A, &nav->eph[sat - 1].e, &nav->eph[sat - 1].i0, &nav->eph[sat - 1].OMG0, &nav->eph[sat - 1].omg, &nav->eph[sat - 1].M0, &nav->eph[sat - 1].deln, &nav->eph[sat - 1].OMGd, &nav->eph[sat - 1].idot, &nav->eph[sat - 1].crc, &nav->eph[sat - 1].crs, &nav->eph[sat - 1].cuc, &nav->eph[sat - 1].cus, &nav->eph[sat - 1].cic, &nav->eph[sat - 1].cis, &nav->eph[sat - 1].toes, &nav->eph[sat - 1].fit, &nav->eph[sat - 1].f0, &nav->eph[sat - 1].f1, &nav->eph[sat - 1].f2, &nav->eph[sat - 1].tgd[0], &nav->eph[sat - 1].code, &nav->eph[sat - 1].flag); } fclose(fp); return 1; } extern int savenav(const char* file, const nav_t* nav) { FILE* fp; int i; char id[32]; trace(3, "savenav: file=%s\n", file); if (!(fp = fopen(file, "w"))) { return 0; } for (i = 0; i < MAXSAT; ++i) { if (nav->eph[i].ttr.time == 0) { continue; } satno2id(nav->eph[i].sat, id); fprintf(fp, "%s,%d,%d,%d,%d,%d,%d,%d,%.14E,%.14E,%.14E,%.14E,%.14E,%.14E," "%.14E,%.14E,%.14E,%.14E,%.14E,%.14E,%.14E,%.14E,%.14E,%.14E," "%.14E,%.14E,%.14E,%.14E,%.14E,%d,%d\n", id, nav->eph[i].iode, nav->eph[i].iodc, nav->eph[i].sva, nav->eph[i].svh, (int)nav->eph[i].toe.time, (int)nav->eph[i].toc.time, (int)nav->eph[i].ttr.time, nav->eph[i].A, nav->eph[i].e, nav->eph[i].i0, nav->eph[i].OMG0, nav->eph[i].omg, nav->eph[i].M0, nav->eph[i].deln, nav->eph[i].OMGd, nav->eph[i].idot, nav->eph[i].crc, nav->eph[i].crs, nav->eph[i].cuc, nav->eph[i].cus, nav->eph[i].cic, nav->eph[i].cis, nav->eph[i].toes, nav->eph[i].fit, nav->eph[i].f0, nav->eph[i].f1, nav->eph[i].f2, nav->eph[i].tgd[0], nav->eph[i].code, nav->eph[i].flag); } fprintf(fp, "IONUTC,%.14E,%.14E,%.14E,%.14E,%.14E,%.14E,%.14E,%.14E,%.14E," "%.14E,%.14E,%.14E,%d", nav->ion_gps[0], nav->ion_gps[1], nav->ion_gps[2], nav->ion_gps[3], nav->ion_gps[4], nav->ion_gps[5], nav->ion_gps[6], nav->ion_gps[7], nav->utc_gps[0], nav->utc_gps[1], nav->utc_gps[2], nav->utc_gps[3], nav->leaps); fclose(fp); return 1; } /* free observation data ------------------------------------------------------- * free memory for observation data * args : obs_t *obs IO observation data * return : none *-----------------------------------------------------------------------------*/ extern void freeobs(obs_t* obs) { free(obs->data); obs->data = NULL; obs->n = obs->nmax = 0; } /* free navigation data *--------------------------------------------------------- * free memory for navigation data * args : nav_t *nav IO navigation data * int opt I option (or of followings) * (0x01: gps/qzs ephmeris, 0x02: glonass *ephemeris, * 0x04: sbas ephemeris, 0x08: precise *ephemeris, * 0x10: precise clock 0x20: almanac, * 0x40: tec data) * return : none *-----------------------------------------------------------------------------*/ extern void freenav(nav_t* nav, int opt) { if (opt & 0x01) { free(nav->eph); nav->eph = NULL; nav->n = nav->nmax = 0; } if (opt & 0x02) { free(nav->geph); nav->geph = NULL; nav->ng = nav->ngmax = 0; } if (opt & 0x04) { free(nav->seph); nav->seph = NULL; nav->ns = nav->nsmax = 0; } if (opt & 0x08) { free(nav->peph); nav->peph = NULL; nav->ne = nav->nemax = 0; } if (opt & 0x10) { free(nav->pclk); nav->pclk = NULL; nav->nc = nav->ncmax = 0; } if (opt & 0x20) { free(nav->alm); nav->alm = NULL; nav->na = nav->namax = 0; } if (opt & 0x40) { free(nav->tec); nav->tec = NULL; nav->nt = nav->ntmax = 0; } } /* debug trace functions -----------------------------------------------------*/ #ifdef TRACE static FILE* fp_trace = NULL; /* file pointer of trace */ static char file_trace[1024]; /* trace file */ static int level_trace = 0; /* level of trace */ static unsigned int tick_trace = 0; /* tick time at traceopen (ms) */ static gtime_t time_trace = {0}; /* time at traceopen */ static lock_t lock_trace; /* lock for trace */ static void traceswap(void) { gtime_t time = utc2gpst(timeget()); char path[1024]; lock(&lock_trace); if ((int)(time2gpst(time, NULL) / INT_SWAP_TRAC) == (int)(time2gpst(time_trace, NULL) / INT_SWAP_TRAC)) { unlock(&lock_trace); return; } time_trace = time; if (!reppath(file_trace, path, time, "", "")) { unlock(&lock_trace); return; } if (fp_trace) { fclose(fp_trace); } if (!(fp_trace = fopen(path, "w"))) { fp_trace = stderr; } unlock(&lock_trace); } extern void traceopen(const char* file) { gtime_t time = utc2gpst(timeget()); char path[1024]; reppath(file, path, time, "", ""); if (fp_trace) { fclose(fp_trace); } if (!*path || !(fp_trace = fopen(path, "w"))) { fp_trace = stderr; } strcpy(file_trace, file); tick_trace = tickget(); time_trace = time; initlock(&lock_trace); } extern void traceclose(void) { if (fp_trace && fp_trace != stderr) { fclose(fp_trace); } fp_trace = NULL; file_trace[0] = '\0'; } extern void tracelevel(int level) { level_trace = level; } extern void trace(int level, const char* format, ...) { va_list ap; /* print error message to stderr */ if (level <= 1) { va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); } if (!fp_trace || level > level_trace) { return; } traceswap(); fprintf(fp_trace, "%d ", level); va_start(ap, format); vfprintf(fp_trace, format, ap); va_end(ap); fflush(fp_trace); } extern void tracet(int level, const char* format, ...) { va_list ap; if (!fp_trace || level > level_trace) { return; } traceswap(); fprintf(fp_trace, "%d %9.3f: ", level, (tickget() - tick_trace) / 1000.0); va_start(ap, format); vfprintf(fp_trace, format, ap); va_end(ap); fflush(fp_trace); } extern void tracemat(int level, const double* A, int n, int m, int p, int q) { if (!fp_trace || level > level_trace) { return; } matfprint(A, n, m, p, q, fp_trace); fflush(fp_trace); } extern void traceobs(int level, const obsd_t* obs, int n) { char str[64], id[16]; int i; if (!fp_trace || level > level_trace) { return; } for (i = 0; i < n; ++i) { time2str(obs[i].time, str, 3); satno2id(obs[i].sat, id); fprintf(fp_trace, " (%2d) %s %-3s rcv%d %13.3f %13.3f %13.3f %13.3f %d %d %d %d " "%3.1f %3.1f\n", i + 1, str, id, obs[i].rcv, obs[i].L[0], obs[i].L[1], obs[i].P[0], obs[i].P[1], obs[i].LLI[0], obs[i].LLI[1], obs[i].code[0], obs[i].code[1], obs[i].SNR[0] * 0.25, obs[i].SNR[1] * 0.25); } fflush(fp_trace); } extern void tracenav(int level, const nav_t* nav) { char s1[64], s2[64], id[16]; int i; if (!fp_trace || level > level_trace) { return; } for (i = 0; i < nav->n; ++i) { time2str(nav->eph[i].toe, s1, 0); time2str(nav->eph[i].ttr, s2, 0); satno2id(nav->eph[i].sat, id); fprintf(fp_trace, "(%3d) %-3s : %s %s %3d %3d %02x\n", i + 1, id, s1, s2, nav->eph[i].iode, nav->eph[i].iodc, nav->eph[i].svh); } fprintf(fp_trace, "(ion) %9.4e %9.4e %9.4e %9.4e\n", nav->ion_gps[0], nav->ion_gps[1], nav->ion_gps[2], nav->ion_gps[3]); fprintf(fp_trace, "(ion) %9.4e %9.4e %9.4e %9.4e\n", nav->ion_gps[4], nav->ion_gps[5], nav->ion_gps[6], nav->ion_gps[7]); fprintf(fp_trace, "(ion) %9.4e %9.4e %9.4e %9.4e\n", nav->ion_gal[0], nav->ion_gal[1], nav->ion_gal[2], nav->ion_gal[3]); } extern void tracegnav(int level, const nav_t* nav) { char s1[64], s2[64], id[16]; int i; if (!fp_trace || level > level_trace) { return; } for (i = 0; i < nav->ng; ++i) { time2str(nav->geph[i].toe, s1, 0); time2str(nav->geph[i].tof, s2, 0); satno2id(nav->geph[i].sat, id); fprintf(fp_trace, "(%3d) %-3s : %s %s %2d %2d %8.3f\n", i + 1, id, s1, s2, nav->geph[i].frq, nav->geph[i].svh, nav->geph[i].taun * 1E6); } } extern void tracehnav(int level, const nav_t* nav) { char s1[64], s2[64], id[16]; int i; if (!fp_trace || level > level_trace) { return; } for (i = 0; i < nav->ns; ++i) { time2str(nav->seph[i].t0, s1, 0); time2str(nav->seph[i].tof, s2, 0); satno2id(nav->seph[i].sat, id); fprintf(fp_trace, "(%3d) %-3s : %s %s %2d %2d\n", i + 1, id, s1, s2, nav->seph[i].svh, nav->seph[i].sva); } } extern void tracepeph(int level, const nav_t* nav) { char s[64], id[16]; int i, j; if (!fp_trace || level > level_trace) { return; } for (i = 0; i < nav->ne; ++i) { time2str(nav->peph[i].time, s, 0); for (j = 0; j < MAXSAT; ++j) { satno2id(j + 1, id); fprintf( fp_trace, "%-3s %d %-3s %13.3f %13.3f %13.3f %13.3f %6.3f %6.3f %6.3f %6.3f\n", s, nav->peph[i].index, id, nav->peph[i].pos[j][0], nav->peph[i].pos[j][1], nav->peph[i].pos[j][2], nav->peph[i].pos[j][3] * 1E9, nav->peph[i].std[j][0], nav->peph[i].std[j][1], nav->peph[i].std[j][2], nav->peph[i].std[j][3] * 1E9); } } } extern void tracepclk(int level, const nav_t* nav) { char s[64], id[16]; int i, j; if (!fp_trace || level > level_trace) { return; } for (i = 0; i < nav->nc; ++i) { time2str(nav->pclk[i].time, s, 0); for (j = 0; j < MAXSAT; ++j) { satno2id(j + 1, id); fprintf(fp_trace, "%-3s %d %-3s %13.3f %6.3f\n", s, nav->pclk[i].index, id, nav->pclk[i].clk[j][0] * 1E9, nav->pclk[i].std[j][0] * 1E9); } } } extern void traceb(int level, const unsigned char* p, int n) { int i; if (!fp_trace || level > level_trace) { return; } for (i = 0; i < n; ++i) { fprintf(fp_trace, "%02X%s", *p++, i % 8 == 7 ? " " : ""); } fprintf(fp_trace, "\n"); } #else extern void traceopen(const char* file) {} extern void traceclose(void) {} extern void tracelevel(int level) {} extern void trace(int level, const char* format, ...) {} extern void tracet(int level, const char* format, ...) {} extern void tracemat(int level, const double* A, int n, int m, int p, int q) {} extern void traceobs(int level, const obsd_t* obs, int n) {} extern void tracenav(int level, const nav_t* nav) {} extern void tracegnav(int level, const nav_t* nav) {} extern void tracehnav(int level, const nav_t* nav) {} extern void tracepeph(int level, const nav_t* nav) {} extern void tracepclk(int level, const nav_t* nav) {} extern void traceb(int level, const unsigned char* p, int n) {} #endif /* TRACE */ /* execute command ------------------------------------------------------------- * execute command line by operating system shell * args : char *cmd I command line * return : execution status (0:ok,0>:error) *-----------------------------------------------------------------------------*/ extern int execcmd(const char* cmd) { #ifdef WIN32 PROCESS_INFORMATION info; STARTUPINFO si = {0}; DWORD stat; char cmds[1024]; trace(3, "execcmd: cmd=%s\n", cmd); si.cb = sizeof(si); sprintf(cmds, "cmd /c %s", cmd); if (!CreateProcess(NULL, (LPTSTR)cmds, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &info)) { return -1; } WaitForSingleObject(info.hProcess, INFINITE); if (!GetExitCodeProcess(info.hProcess, &stat)) { stat = -1; } CloseHandle(info.hProcess); CloseHandle(info.hThread); return (int)stat; #else trace(3, "execcmd: cmd=%s\n", cmd); return system(cmd); #endif } /* expand file path ------------------------------------------------------------ * expand file path with wild-card (*) in file * args : char *path I file path to expand (captal insensitive) * char *paths O expanded file paths * int nmax I max number of expanded file paths * return : number of expanded file paths * notes : the order of expanded files is alphabetical order *-----------------------------------------------------------------------------*/ extern int expath(const char* path, char* paths[], int nmax) { int i, j, n = 0; char tmp[1024]; #ifdef WIN32 WIN32_FIND_DATA file; HANDLE h; char dir[1024] = "", *p; trace(3, "expath : path=%s nmax=%d\n", path, nmax); if ((p = strrchr(path, '\\'))) { strncpy(dir, path, p - path + 1); dir[p - path + 1] = '\0'; } if ((h = FindFirstFile((LPCTSTR)path, &file)) == INVALID_HANDLE_VALUE) { strcpy(paths[0], path); return 1; } sprintf(paths[n++], "%s%s", dir, file.cFileName); while (FindNextFile(h, &file) && n < nmax) { if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } sprintf(paths[n++], "%s%s", dir, file.cFileName); } FindClose(h); #else struct dirent* d; DIR* dp; const char* file = path; char dir[1024] = "", s1[1024], s2[1024], *p, *q, *r; trace(3, "expath : path=%s nmax=%d\n", path, nmax); if ((p = strrchr(path, '/')) || (p = strrchr(path, '\\'))) { file = p + 1; strncpy(dir, path, p - path + 1); dir[p - path + 1] = '\0'; } if (!(dp = opendir(*dir ? dir : "."))) { return 0; } while ((d = readdir(dp))) { if (*(d->d_name) == '.') { continue; } sprintf(s1, "^%s$", d->d_name); sprintf(s2, "^%s$", file); for (p = s1; *p; p++) { *p = (char)tolower((int)*p); } for (p = s2; *p; p++) { *p = (char)tolower((int)*p); } for (p = s1, q = strtok_r(s2, "*", &r); q; q = strtok_r(NULL, "*", &r)) { if ((p = strstr(p, q))) { p += strlen(q); } else { break; } } if (p && n < nmax) { sprintf(paths[n++], "%s%s", dir, d->d_name); } } closedir(dp); #endif /* sort paths in alphabetical order */ for (i = 0; i < n - 1; ++i) { for (j = i + 1; j < n; ++j) { if (strcmp(paths[i], paths[j]) > 0) { strcpy(tmp, paths[i]); strcpy(paths[i], paths[j]); strcpy(paths[j], tmp); } } } for (i = 0; i < n; ++i) { trace(3, "expath : file=%s\n", paths[i]); } return n; } /* create directory ------------------------------------------------------------ * create directory if not exist * args : char *path I file path to be saved * return : none * notes : not recursive. only one level *-----------------------------------------------------------------------------*/ extern void createdir(const char* path) { char buff[1024], *p; tracet(3, "createdir: path=%s\n", path); strcpy(buff, path); if (!(p = strrchr(buff, FILEPATHSEP))) { return; } *p = '\0'; #ifdef WIN32 CreateDirectory(buff, NULL); #else mkdir(buff, 0777); #endif } /* replace string ------------------------------------------------------------*/ static int repstr(char* str, const char* pat, const char* rep) { int len = strlen(pat); char buff[1024], *p, *q, *r; for (p = str, r = buff; *p; p = q + len) { if (!(q = strstr(p, pat))) { break; } strncpy(r, p, q - p); r += q - p; r += sprintf(r, "%s", rep); } if (p <= str) { return 0; } strcpy(r, p); strcpy(str, buff); return 1; } /* replace keywords in file path ----------------------------------------------- * replace keywords in file path with date, time, rover and base station id * args : char *path I file path (see below) * char *rpath O file path in which keywords replaced (see below) * gtime_t time I time (gpst) (time.time==0: not replaced) * char *rov I rover id string ("": not replaced) * char *base I base station id string ("": not replaced) * return : status (1:keywords replaced, 0:no valid keyword in the path, * -1:no valid time) * notes : the following keywords in path are replaced by date, time and name * %Y -> yyyy : year (4 digits) (1900-2099) * %y -> yy : year (2 digits) (00-99) * %m -> mm : month (01-12) * %d -> dd : day of month (01-31) * %h -> hh : hours (00-23) * %M -> mm : minutes (00-59) * %S -> ss : seconds (00-59) * %n -> ddd : day of year (001-366) * %W -> wwww : gps week (0001-9999) * %D -> d : day of gps week (0-6) * %H -> h : hour code (a=0,b=1,c=2,...,x=23) * %ha-> hh : 3 hours (00,03,06,...,21) * %hb-> hh : 6 hours (00,06,12,18) * %hc-> hh : 12 hours (00,12) * %t -> mm : 15 minutes (00,15,30,45) * %r -> rrrr : rover id * %b -> bbbb : base station id *-----------------------------------------------------------------------------*/ extern int reppath(const char* path, char* rpath, gtime_t time, const char* rov, const char* base) { double ep[6], ep0[6] = {2000, 1, 1, 0, 0, 0}; int week, dow, doy, stat = 0; char rep[64]; trace(3, "reppath : path =%s time=%s rov=%s base=%s\n", path, time_str(time, 0), rov, base); strcpy(rpath, path); if (!strstr(rpath, "%")) { return 0; } if (*rov) { stat |= repstr(rpath, "%r", rov); } if (*base) { stat |= repstr(rpath, "%b", base); } if (time.time != 0) { time2epoch(time, ep); ep0[0] = ep[0]; dow = (int)floor(time2gpst(time, &week) / 86400.0); doy = (int)floor(timediff(time, epoch2time(ep0)) / 86400.0) + 1; sprintf(rep, "%02d", ((int)ep[3] / 3) * 3); stat |= repstr(rpath, "%ha", rep); sprintf(rep, "%02d", ((int)ep[3] / 6) * 6); stat |= repstr(rpath, "%hb", rep); sprintf(rep, "%02d", ((int)ep[3] / 12) * 12); stat |= repstr(rpath, "%hc", rep); sprintf(rep, "%04.0f", ep[0]); stat |= repstr(rpath, "%Y", rep); sprintf(rep, "%02.0f", fmod(ep[0], 100.0)); stat |= repstr(rpath, "%y", rep); sprintf(rep, "%02.0f", ep[1]); stat |= repstr(rpath, "%m", rep); sprintf(rep, "%02.0f", ep[2]); stat |= repstr(rpath, "%d", rep); sprintf(rep, "%02.0f", ep[3]); stat |= repstr(rpath, "%h", rep); sprintf(rep, "%02.0f", ep[4]); stat |= repstr(rpath, "%M", rep); sprintf(rep, "%02.0f", floor(ep[5])); stat |= repstr(rpath, "%S", rep); sprintf(rep, "%03d", doy); stat |= repstr(rpath, "%n", rep); sprintf(rep, "%04d", week); stat |= repstr(rpath, "%W", rep); sprintf(rep, "%d", dow); stat |= repstr(rpath, "%D", rep); sprintf(rep, "%c", 'a' + (int)ep[3]); stat |= repstr(rpath, "%H", rep); sprintf(rep, "%02d", ((int)ep[4] / 15) * 15); stat |= repstr(rpath, "%t", rep); } else if (strstr(rpath, "%ha") || strstr(rpath, "%hb") || strstr(rpath, "%hc") || strstr(rpath, "%Y") || strstr(rpath, "%y") || strstr(rpath, "%m") || strstr(rpath, "%d") || strstr(rpath, "%h") || strstr(rpath, "%M") || strstr(rpath, "%S") || strstr(rpath, "%n") || strstr(rpath, "%W") || strstr(rpath, "%D") || strstr(rpath, "%H") || strstr(rpath, "%t")) { return -1; /* no valid time */ } trace(3, "reppath : rpath=%s\n", rpath); return stat; } /* replace keywords in file path and generate multiple paths ------------------- * replace keywords in file path with date, time, rover and base station id * generate multiple keywords-replaced paths * args : char *path I file path (see below) * char *rpath[] O file paths in which keywords replaced * int nmax I max number of output file paths * gtime_t ts I time start (gpst) * gtime_t te I time end (gpst) * char *rov I rover id string ("": not replaced) * char *base I base station id string ("": not replaced) * return : number of replaced file paths * notes : see reppath() for replacements of keywords. * minimum interval of time replaced is 900s. *-----------------------------------------------------------------------------*/ extern int reppaths(const char* path, char* rpath[], int nmax, gtime_t ts, gtime_t te, const char* rov, const char* base) { gtime_t time; double tow, tint = 86400.0; int i, n = 0, week; trace(3, "reppaths: path =%s nmax=%d rov=%s base=%s\n", path, nmax, rov, base); if (ts.time == 0 || te.time == 0 || timediff(ts, te) > 0.0) { return 0; } if (strstr(path, "%S") || strstr(path, "%M") || strstr(path, "%t")) { tint = 900.0; } else if (strstr(path, "%h") || strstr(path, "%H")) { tint = 3600.0; } tow = time2gpst(ts, &week); time = gpst2time(week, floor(tow / tint) * tint); while (timediff(time, te) <= 0.0 && n < nmax) { reppath(path, rpath[n], time, rov, base); if (n == 0 || strcmp(rpath[n], rpath[n - 1])) { n++; } time = timeadd(time, tint); } for (i = 0; i < n; ++i) { trace(3, "reppaths: rpath=%s\n", rpath[i]); } return n; } /* satellite carrier wave length ----------------------------------------------- * get satellite carrier wave lengths * args : int sat I satellite number * int frq I frequency index (0:L1,1:L2,2:L5/3,...) * nav_t *nav I navigation messages * return : carrier wave length (m) (0.0: error) *-----------------------------------------------------------------------------*/ extern double satwavelen(int sat, int frq, const nav_t* nav) { const double freq_glo[] = {FREQ1_GLO, FREQ2_GLO, FREQ3_GLO}; const double dfrq_glo[] = {DFRQ1_GLO, DFRQ2_GLO, 0.0}; int i, sys = satsys(sat, NULL); if (sys == SYS_GLO) { if (0 <= frq && frq <= 2) { for (i = 0; i < nav->ng; ++i) { if (nav->geph[i].sat != sat) { continue; } return CLIGHT / (freq_glo[frq] + dfrq_glo[frq] * nav->geph[i].frq); } } } else if (sys == SYS_CMP) { if (frq == 0) { return CLIGHT / FREQ1_CMP; /* B1 */ } else if (frq == 1) { return CLIGHT / FREQ2_CMP; /* B3 */ } else if (frq == 2) { return CLIGHT / FREQ3_CMP; /* B2 */ } } else { if (frq == 0) { return CLIGHT / FREQ1; /* L1/E1 */ } else if (frq == 1) { return CLIGHT / FREQ2; /* L2 */ } else if (frq == 2) { return CLIGHT / FREQ5; /* L5/E5a */ } else if (frq == 3) { return CLIGHT / FREQ6; /* L6/LEX */ } else if (frq == 4) { return CLIGHT / FREQ7; /* E5b */ } else if (frq == 5) { return CLIGHT / FREQ8; /* E5a+b */ } } return 0.0; } /* geometric distance ---------------------------------------------------------- * compute geometric distance and receiver-to-satellite unit vector * args : double *rs I satellilte position (ecef at transmission) (m) * double *rr I receiver position (ecef at reception) (m) * double *e O line-of-sight vector (ecef) * return : geometric distance (m) (0>:error/no satellite position) * notes : distance includes sagnac effect correction *-----------------------------------------------------------------------------*/ extern double geodist(const double* rs, const double* rr, double* e) { double r; int i; if (norm(rs, 3) < RE_WGS84) { return -1.0; } for (i = 0; i < 3; ++i) { e[i] = rs[i] - rr[i]; } r = norm(e, 3); for (i = 0; i < 3; ++i) { e[i] /= r; } return r + OMGE * (rs[0] * rr[1] - rs[1] * rr[0]) / CLIGHT; } /* satellite azimuth/elevation angle ------------------------------------------- * compute satellite azimuth/elevation angle * args : double *pos I geodetic position {lat,lon,h} (rad,m) * double *e I receiver-to-satellilte unit vevtor (ecef) * double *azel IO azimuth/elevation {az,el} (rad) (NULL: no *output) * (0.0<=azel[0]<2*pi,-pi/2<=azel[1]<=pi/2) * return : elevation angle (rad) *-----------------------------------------------------------------------------*/ extern double satazel(const double* pos, const double* e, double* azel) { double az = 0.0, el = PI / 2.0, enu[3]; if (pos[2] > -RE_WGS84) { ecef2enu(pos, e, enu); az = dot(enu, enu, 2) < 1E-12 ? 0.0 : atan2(enu[0], enu[1]); if (az < 0.0) { az += 2 * PI; } el = asin(enu[2]); } if (azel) { azel[0] = az; azel[1] = el; } return el; } /* compute dops ---------------------------------------------------------------- * compute DOP (dilution of precision) * args : int ns I number of satellites * double *azel I satellite azimuth/elevation angle (rad) * double elmin I elevation cutoff angle (rad) * double *dop O DOPs {GDOP,PDOP,HDOP,VDOP} * return : none * notes : dop[0]-[3] return 0 in case of dop computation error *-----------------------------------------------------------------------------*/ #define SQRT(x) ((x) < 0.0 ? 0.0 : sqrt(x)) extern void dops(int ns, const double* azel, double elmin, double* dop) { double H[4 * MAXSAT], Q[16], cosel, sinel; int i, n; for (i = 0; i < 4; ++i) { dop[i] = 0.0; } for (i = n = 0; i < ns && i < MAXSAT; ++i) { if (azel[1 + i * 2] < elmin || azel[1 + i * 2] <= 0.0) { continue; } cosel = cos(azel[1 + i * 2]); sinel = sin(azel[1 + i * 2]); H[4 * n] = cosel * sin(azel[i * 2]); H[1 + 4 * n] = cosel * cos(azel[i * 2]); H[2 + 4 * n] = sinel; H[3 + 4 * n++] = 1.0; } if (n < 4) { return; } matmul("NT", 4, 4, n, 1.0, H, H, 0.0, Q); if (!matinv(Q, 4)) { dop[0] = SQRT(Q[0] + Q[5] + Q[10] + Q[15]); /* GDOP */ dop[1] = SQRT(Q[0] + Q[5] + Q[10]); /* PDOP */ dop[2] = SQRT(Q[0] + Q[5]); /* HDOP */ dop[3] = SQRT(Q[10]); /* VDOP */ } } /* ionosphere model ------------------------------------------------------------ * compute ionospheric delay by broadcast ionosphere model (klobuchar model) * args : gtime_t t I time (gpst) * double *ion I iono model parameters {a0,a1,a2,a3,b0,b1,b2,b3} * double *pos I receiver position {lat,lon,h} (rad,m) * double *azel I azimuth/elevation angle {az,el} (rad) * return : ionospheric delay (L1) (m) *-----------------------------------------------------------------------------*/ extern double ionmodel(gtime_t t, const double* ion, const double* pos, const double* azel) { const double ion_default[] = {/* 2004/1/1 */ 0.1118E-07, -0.7451E-08, -0.5961E-07, 0.1192E-06, 0.1167E+06, -0.2294E+06, -0.1311E+06, 0.1049E+07}; double tt, f, psi, phi, lam, amp, per, x; int week; if (pos[2] < -1E3 || azel[1] <= 0) { return 0.0; } if (norm(ion, 8) <= 0.0) { ion = ion_default; } /* earth centered angle (semi-circle) */ psi = 0.0137 / (azel[1] / PI + 0.11) - 0.022; /* subionospheric latitude/longitude (semi-circle) */ phi = pos[0] / PI + psi * cos(azel[0]); if (phi > 0.416) { phi = 0.416; } else if (phi < -0.416) { phi = -0.416; } lam = pos[1] / PI + psi * sin(azel[0]) / cos(phi * PI); /* geomagnetic latitude (semi-circle) */ phi += 0.064 * cos((lam - 1.617) * PI); /* local time (s) */ tt = 43200.0 * lam + time2gpst(t, &week); tt -= floor(tt / 86400.0) * 86400.0; /* 0<=tt<86400 */ /* slant factor */ f = 1.0 + 16.0 * pow(0.53 - azel[1] / PI, 3.0); /* ionospheric delay */ amp = ion[0] + phi * (ion[1] + phi * (ion[2] + phi * ion[3])); per = ion[4] + phi * (ion[5] + phi * (ion[6] + phi * ion[7])); amp = amp < 0.0 ? 0.0 : amp; per = per < 72000.0 ? 72000.0 : per; x = 2.0 * PI * (tt - 50400.0) / per; return CLIGHT * f * (fabs(x) < 1.57 ? 5E-9 + amp * (1.0 + x * x * (-0.5 + x * x / 24.0)) : 5E-9); } /* ionosphere mapping function ------------------------------------------------- * compute ionospheric delay mapping function by single layer model * args : double *pos I receiver position {lat,lon,h} (rad,m) * double *azel I azimuth/elevation angle {az,el} (rad) * return : ionospheric mapping function *-----------------------------------------------------------------------------*/ extern double ionmapf(const double* pos, const double* azel) { if (pos[2] >= HION) { return 1.0; } return 1.0 / cos(asin((RE_WGS84 + pos[2]) / (RE_WGS84 + HION) * sin(PI / 2.0 - azel[1]))); } /* ionospheric pierce point position ------------------------------------------- * compute ionospheric pierce point (ipp) position and slant factor * args : double *pos I receiver position {lat,lon,h} (rad,m) * double *azel I azimuth/elevation angle {az,el} (rad) * double re I earth radius (km) * double hion I altitude of ionosphere (km) * double *posp O pierce point position {lat,lon,h} (rad,m) * return : slant factor * notes : see ref [2], only valid on the earth surface * fixing bug on ref [2] A.4.4.10.1 A-22,23 *-----------------------------------------------------------------------------*/ extern double ionppp(const double* pos, const double* azel, double re, double hion, double* posp) { double cosaz, rp, ap, sinap, tanap; rp = re / (re + hion) * cos(azel[1]); ap = PI / 2.0 - azel[1] - asin(rp); sinap = sin(ap); tanap = tan(ap); cosaz = cos(azel[0]); posp[0] = asin(sin(pos[0]) * cos(ap) + cos(pos[0]) * sinap * cosaz); if ((pos[0] > 70.0 * D2R && tanap * cosaz > tan(PI / 2.0 - pos[0])) || (pos[0] < -70.0 * D2R && -tanap * cosaz > tan(PI / 2.0 + pos[0]))) { posp[1] = pos[1] + PI - asin(sinap * sin(azel[0]) / cos(posp[0])); } else { posp[1] = pos[1] + asin(sinap * sin(azel[0]) / cos(posp[0])); } return 1.0 / sqrt(1.0 - rp * rp); } /* troposphere model ----------------------------------------------------------- * compute tropospheric delay by standard atmosphere and saastamoinen model * args : gtime_t time I time * double *pos I receiver position {lat,lon,h} (rad,m) * double *azel I azimuth/elevation angle {az,el} (rad) * double humi I relative humidity * return : tropospheric delay (m) *-----------------------------------------------------------------------------*/ extern double tropmodel(gtime_t time, const double* pos, const double* azel, double humi) { const double temp0 = 15.0; /* temparature at sea level */ double hgt, pres, temp, e, z, trph, trpw; if (pos[2] < -100.0 || 1E4 < pos[2] || azel[1] <= 0) { return 0.0; } /* standard atmosphere */ hgt = pos[2] < 0.0 ? 0.0 : pos[2]; pres = 1013.25 * pow(1.0 - 2.2557E-5 * hgt, 5.2568); temp = temp0 - 6.5E-3 * hgt + 273.16; e = 6.108 * humi * exp((17.15 * temp - 4684.0) / (temp - 38.45)); /* saastamoninen model */ z = PI / 2.0 - azel[1]; trph = 0.0022768 * pres / (1.0 - 0.00266 * cos(2.0 * pos[0]) - 0.00028 * hgt / 1E3) / cos(z); trpw = 0.002277 * (1255.0 / temp + 0.05) * e / cos(z); return trph + trpw; } static double interpc(const double coef[], double lat) { int i = (int)(lat / 15.0); if (i < 1) { return coef[0]; } else if (i > 4) { return coef[4]; } return coef[i - 1] * (1.0 - lat / 15.0 + i) + coef[i] * (lat / 15.0 - i); } static double mapf(double el, double a, double b, double c) { double sinel = sin(el); return (1.0 + a / (1.0 + b / (1.0 + c))) / (sinel + (a / (sinel + b / (sinel + c)))); } static double nmf(gtime_t time, const double pos[], const double azel[], double* mapfw) { /* ref [5] table 3 */ /* hydro-ave-a,b,c, hydro-amp-a,b,c, wet-a,b,c at latitude 15,30,45,60,75 */ const double coef[][5] = { {1.2769934E-3, 1.2683230E-3, 1.2465397E-3, 1.2196049E-3, 1.2045996E-3}, {2.9153695E-3, 2.9152299E-3, 2.9288445E-3, 2.9022565E-3, 2.9024912E-3}, {62.610505E-3, 62.837393E-3, 63.721774E-3, 63.824265E-3, 64.258455E-3}, {0.0000000E-0, 1.2709626E-5, 2.6523662E-5, 3.4000452E-5, 4.1202191E-5}, {0.0000000E-0, 2.1414979E-5, 3.0160779E-5, 7.2562722E-5, 11.723375E-5}, {0.0000000E-0, 9.0128400E-5, 4.3497037E-5, 84.795348E-5, 170.37206E-5}, {5.8021897E-4, 5.6794847E-4, 5.8118019E-4, 5.9727542E-4, 6.1641693E-4}, {1.4275268E-3, 1.5138625E-3, 1.4572752E-3, 1.5007428E-3, 1.7599082E-3}, {4.3472961E-2, 4.6729510E-2, 4.3908931E-2, 4.4626982E-2, 5.4736038E-2}}; const double aht[] = {2.53E-5, 5.49E-3, 1.14E-3}; /* height correction */ double y, cosy, ah[3], aw[3], dm, el = azel[1], lat = pos[0] * R2D, hgt = pos[2]; int i; if (el <= 0.0) { if (mapfw) { *mapfw = 0.0; } return 0.0; } /* year from doy 28, added half a year for southern latitudes */ y = (time2doy(time) - 28.0) / 365.25 + (lat < 0.0 ? 0.5 : 0.0); cosy = cos(2.0 * PI * y); lat = fabs(lat); for (i = 0; i < 3; ++i) { ah[i] = interpc(coef[i], lat) - interpc(coef[i + 3], lat) * cosy; aw[i] = interpc(coef[i + 6], lat); } /* ellipsoidal height is used instead of height above sea level */ dm = (1.0 / sin(el) - mapf(el, aht[0], aht[1], aht[2])) * hgt / 1E3; if (mapfw) { *mapfw = mapf(el, aw[0], aw[1], aw[2]); } return mapf(el, ah[0], ah[1], ah[2]) + dm; } /* troposphere mapping function ------------------------------------------------ * compute tropospheric mapping function by NMF * args : gtime_t t I time * double *pos I receiver position {lat,lon,h} (rad,m) * double *azel I azimuth/elevation angle {az,el} (rad) * double *mapfw IO wet mapping function (NULL: not output) * return : dry mapping function * note : see ref [5] (NMF) and [9] (GMF) * original JGR paper of [5] has bugs in eq.(4) and (5). the corrected * paper is obtained from: * ftp://web.haystack.edu/pub/aen/nmf/NMF_JGR.pdf *-----------------------------------------------------------------------------*/ extern double tropmapf(gtime_t time, const double pos[], const double azel[], double* mapfw) { #ifdef IERS_MODEL const double ep[] = {2000, 1, 1, 12, 0, 0}; double mjd, lat, lon, hgt, zd, gmfh, gmfw; #endif trace(4, "tropmapf: pos=%10.6f %11.6f %6.1f azel=%5.1f %4.1f\n", pos[0] * R2D, pos[1] * R2D, pos[2], azel[0] * R2D, azel[1] * R2D); if (pos[2] < -1000.0 || pos[2] > 20000.0) { if (mapfw) { *mapfw = 0.0; } return 0.0; } #ifdef IERS_MODEL mjd = 51544.5 + (timediff(time, epoch2time(ep))) / 86400.0; lat = pos[0]; lon = pos[1]; hgt = pos[2] - geoidh(pos); /* height in m (mean sea level) */ zd = PI / 2.0 - azel[1]; /* call GMF */ gmf_(&mjd, &lat, &lon, &hgt, &zd, &gmfh, &gmfw); if (mapfw) { *mapfw = gmfw; } return gmfh; #else return nmf(time, pos, azel, mapfw); /* NMF */ #endif } /* interpolate antenna phase center variation --------------------------------*/ static double interpvar(double ang, const double* var) { double a = ang / 5.0; /* ang=0-90 */ int i = (int)a; if (i < 0) { return var[0]; } else if (i >= 18) { return var[18]; } return var[i] * (1.0 - a + i) + var[i + 1] * (a - i); } /* receiver antenna model ------------------------------------------------------ * compute antenna offset by antenna phase center parameters * args : pcv_t *pcv I antenna phase center parameters * double *azel I azimuth/elevation for receiver {az,el} (rad) * int opt I option (0:only offset,1:offset+pcv) * double *dant O range offsets for each frequency (m) * return : none * notes : current version does not support azimuth dependent terms *-----------------------------------------------------------------------------*/ extern void antmodel(const pcv_t* pcv, const double* del, const double* azel, int opt, double* dant) { double e[3], off[3], cosel = cos(azel[1]); int i, j; trace(4, "antmodel: azel=%6.1f %4.1f opt=%d\n", azel[0] * R2D, azel[1] * R2D, opt); e[0] = sin(azel[0]) * cosel; e[1] = cos(azel[0]) * cosel; e[2] = sin(azel[1]); for (i = 0; i < NFREQ; ++i) { for (j = 0; j < 3; ++j) { off[j] = pcv->off[i][j] + del[j]; } dant[i] = -dot(off, e, 3) + (opt ? interpvar(90.0 - azel[1] * R2D, pcv->var[i]) : 0.0); } trace(5, "antmodel: dant=%6.3f %6.3f\n", dant[0], dant[1]); } /* satellite antenna model *------------------------------------------------------ * compute satellite antenna phase center parameters * args : pcv_t *pcv I antenna phase center parameters * double nadir I nadir angle for satellite (rad) * double *dant O range offsets for each frequency (m) * return : none *-----------------------------------------------------------------------------*/ extern void antmodel_s(const pcv_t* pcv, double nadir, double* dant) { int i; trace(4, "antmodel_s: nadir=%6.1f\n", nadir * R2D); for (i = 0; i < NFREQ; ++i) { dant[i] = interpvar(nadir * R2D * 5.0, pcv->var[i]); } trace(5, "antmodel_s: dant=%6.3f %6.3f\n", dant[0], dant[1]); } /* sun and moon position in eci (ref [4] 5.1.1, 5.2.1) -----------------------*/ static void sunmoonpos_eci(gtime_t tut, double* rsun, double* rmoon) { const double ep2000[] = {2000, 1, 1, 12, 0, 0}; double t, f[5], eps, Ms, ls, rs, lm, pm, rm, sine, cose, sinp, cosp, sinl, cosl; trace(3, "sunmoonpos_eci: tut=%s\n", time_str(tut, 3)); t = timediff(tut, epoch2time(ep2000)) / 86400.0 / 36525.0; /* astronomical arguments */ ast_args(t, f); /* obliquity of the ecliptic */ eps = 23.439291 - 0.0130042 * t; sine = sin(eps * D2R); cose = cos(eps * D2R); /* sun position in eci */ if (rsun) { Ms = 357.5277233 + 35999.05034 * t; ls = 280.460 + 36000.770 * t + 1.914666471 * sin(Ms * D2R) + 0.019994643 * sin(2.0 * Ms * D2R); rs = AU * (1.000140612 - 0.016708617 * cos(Ms * D2R) - 0.000139589 * cos(2.0 * Ms * D2R)); sinl = sin(ls * D2R); cosl = cos(ls * D2R); rsun[0] = rs * cosl; rsun[1] = rs * cose * sinl; rsun[2] = rs * sine * sinl; trace(5, "rsun =%.3f %.3f %.3f\n", rsun[0], rsun[1], rsun[2]); } /* moon position in eci */ if (rmoon) { lm = 218.32 + 481267.883 * t + 6.29 * sin(f[0]) - 1.27 * sin(f[0] - 2.0 * f[3]) + 0.66 * sin(2.0 * f[3]) + 0.21 * sin(2.0 * f[0]) - 0.19 * sin(f[1]) - 0.11 * sin(2.0 * f[2]); pm = 5.13 * sin(f[2]) + 0.28 * sin(f[0] + f[2]) - 0.28 * sin(f[2] - f[0]) - 0.17 * sin(f[2] - 2.0 * f[3]); rm = RE_WGS84 / sin((0.9508 + 0.0518 * cos(f[0]) + 0.0095 * cos(f[0] - 2.0 * f[3]) + 0.0078 * cos(2.0 * f[3]) + 0.0028 * cos(2.0 * f[0])) * D2R); sinl = sin(lm * D2R); cosl = cos(lm * D2R); sinp = sin(pm * D2R); cosp = cos(pm * D2R); rmoon[0] = rm * cosp * cosl; rmoon[1] = rm * (cose * cosp * sinl - sine * sinp); rmoon[2] = rm * (sine * cosp * sinl + cose * sinp); trace(5, "rmoon=%.3f %.3f %.3f\n", rmoon[0], rmoon[1], rmoon[2]); } } /* sun and moon position ------------------------------------------------------- * get sun and moon position in ecef * args : gtime_t tut I time in ut1 * double *erpv I erp value {xp,yp,ut1_utc,lod} (rad,rad,s,s/d) * double *rsun IO sun position in ecef (m) (NULL: not output) * double *rmoon IO moon position in ecef (m) (NULL: not output) * double *gmst O gmst (rad) * return : none *-----------------------------------------------------------------------------*/ extern void sunmoonpos(gtime_t tutc, const double* erpv, double* rsun, double* rmoon, double* gmst) { gtime_t tut; double rs[3], rm[3], U[9], gmst_; trace(3, "sunmoonpos: tutc=%s\n", time_str(tutc, 3)); tut = timeadd(tutc, erpv[2]); /* utc -> ut1 */ /* sun and moon position in eci */ sunmoonpos_eci(tut, rsun ? rs : NULL, rmoon ? rm : NULL); /* eci to ecef transformation matrix */ eci2ecef(tutc, erpv, U, &gmst_); /* sun and moon postion in ecef */ if (rsun) { matmul("NN", 3, 1, 3, 1.0, U, rs, 0.0, rsun); } if (rmoon) { matmul("NN", 3, 1, 3, 1.0, U, rm, 0.0, rmoon); } if (gmst) { *gmst = gmst_; } } /* phase windup correction ----------------------------------------------------- * phase windup correction (ref [7] 5.1.2) * args : gtime_t time I time (GPST) * double *rs I satellite position (ecef) {x,y,z} (m) * double *rr I receiver position (ecef) {x,y,z} (m) * double *phw IO phase windup correction (cycle) * return : none * notes : the previous value of phase windup correction should be set to *phw * as an input. the function assumes windup correction has no jump more * than 0.5 cycle. *-----------------------------------------------------------------------------*/ extern void windupcorr(gtime_t time, const double* rs, const double* rr, double* phw) { double ek[3], exs[3], eys[3], ezs[3], ess[3], exr[3], eyr[3], eks[3], ekr[3], E[9]; double dr[3], ds[3], drs[3], r[3], pos[3], rsun[3], cosp, ph, erpv[5] = {0}; int i; trace(4, "windupcorr: time=%s\n", time_str(time, 0)); /* sun position in ecef */ sunmoonpos(gpst2utc(time), erpv, rsun, NULL, NULL); /* unit vector satellite to receiver */ for (i = 0; i < 3; ++i) { r[i] = rr[i] - rs[i]; } if (!normv3(r, ek)) { return; } /* unit vectors of satellite antenna */ for (i = 0; i < 3; ++i) { r[i] = -rs[i]; } if (!normv3(r, ezs)) { return; } for (i = 0; i < 3; ++i) { r[i] = rsun[i] - rs[i]; } if (!normv3(r, ess)) { return; } cross3(ezs, ess, r); if (!normv3(r, eys)) { return; } cross3(eys, ezs, exs); /* unit vectors of receiver antenna */ ecef2pos(rr, pos); xyz2enu(pos, E); exr[0] = E[1]; exr[1] = E[4]; exr[2] = E[7]; /* x = north */ eyr[0] = -E[0]; eyr[1] = -E[3]; eyr[2] = -E[6]; /* y = west */ /* phase windup effect */ cross3(ek, eys, eks); cross3(ek, eyr, ekr); for (i = 0; i < 3; ++i) { ds[i] = exs[i] - ek[i] * dot(ek, exs, 3) - eks[i]; dr[i] = exr[i] - ek[i] * dot(ek, exr, 3) + ekr[i]; } cosp = dot(ds, dr, 3) / norm(ds, 3) / norm(dr, 3); if (cosp < -1.0) { cosp = -1.0; } else if (cosp > 1.0) { cosp = 1.0; } ph = acos(cosp) / 2.0 / PI; cross3(ds, dr, drs); if (dot(ek, drs, 3) < 0.0) { ph = -ph; } *phw = ph + floor(*phw - ph + 0.5); /* in cycle */ } /* carrier smoothing ----------------------------------------------------------- * carrier smoothing by Hatch filter * args : obs_t *obs IO raw observation data/smoothed observation data * int ns I smoothing window size (epochs) * return : none *-----------------------------------------------------------------------------*/ extern void csmooth(obs_t* obs, int ns) { double Ps[2][MAXSAT][NFREQ] = {{{0}}}, Lp[2][MAXSAT][NFREQ] = {{{0}}}, dcp; int i, j, s, r, n[2][MAXSAT][NFREQ] = {{{0}}}; obsd_t* p; trace(3, "csmooth: nobs=%d,ns=%d\n", obs->n, ns); for (i = 0; i < obs->n; ++i) { p = &obs->data[i]; s = p->sat; r = p->rcv; for (j = 0; j < NFREQ; ++j) { if (s <= 0 || MAXSAT < s || r <= 0 || 2 < r) { continue; } if (p->P[j] == 0.0 || p->L[j] == 0.0) { continue; } if (p->LLI[j]) { n[r - 1][s - 1][j] = 0; } if (n[r - 1][s - 1][j] == 0) { Ps[r - 1][s - 1][j] = p->P[j]; } else { dcp = lam_carr[j] * (p->L[j] - Lp[r - 1][s - 1][j]); Ps[r - 1][s - 1][j] = p->P[j] / ns + (Ps[r - 1][s - 1][j] + dcp) * (ns - 1) / ns; } if (++n[r - 1][s - 1][j] < ns) { p->P[j] = 0.0; } else { p->P[j] = Ps[r - 1][s - 1][j]; } Lp[r - 1][s - 1][j] = p->L[j]; } } } /* uncompress file ------------------------------------------------------------- * uncompress (uncompress/unzip/uncompact hatanaka-compression/tar) file * args : char *file I input file * char *uncfile O uncompressed file * return : status (-1:error,0:not compressed file,1:uncompress completed) * note : creates uncompressed file in tempolary directory * gzip and crx2rnx commands have to be installed in commands path *-----------------------------------------------------------------------------*/ extern int uncompress(const char* file, char* uncfile) { int stat = 0; char *p, cmd[2048] = "", tmpfile[1024] = "", buff[1024], *fname, *dir = ""; trace(3, "uncompress: file=%s\n", file); strcpy(tmpfile, file); if (!(p = strrchr(tmpfile, '.'))) { return 0; } /* uncompress by gzip */ if (!strcmp(p, ".z") || !strcmp(p, ".Z") || !strcmp(p, ".gz") || !strcmp(p, ".GZ") || !strcmp(p, ".zip") || !strcmp(p, ".ZIP")) { strcpy(uncfile, tmpfile); uncfile[p - tmpfile] = '\0'; sprintf(cmd, "gzip -f -d -c \"%s\" > \"%s\"", tmpfile, uncfile); if (execcmd(cmd)) { remove(uncfile); return -1; } strcpy(tmpfile, uncfile); stat = 1; } /* extract tar file */ if ((p = strrchr(tmpfile, '.')) && !strcmp(p, ".tar")) { strcpy(uncfile, tmpfile); uncfile[p - tmpfile] = '\0'; strcpy(buff, tmpfile); fname = buff; #ifdef WIN32 if ((p = strrchr(buff, '\\'))) { *p = '\0'; dir = fname; fname = p + 1; } sprintf(cmd, "set PATH=%%CD%%;%%PATH%% & cd /D \"%s\" & tar -xf \"%s\"", dir, fname); #else if ((p = strrchr(buff, '/'))) { *p = '\0'; dir = fname; fname = p + 1; } sprintf(cmd, "tar -C \"%s\" -xf \"%s\"", dir, tmpfile); #endif if (execcmd(cmd)) { if (stat) { remove(tmpfile); } return -1; } if (stat) { remove(tmpfile); } stat = 1; } /* extract hatanaka-compressed file by cnx2rnx */ else if ((p = strrchr(tmpfile, '.')) && strlen(p) > 3 && (*(p + 3) == 'd' || *(p + 3) == 'D')) { strcpy(uncfile, tmpfile); uncfile[p - tmpfile + 3] = *(p + 3) == 'D' ? 'O' : 'o'; sprintf(cmd, "crx2rnx < \"%s\" > \"%s\"", tmpfile, uncfile); if (execcmd(cmd)) { remove(uncfile); if (stat) { remove(tmpfile); } return -1; } if (stat) { remove(tmpfile); } stat = 1; } trace(3, "uncompress: stat=%d\n", stat); return stat; } /* dummy application functions for shared library ----------------------------*/ #ifdef DLL extern int showmsg(char* format, ...) { return 0; } extern void settspan(gtime_t ts, gtime_t te) {} extern void settime(gtime_t time) {} #endif /* dummy functions for lex extentions ----------------------------------------*/ #ifndef EXTLEX extern int input_lexr(raw_t* raw, unsigned char data) { return 0; } extern int input_lexrf(raw_t* raw, FILE* fp) { return 0; } extern int gen_lexr(const char* msg, unsigned char* buff) { return 0; } #endif /* EXTLEX */
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/rtklib/rcvraw.c
/********************************************************************************* * The RTKLIB software package is distributed under the following BSD 2-clause * license (http://opensource.org/licenses/BSD-2-Clause) and additional two * exclusive clauses. Users are permitted to develop, produce or sell their own * non-commercial or commercial products utilizing, linking or including RTKLIB *as * long as they comply with the license. * * Copyright (c) 2007-2013, T. Takasu, 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. * * - The software package includes some companion executive binaries or shared * libraries necessary to execute APs on Windows. These licenses succeed to the * original ones of these software. * * 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 HOLDER 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. ***********************************************************************************/ /*------------------------------------------------------------------------------ * rcvraw.c : receiver raw data functions * * Copyright (C) 2009-2014 by T.TAKASU, All rights reserved. * Copyright (C) 2014 by T.SUZUKI, All rights reserved. * * references : * [1] IS-GPS-200D, Navstar GPS Space Segment/Navigation User Interfaces, * 7 March, 2006 * [2] Global navigation satellite system GLONASS interface control document * navigation radiosignal in bands L1,L2 (version 5.1), 2008 * [3] BeiDou satellite navigation system signal in space interface control * document open service signal (version 2.0), December 2013 * [4] Quasi-Zenith Satellite System Navigation Service Interface * Specification for QZSS (IS-QZSS) V.1.5, March 27, 2014 * * version : $Revision: 1.1 $ $Date: 2008/07/17 21:48:06 $ * history : 2009/04/10 1.0 new * 2009/06/02 1.1 support glonass * 2010/07/31 1.2 support eph_t struct change * 2010/12/06 1.3 add almanac decoding, support of GW10 * change api decode_frame() * 2013/04/11 1.4 fix bug on decode fit interval * 2014/01/31 1.5 fix bug on decode fit interval * 2014/06/22 1.6 add api decode_glostr() * 2014/06/22 1.7 add api decode_bds_d1(), decode_bds_d2() * 2014/08/14 1.8 add test_glostr() * add support input format rt17 * 2014/08/31 1.9 suppress warning * 2014/11/07 1.10 support qzss navigation subframes *-----------------------------------------------------------------------------*/ /** * file: rcvraw.c * version: rtklib ver.2.4.2 * Copy from * https://github.com/tomojitakasu/RTKLIB/tree/76b9c97257f304aedad38b5a6bbbac444724aab3/src/rcvraw.c */ #include <stdint.h> #include "rtklib.h" /* static const char rcsid[] = "$Id:$"; */ #define P2_66 1.355252715606881E-20 /* 2^-66 for BeiDou ephemeris */ /* get two component bits ----------------------------------------------------*/ static unsigned int getbitu2(const unsigned char* buff, int p1, int l1, int p2, int l2) { return (getbitu(buff, p1, l1) << l2) + getbitu(buff, p2, l2); } static int getbits2(const unsigned char* buff, int p1, int l1, int p2, int l2) { if (getbitu(buff, p1, 1)) { return (int)((getbits(buff, p1, l1) << l2) + getbitu(buff, p2, l2)); } else { return (int)getbitu2(buff, p1, l1, p2, l2); } } /* get three component bits --------------------------------------------------*/ static unsigned int getbitu3(const unsigned char* buff, int p1, int l1, int p2, int l2, int p3, int l3) { return (getbitu(buff, p1, l1) << (l2 + l3)) + (getbitu(buff, p2, l2) << l3) + getbitu(buff, p3, l3); } static int getbits3(const unsigned char* buff, int p1, int l1, int p2, int l2, int p3, int l3) { if (getbitu(buff, p1, 1)) { return (int)((getbits(buff, p1, l1) << (l2 + l3)) + (getbitu(buff, p2, l2) << l3) + getbitu(buff, p3, l3)); } else { return (int)getbitu3(buff, p1, l1, p2, l2, p3, l3); } } /* merge two components ------------------------------------------------------*/ static unsigned int merge_two_u(unsigned int a, unsigned int b, int n) { return (a << n) + b; } static int merge_two_s(int a, unsigned int b, int n) { return (int)((a << n) + b); } /* get sign-magnitude bits ---------------------------------------------------*/ static double getbitg(const unsigned char* buff, int pos, int len) { double value = getbitu(buff, pos + 1, len - 1); return getbitu(buff, pos, 1) ? -value : value; } /* decode BeiDou D1 ephemeris -------------------------------------------------- * decode BeiDou D1 ephemeris (IGSO/MEO satellites) (ref [3] 5.2) * args : unsigned char *buff I beidou D1 subframe bits * buff[ 0- 37]: subframe 1 (300 bits) * buff[38- 75]: subframe 2 * buff[76-113]: subframe 3 * eph_t *eph IO ephemeris structure * return : status (1:ok,0:error) *-----------------------------------------------------------------------------*/ extern int decode_bds_d1(const unsigned char* buff, eph_t* eph) { double toc_bds = 0.0; double sqrtA = 0.0; unsigned int toe1 = 0; unsigned int toe2 = 0; unsigned int sow1 = 0; unsigned int sow2 = 0; unsigned int sow3 = 0; int i = 0; int frn1 = 0; int frn2 = 0; int frn3 = 0; trace(3, "decode_bds_d1:\n"); i = 8 * 38 * 0; /* subframe 1 */ frn1 = getbitu(buff, i + 15, 3); sow1 = getbitu2(buff, i + 18, 8, i + 30, 12); eph->svh = getbitu(buff, i + 42, 1); /* SatH1 */ eph->iodc = getbitu(buff, i + 43, 5); /* AODC */ eph->sva = getbitu(buff, i + 48, 4); eph->week = getbitu(buff, i + 60, 13); /* week in BDT */ toc_bds = getbitu2(buff, i + 73, 9, i + 90, 8) * 8.0; eph->tgd[0] = getbits(buff, i + 98, 10) * 0.1 * 1E-9; eph->tgd[1] = getbits2(buff, i + 108, 4, i + 120, 6) * 0.1 * 1E-9; eph->f2 = getbits(buff, i + 214, 11) * P2_66; eph->f0 = getbits2(buff, i + 225, 7, i + 240, 17) * P2_33; eph->f1 = getbits2(buff, i + 257, 5, i + 270, 17) * P2_50; eph->iode = getbitu(buff, i + 287, 5); /* AODE */ i = 8 * 38 * 1; /* subframe 2 */ frn2 = getbitu(buff, i + 15, 3); sow2 = getbitu2(buff, i + 18, 8, i + 30, 12); eph->deln = getbits2(buff, i + 42, 10, i + 60, 6) * P2_43 * SC2RAD; eph->cuc = getbits2(buff, i + 66, 16, i + 90, 2) * P2_31; eph->M0 = getbits2(buff, i + 92, 20, i + 120, 12) * P2_31 * SC2RAD; eph->e = getbitu2(buff, i + 132, 10, i + 150, 22) * P2_33; eph->cus = getbits(buff, i + 180, 18) * P2_31; eph->crc = getbits2(buff, i + 198, 4, i + 210, 14) * P2_6; eph->crs = getbits2(buff, i + 224, 8, i + 240, 10) * P2_6; sqrtA = getbitu2(buff, i + 250, 12, i + 270, 20) * P2_19; toe1 = getbitu(buff, i + 290, 2); /* TOE 2-MSB */ eph->A = sqrtA * sqrtA; i = 8 * 38 * 2; /* subframe 3 */ frn3 = getbitu(buff, i + 15, 3); sow3 = getbitu2(buff, i + 18, 8, i + 30, 12); toe2 = getbitu2(buff, i + 42, 10, i + 60, 5); /* TOE 5-LSB */ eph->i0 = getbits2(buff, i + 65, 17, i + 90, 15) * P2_31 * SC2RAD; eph->cic = getbits2(buff, i + 105, 7, i + 120, 11) * P2_31; eph->OMGd = getbits2(buff, i + 131, 11, i + 150, 13) * P2_43 * SC2RAD; eph->cis = getbits2(buff, i + 163, 9, i + 180, 9) * P2_31; eph->idot = getbits2(buff, i + 189, 13, i + 210, 1) * P2_43 * SC2RAD; eph->OMG0 = getbits2(buff, i + 211, 21, i + 240, 11) * P2_31 * SC2RAD; eph->omg = getbits2(buff, i + 251, 11, i + 270, 21) * P2_31 * SC2RAD; eph->toes = merge_two_u(toe1, toe2, 15) * 8.0; /* check consistency of subframe numbers, sows and toe/toc */ if (frn1 != 1 || frn2 != 2 || frn3 != 3) { trace(3, "decode_bds_d1 error: frn=%d %d %d\n", frn1, frn2, frn3); return 0; } if (sow2 != sow1 + 6 || sow3 != sow2 + 6) { trace(3, "decode_bds_d1 error: sow=%d %d %d\n", sow1, sow2, sow3); return 0; } if (toc_bds != eph->toes) { trace(3, "decode_bds_d1 error: toe=%.0f toc=%.0f\n", eph->toes, toc_bds); return 0; } eph->ttr = bdt2gpst(bdt2time(eph->week, sow1)); /* bdt -> gpst */ if (eph->toes > sow1 + 302400.0) { eph->week++; } else if (eph->toes < sow1 - 302400.0) { eph->week--; } eph->toe = bdt2gpst(bdt2time(eph->week, eph->toes)); /* bdt -> gpst */ eph->toc = bdt2gpst(bdt2time(eph->week, toc_bds)); /* bdt -> gpst */ return 1; } /* decode BeiDou D2 ephemeris -------------------------------------------------- * decode BeiDou D2 ephemeris (GEO satellites) (ref [3] 5.3) * args : unsigned char *buff I beidou D2 subframe 1 page bits * buff[ 0- 37]: page 1 (300 bits) * buff[ 38- 75]: page 2 * ... * buff[342-379]: page 10 * eph_t *eph IO ephemeris structure * return : status (1:ok,0:error) *-----------------------------------------------------------------------------*/ extern int decode_bds_d2(const unsigned char* buff, eph_t* eph) { double toc_bds = 0.0; double sqrtA = 0.0; unsigned int f1p4 = 0; unsigned int cucp5 = 0; unsigned int ep6 = 0; unsigned int cicp7 = 0; unsigned int i0p8 = 0; unsigned int OMGdp9 = 0; unsigned int omgp10 = 0; unsigned int sow1 = 0; unsigned int sow3 = 0; unsigned int sow4 = 0; unsigned int sow5 = 0; unsigned int sow6 = 0; unsigned int sow7 = 0; unsigned int sow8 = 0; unsigned int sow9 = 0; unsigned int sow10 = 0; int i = 0; int f1p3 = 0; int cucp4 = 0; int ep5 = 0; int cicp6 = 0; int i0p7 = 0; int OMGdp8 = 0; int omgp9 = 0; int pgn1 = 0; int pgn3 = 0; int pgn4 = 0; int pgn5 = 0; int pgn6 = 0; int pgn7 = 0; int pgn8 = 0; int pgn9 = 0; int pgn10 = 0; trace(3, "decode_bds_d2:\n"); i = 8 * 38 * 0; /* page 1 */ pgn1 = getbitu(buff, i + 42, 4); sow1 = getbitu2(buff, i + 18, 8, i + 30, 12); eph->svh = getbitu(buff, i + 46, 1); /* SatH1 */ eph->iodc = getbitu(buff, i + 47, 5); /* AODC */ eph->sva = getbitu(buff, i + 60, 4); eph->week = getbitu(buff, i + 64, 13); /* week in BDT */ toc_bds = getbitu2(buff, i + 77, 5, i + 90, 12) * 8.0; eph->tgd[0] = getbits(buff, i + 102, 10) * 0.1 * 1E-9; eph->tgd[1] = getbits(buff, i + 120, 10) * 0.1 * 1E-9; i = 8 * 38 * 2; /* page 3 */ pgn3 = getbitu(buff, i + 42, 4); sow3 = getbitu2(buff, i + 18, 8, i + 30, 12); eph->f0 = getbits2(buff, i + 100, 12, i + 120, 12) * P2_33; f1p3 = getbits(buff, i + 132, 4); i = 8 * 38 * 3; /* page 4 */ pgn4 = getbitu(buff, i + 42, 4); sow4 = getbitu2(buff, i + 18, 8, i + 30, 12); f1p4 = getbitu2(buff, i + 46, 6, i + 60, 12); eph->f2 = getbits2(buff, i + 72, 10, i + 90, 1) * P2_66; eph->iode = getbitu(buff, i + 91, 5); /* AODE */ eph->deln = getbits(buff, i + 96, 16) * P2_43 * SC2RAD; cucp4 = getbits(buff, i + 120, 14); i = 8 * 38 * 4; /* page 5 */ pgn5 = getbitu(buff, i + 42, 4); sow5 = getbitu2(buff, i + 18, 8, i + 30, 12); cucp5 = getbitu(buff, i + 46, 4); eph->M0 = getbits3(buff, i + 50, 2, i + 60, 22, i + 90, 8) * P2_31 * SC2RAD; eph->cus = getbits2(buff, i + 98, 14, i + 120, 4) * P2_31; ep5 = getbits(buff, i + 124, 10); i = 8 * 38 * 5; /* page 6 */ pgn6 = getbitu(buff, i + 42, 4); sow6 = getbitu2(buff, i + 18, 8, i + 30, 12); ep6 = getbitu2(buff, i + 46, 6, i + 60, 16); sqrtA = getbitu3(buff, i + 76, 6, i + 90, 22, i + 120, 4) * P2_19; cicp6 = getbits(buff, i + 124, 10); eph->A = sqrtA * sqrtA; i = 8 * 38 * 6; /* page 7 */ pgn7 = getbitu(buff, i + 42, 4); sow7 = getbitu2(buff, i + 18, 8, i + 30, 12); cicp7 = getbitu2(buff, i + 46, 6, i + 60, 2); eph->cis = getbits(buff, i + 62, 18) * P2_31; eph->toes = getbitu2(buff, i + 80, 2, i + 90, 15) * 8.0; i0p7 = getbits2(buff, i + 105, 7, i + 120, 14); i = 8 * 38 * 7; /* page 8 */ pgn8 = getbitu(buff, i + 42, 4); sow8 = getbitu2(buff, i + 18, 8, i + 30, 12); i0p8 = getbitu2(buff, i + 46, 6, i + 60, 5); eph->crc = getbits2(buff, i + 65, 17, i + 90, 1) * P2_6; eph->crs = getbits(buff, i + 91, 18) * P2_6; OMGdp8 = getbits2(buff, i + 109, 3, i + 120, 16); i = 8 * 38 * 8; /* page 9 */ pgn9 = getbitu(buff, i + 42, 4); sow9 = getbitu2(buff, i + 18, 8, i + 30, 12); OMGdp9 = getbitu(buff, i + 46, 5); eph->OMG0 = getbits3(buff, i + 51, 1, i + 60, 22, i + 90, 9) * P2_31 * SC2RAD; omgp9 = getbits2(buff, i + 99, 13, i + 120, 14); i = 8 * 38 * 9; /* page 10 */ pgn10 = getbitu(buff, i + 42, 4); sow10 = getbitu2(buff, i + 18, 8, i + 30, 12); omgp10 = getbitu(buff, i + 46, 5); eph->idot = getbits2(buff, i + 51, 1, i + 60, 13) * P2_43 * SC2RAD; /* check consistency of page numbers, sows and toe/toc */ if (pgn1 != 1 || pgn3 != 3 || pgn4 != 4 || pgn5 != 5 || pgn6 != 6 || pgn7 != 7 || pgn8 != 8 || pgn9 != 9 || pgn10 != 10) { trace(3, "decode_bds_d2 error: pgn=%d %d %d %d %d %d %d %d %d\n", pgn1, pgn3, pgn4, pgn5, pgn6, pgn7, pgn8, pgn9, pgn10); return 0; } if (sow3 != sow1 + 6 || sow4 != sow3 + 3 || sow5 != sow4 + 3 || sow6 != sow5 + 3 || sow7 != sow6 + 3 || sow8 != sow7 + 3 || sow9 != sow8 + 3 || sow10 != sow9 + 3) { trace(3, "decode_bds_d2 error: sow=%d %d %d %d %d %d %d %d %d\n", sow1, sow3, sow4, sow5, sow6, sow7, sow8, sow9, sow10); return 0; } if (toc_bds != eph->toes) { trace(3, "decode_bds_d2 error: toe=%.0f toc=%.0f\n", eph->toes, toc_bds); return 0; } eph->f1 = merge_two_s(f1p3, f1p4, 18) * P2_50; eph->cuc = merge_two_s(cucp4, cucp5, 4) * P2_31; eph->e = merge_two_s(ep5, ep6, 22) * P2_33; eph->cic = merge_two_s(cicp6, cicp7, 8) * P2_31; eph->i0 = merge_two_s(i0p7, i0p8, 11) * P2_31 * SC2RAD; eph->OMGd = merge_two_s(OMGdp8, OMGdp9, 5) * P2_43 * SC2RAD; eph->omg = merge_two_s(omgp9, omgp10, 5) * P2_31 * SC2RAD; eph->ttr = bdt2gpst(bdt2time(eph->week, sow1)); /* bdt -> gpst */ if (eph->toes > sow1 + 302400.0) { eph->week++; } else if (eph->toes < sow1 - 302400.0) { eph->week--; } eph->toe = bdt2gpst(bdt2time(eph->week, eph->toes)); /* bdt -> gpst */ eph->toc = bdt2gpst(bdt2time(eph->week, toc_bds)); /* bdt -> gpst */ return 1; } /* test hamming code of glonass ephemeris string ------------------------------- * test hamming code of glonass ephemeris string (ref [2] 4.7) * args : unsigned char *buff I glonass navigation data string bits in frame * with hamming * buff[ 0]: string bit 85-78 * buff[ 1]: string bit 77-70 * ... * buff[10]: string bit 5- 1 (0 padded) * return : status (1:ok,0:error) *-----------------------------------------------------------------------------*/ extern int test_glostr(const unsigned char* buff) { static const unsigned char xor_8bit[256] = { /* xor of 8 bits */ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }; static const unsigned char mask_hamming[][12] = { /* mask of hamming codes */ {0x55, 0x55, 0x5A, 0xAA, 0xAA, 0xAA, 0xB5, 0x55, 0x6A, 0xD8, 0x08}, {0x66, 0x66, 0x6C, 0xCC, 0xCC, 0xCC, 0xD9, 0x99, 0xB3, 0x68, 0x10}, {0x87, 0x87, 0x8F, 0x0F, 0x0F, 0x0F, 0x1E, 0x1E, 0x3C, 0x70, 0x20}, {0x07, 0xF8, 0x0F, 0xF0, 0x0F, 0xF0, 0x1F, 0xE0, 0x3F, 0x80, 0x40}, {0xF8, 0x00, 0x0F, 0xFF, 0xF0, 0x00, 0x1F, 0xFF, 0xC0, 0x00, 0x80}, {0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x01, 0x00}, {0xFF, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00}, {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF8} }; unsigned char cs = 0; int i = 0; int j = 0; int n = 0; for (i = 0; i < 8; ++i) { for (j = 0, cs = 0; j < 11; ++j) { cs ^= xor_8bit[buff[j] & mask_hamming[i][j]]; } if (cs) { n++; } } return n == 0 || (n == 2 && cs); } /* decode glonass ephemeris strings -------------------------------------------- * decode glonass ephemeris string (ref [2]) * args : unsigned char *buff I glonass navigation data string bits in frames * (without hamming and time mark) * buff[ 0- 9]: string #1 (77 bits) * buff[10-19]: string #2 * buff[20-29]: string #3 * buff[30-39]: string #4 * geph_t *geph IO glonass ephemeris message * return : status (1:ok,0:error) * notes : geph->tof should be set to frame time witin 1/2 day before calling * geph->frq is set to 0 *-----------------------------------------------------------------------------*/ extern int decode_glostr(const unsigned char* buff, geph_t* geph) { double tow = 0.0; double tod = 0.0; double tof = 0.0; double toe = 0.0; // int P = 0; // int P1 = 0; // int P2 = 0; // int P3 = 0; // int P4 = 0; int tk_h = 0; int tk_m = 0; int tk_s = 0; int tb = 0; int slot = 0; int week = 0; int i = 1; int frn1 = 0; int frn2 = 0; int frn3 = 0; int frn4 = 0; trace(3, "decode_glostr:\n"); /* frame 1 */ frn1 = getbitu(buff, i, 4); i += 4 + 2; //P1 = getbitu(buff, i, 2); getbitu(buff, i, 2); i += 2; tk_h = getbitu(buff, i, 5); i += 5; tk_m = getbitu(buff, i, 6); i += 6; tk_s = getbitu(buff, i, 1) * 30; i += 1; geph->vel[0] = getbitg(buff, i, 24) * P2_20 * 1E3; i += 24; geph->acc[0] = getbitg(buff, i, 5) * P2_30 * 1E3; i += 5; geph->pos[0] = getbitg(buff, i, 27) * P2_11 * 1E3; i += 27 + 4; /* frame 2 */ frn2 = getbitu(buff, i, 4); i += 4; geph->svh = getbitu(buff, i, 3); i += 3; //P2 = getbitu(buff, i, 1); getbitu(buff, i, 1); i += 1; tb = getbitu(buff, i, 7); i += 7 + 5; geph->vel[1] = getbitg(buff, i, 24) * P2_20 * 1E3; i += 24; geph->acc[1] = getbitg(buff, i, 5) * P2_30 * 1E3; i += 5; geph->pos[1] = getbitg(buff, i, 27) * P2_11 * 1E3; i += 27 + 4; /* frame 3 */ frn3 = getbitu(buff, i, 4); i += 4; //P3 = getbitu(buff, i, 1); getbitu(buff, i, 1); i += 1; geph->gamn = getbitg(buff, i, 11) * P2_40; i += 11 + 1; //P = getbitu(buff, i, 2); getbitu(buff, i, 2); i += 2; //int ln = getbitu(buff, i, 1); getbitu(buff, i, 1); i += 1; geph->vel[2] = getbitg(buff, i, 24) * P2_20 * 1E3; i += 24; geph->acc[2] = getbitg(buff, i, 5) * P2_30 * 1E3; i += 5; geph->pos[2] = getbitg(buff, i, 27) * P2_11 * 1E3; i += 27 + 4; /* frame 4 */ frn4 = getbitu(buff, i, 4); i += 4; geph->taun = getbitg(buff, i, 22) * P2_30; i += 22; geph->dtaun = getbitg(buff, i, 5) * P2_30; i += 5; geph->age = getbitu(buff, i, 5); i += 5 + 14; //P4 = getbitu(buff, i, 1); getbitu(buff, i, 1); i += 1; geph->sva = getbitu(buff, i, 4); i += 4 + 3; //int NT = getbitu(buff, i, 11); getbitu(buff, i, 11); i += 11; slot = getbitu(buff, i, 5); i += 5; //int M = getbitu(buff, i, 2); getbitu(buff, i, 2); if (frn1 != 1 || frn2 != 2 || frn3 != 3 || frn4 != 4) { trace(3, "decode_glostr error: frn=%d %d %d %d %d\n", frn1, frn2, frn3, frn4); return 0; } if (!(geph->sat = satno(SYS_GLO, slot))) { trace(2, "decode_glostr error: slot=%d\n", slot); return 0; } geph->frq = 0; geph->iode = tb; tow = time2gpst(gpst2utc(geph->tof), &week); tod = fmod(tow, 86400.0); tow -= tod; tof = tk_h * 3600.0 + tk_m * 60.0 + tk_s - 10800.0; /* lt->utc */ if (tof < tod - 43200.0) { tof += 86400.0; } else if (tof > tod + 43200.0) { tof -= 86400.0; } geph->tof = utc2gpst(gpst2time(week, tow + tof)); toe = tb * 900.0 - 10800.0; /* lt->utc */ if (toe < tod - 43200.0) { toe += 86400.0; } else if (toe > tod + 43200.0) { toe -= 86400.0; } geph->toe = utc2gpst(gpst2time(week, tow + toe)); /* utc->gpst */ return 1; } /* decode gps/qzss navigation data subframe 1 --------------------------------*/ static int decode_subfrm1(const unsigned char* buff, eph_t* eph) { double tow = 0.0; double toc = 0.0; int i = 48; int week = 0; int iodc0 = 0; int iodc1 = 0; int tgd = 0; trace(4, "decode_subfrm1:\n"); trace(5, "decode_subfrm1: buff="); traceb(5, buff, 30); tow = getbitu(buff, 24, 17) * 6.0; /* transmission time */ week = getbitu(buff, i, 10); i += 10; eph->code = getbitu(buff, i, 2); i += 2; eph->sva = getbitu(buff, i, 4); i += 4; /* ura index */ eph->svh = getbitu(buff, i, 6); i += 6; iodc0 = getbitu(buff, i, 2); i += 2; eph->flag = getbitu(buff, i, 1); i += 1 + 87; tgd = getbits(buff, i, 8); i += 8; iodc1 = getbitu(buff, i, 8); i += 8; toc = getbitu(buff, i, 16) * 16.0; i += 16; eph->f2 = getbits(buff, i, 8) * P2_55; i += 8; eph->f1 = getbits(buff, i, 16) * P2_43; i += 16; eph->f0 = getbits(buff, i, 22) * P2_31; eph->tgd[0] = tgd == -128 ? 0.0 : tgd * P2_31; /* ref [4] */ eph->iodc = (iodc0 << 8) + iodc1; eph->week = adjgpsweek(week); /* week of tow */ eph->ttr = gpst2time(eph->week, tow); eph->toc = gpst2time(eph->week, toc); return 1; } /* decode gps/qzss navigation data subframe 2 --------------------------------*/ static int decode_subfrm2(const unsigned char* buff, eph_t* eph) { double sqrtA = 0.0; int i = 48; trace(4, "decode_subfrm2:\n"); trace(5, "decode_subfrm2: buff="); traceb(5, buff, 30); eph->iode = getbitu(buff, i, 8); i += 8; eph->crs = getbits(buff, i, 16) * P2_5; i += 16; eph->deln = getbits(buff, i, 16) * P2_43 * SC2RAD; i += 16; eph->M0 = getbits(buff, i, 32) * P2_31 * SC2RAD; i += 32; eph->cuc = getbits(buff, i, 16) * P2_29; i += 16; eph->e = getbitu(buff, i, 32) * P2_33; i += 32; eph->cus = getbits(buff, i, 16) * P2_29; i += 16; sqrtA = getbitu(buff, i, 32) * P2_19; i += 32; eph->toes = getbitu(buff, i, 16) * 16.0; i += 16; eph->fit = getbitu(buff, i, 1) ? 0.0 : 4.0; /* 0:4hr,1:>4hr */ eph->A = sqrtA * sqrtA; return 2; } /* decode gps/qzss navigation data subframe 3 --------------------------------*/ static int decode_subfrm3(const unsigned char* buff, eph_t* eph) { double tow = 0.0; double toc = 0.0; int i = 48; int iode = 0; trace(4, "decode_subfrm3:\n"); trace(5, "decode_subfrm3: buff="); traceb(5, buff, 30); eph->cic = getbits(buff, i, 16) * P2_29; i += 16; eph->OMG0 = getbits(buff, i, 32) * P2_31 * SC2RAD; i += 32; eph->cis = getbits(buff, i, 16) * P2_29; i += 16; eph->i0 = getbits(buff, i, 32) * P2_31 * SC2RAD; i += 32; eph->crc = getbits(buff, i, 16) * P2_5; i += 16; eph->omg = getbits(buff, i, 32) * P2_31 * SC2RAD; i += 32; eph->OMGd = getbits(buff, i, 24) * P2_43 * SC2RAD; i += 24; iode = getbitu(buff, i, 8); i += 8; eph->idot = getbits(buff, i, 14) * P2_43 * SC2RAD; /* check iode and iodc consistency */ if (iode != eph->iode || iode != (eph->iodc & 0xFF)) { return 0; } /* adjustment for week handover */ tow = time2gpst(eph->ttr, &eph->week); toc = time2gpst(eph->toc, NULL); if (eph->toes < tow - 302400.0) { eph->week++; tow -= 604800.0; } else if (eph->toes > tow + 302400.0) { eph->week--; tow += 604800.0; } eph->toe = gpst2time(eph->week, eph->toes); eph->toc = gpst2time(eph->week, toc); eph->ttr = gpst2time(eph->week, tow); return 3; } /* decode gps/qzss almanac ---------------------------------------------------*/ static void decode_almanac(const unsigned char* buff, int sat, alm_t* alm) { gtime_t toa; double deltai = 0.0; double sqrtA = 0.0; double tt = 0.0; int i = 50; int f0 = 0; trace(4, "decode_almanac: sat=%2d\n", sat); if (!alm || alm[sat - 1].week == 0) { return; } alm[sat - 1].sat = sat; alm[sat - 1].e = getbits(buff, i, 16) * P2_21; i += 16; alm[sat - 1].toas = getbitu(buff, i, 8) * 4096.0; i += 8; deltai = getbits(buff, i, 16) * P2_19 * SC2RAD; i += 16; alm[sat - 1].OMGd = getbits(buff, i, 16) * P2_38 * SC2RAD; i += 16; alm[sat - 1].svh = getbitu(buff, i, 8); i += 8; sqrtA = getbitu(buff, i, 24) * P2_11; i += 24; alm[sat - 1].OMG0 = getbits(buff, i, 24) * P2_23 * SC2RAD; i += 24; alm[sat - 1].omg = getbits(buff, i, 24) * P2_23 * SC2RAD; i += 24; alm[sat - 1].M0 = getbits(buff, i, 24) * P2_23 * SC2RAD; i += 24; f0 = getbitu(buff, i, 8); i += 8; alm[sat - 1].f1 = getbits(buff, i, 11) * P2_38; i += 11; alm[sat - 1].f0 = getbits(buff, i, 3) * P2_17 + f0 * P2_20; alm[sat - 1].A = sqrtA * sqrtA; alm[sat - 1].i0 = 0.3 * SC2RAD + deltai; toa = gpst2time(alm[sat - 1].week, alm[sat - 1].toas); tt = timediff(toa, alm[sat - 1].toa); if (tt < 302400.0) { alm[sat - 1].week--; } else if (tt > 302400.0) { alm[sat - 1].week++; } alm[sat - 1].toa = gpst2time(alm[sat - 1].week, alm[sat - 1].toas); } /* decode gps navigation data subframe 4 -------------------------------------*/ static void decode_gps_subfrm4(const unsigned char* buff, alm_t* alm, double* ion, double* utc, int* leaps) { int i = 0; int sat = 0; int svid = getbitu(buff, 50, 6); if (25 <= svid && svid <= 32) { /* page 2,3,4,5,7,8,9,10 */ /* decode almanac */ sat = getbitu(buff, 50, 6); if (1 <= sat && sat <= 32) { decode_almanac(buff, sat, alm); } } else if (svid == 63) { /* page 25 */ /* decode as and sv config */ i = 56; for (sat = 1; sat <= 32; sat++) { if (alm) { alm[sat - 1].svconf = getbitu(buff, i, 4); } i += 4; } /* decode sv health */ i = 186; for (sat = 25; sat <= 32; sat++) { if (alm) { alm[sat - 1].svh = getbitu(buff, i, 6); } i += 6; } } else if (svid == 56) { /* page 18 */ /* decode ion/utc parameters */ if (ion) { i = 56; ion[0] = getbits(buff, i, 8) * P2_30; i += 8; ion[1] = getbits(buff, i, 8) * P2_27; i += 8; ion[2] = getbits(buff, i, 8) * P2_24; i += 8; ion[3] = getbits(buff, i, 8) * P2_24; i += 8; ion[4] = getbits(buff, i, 8) * pow(2, 11); i += 8; ion[5] = getbits(buff, i, 8) * pow(2, 14); i += 8; ion[6] = getbits(buff, i, 8) * pow(2, 16); i += 8; ion[7] = getbits(buff, i, 8) * pow(2, 16); } if (utc) { i = 120; utc[1] = getbits(buff, i, 24) * P2_50; i += 24; utc[0] = getbits(buff, i, 32) * P2_30; i += 32; utc[2] = getbits(buff, i, 8) * pow(2, 12); i += 8; utc[3] = getbitu(buff, i, 8); } if (leaps) { i = 192; *leaps = getbits(buff, i, 8); } } } /* decode gps navigation data subframe 5 -------------------------------------*/ static void decode_gps_subfrm5(const unsigned char* buff, alm_t* alm) { double toas = 0.0; int i = 0; int sat = 0; int week = 0; int svid = getbitu(buff, 50, 6); if (1 <= svid && svid <= 24) { /* page 1-24 */ /* decode almanac */ sat = getbitu(buff, 50, 6); if (1 <= sat && sat <= 32) { decode_almanac(buff, sat, alm); } } else if (svid == 51) { /* page 25 */ if (alm) { i = 56; toas = getbitu(buff, i, 8) * 4096; i += 8; week = getbitu(buff, i, 8); i += 8; week = adjgpsweek(week); /* decode sv health */ for (sat = 1; sat <= 24; sat++) { alm[sat - 1].svh = getbitu(buff, i, 6); i += 6; } for (sat = 1; sat <= 32; sat++) { alm[sat - 1].toas = toas; alm[sat - 1].week = week; alm[sat - 1].toa = gpst2time(week, toas); } } } } /* decode qzss navigation data subframe 4/5 ----------------------------------*/ static void decode_qzs_subfrm45(const unsigned char* buff, alm_t* alm, double* ion, double* utc, int* leaps) { int i = 0; int j = 0; int sat = 0; int toas = 0; int week = 0; int svid = getbitu(buff, 50, 6); if (1 <= svid && svid <= 5) { /* qzss almanac */ if (!(sat = satno(SYS_QZS, 192 + svid))) { return; } decode_almanac(buff, sat, alm); } else if (svid == 51) { /* qzss health */ if (alm) { i = 56; toas = getbitu(buff, i, 8) * 4096; i += 8; week = getbitu(buff, i, 8); i += 8; week = adjgpsweek(week); for (j = 0; j < 5; ++j) { if (!(sat = satno(SYS_QZS, 193 + j))) { continue; } alm[sat - 1].toas = toas; alm[sat - 1].week = week; alm[sat - 1].toa = gpst2time(week, toas); alm[sat - 1].svh = getbitu(buff, i, 6); i += 6; } } } else if (svid == 56) { /* ion/utc parameters */ if (ion) { i = 56; ion[0] = getbits(buff, i, 8) * P2_30; i += 8; ion[1] = getbits(buff, i, 8) * P2_27; i += 8; ion[2] = getbits(buff, i, 8) * P2_24; i += 8; ion[3] = getbits(buff, i, 8) * P2_24; i += 8; ion[4] = getbits(buff, i, 8) * pow(2, 11); i += 8; ion[5] = getbits(buff, i, 8) * pow(2, 14); i += 8; ion[6] = getbits(buff, i, 8) * pow(2, 16); i += 8; ion[7] = getbits(buff, i, 8) * pow(2, 16); } if (utc) { i = 120; utc[1] = getbits(buff, i, 24) * P2_50; i += 24; utc[0] = getbits(buff, i, 32) * P2_30; i += 32; utc[2] = getbits(buff, i, 8) * pow(2, 12); i += 8; utc[3] = getbitu(buff, i, 8); } } } /* decode gps/qzss navigation data subframe 4 --------------------------------*/ static int decode_subfrm4(const unsigned char* buff, alm_t* alm, double* ion, double* utc, int* leaps) { int dataid = getbitu(buff, 48, 2); trace(4, "decode_subfrm4: dataid=%d\n", dataid); trace(5, "decode_subfrm4: buff="); traceb(5, buff, 30); if (dataid == 1) { /* gps */ decode_gps_subfrm4(buff, alm, ion, utc, leaps); } else if (dataid == 3) { /* qzss */ decode_qzs_subfrm45(buff, alm, ion, utc, leaps); } return 4; } /* decode gps/qzss navigation data subframe 5 --------------------------------*/ static int decode_subfrm5(const unsigned char* buff, alm_t* alm, double* ion, double* utc, int* leaps) { int dataid = getbitu(buff, 48, 2); trace(4, "decode_subfrm5: dataid=%d\n", dataid); trace(5, "decode_subfrm5: buff="); traceb(5, buff, 30); if (dataid == 1) { /* gps */ decode_gps_subfrm5(buff, alm); } else if (dataid == 3) { /* qzss */ decode_qzs_subfrm45(buff, alm, ion, utc, leaps); } return 5; } /* decode gps/qzss navigation data frame --------------------------------------- * decode navigation data frame and extract ephemeris and ion/utc parameters * args : unsigned char *buff I gps navigation data frame (without parity) * buff[0-29]: 24 bits x 10 words * eph_t *eph IO ephemeris message (NULL: no input) * alm_t *alm IO almanac (NULL: no input) * double *ion IO ionospheric parameters (NULL: no input) * double *utc IO delta-utc parameters (NULL: no input) * int *leaps IO leap seconds (s) (NULL: no input) * return : status (0:no valid, 1-5:subframe id) * notes : use cpu time to resolve modulo 1024 ambiguity of the week number * see ref [1] * utc[3] reference week for utc parameter is truncated in 8 bits * ion and utc parameters by qzss indicate local iono and qzst-utc * parameters. *-----------------------------------------------------------------------------*/ extern int decode_frame(const unsigned char* buff, eph_t* eph, alm_t* alm, double* ion, double* utc, int* leaps) { int id = getbitu(buff, 43, 3); /* subframe id */ trace(3, "decodefrm: id=%d\n", id); switch (id) { case 1: return decode_subfrm1(buff, eph); case 2: return decode_subfrm2(buff, eph); case 3: return decode_subfrm3(buff, eph); case 4: return decode_subfrm4(buff, alm, ion, utc, leaps); case 5: return decode_subfrm5(buff, alm, ion, utc, leaps); } return 0; } /* initialize receiver raw data control ---------------------------------------- * initialize receiver raw data control struct and reallocate obsevation and * epheris buffer * args : raw_t *raw IO receiver raw data control struct * return : status (1:ok,0:memory allocation error) *-----------------------------------------------------------------------------*/ extern int init_raw(raw_t* raw) { const double lam_glo[NFREQ] = {CLIGHT / FREQ1_GLO, CLIGHT / FREQ2_GLO}; gtime_t time0 = {0}; obsd_t data0 = {{0}}; eph_t eph0 = {0, -1, -1}; alm_t alm0 = {0, -1}; geph_t geph0 = {0, -1}; seph_t seph0 = {0}; sbsmsg_t sbsmsg0 = {0}; lexmsg_t lexmsg0 = {0}; int i = 0; int j = 0; int sys = 0; trace(3, "init_raw:\n"); raw->time = raw->tobs = time0; raw->ephsat = 0; raw->sbsmsg = sbsmsg0; raw->msgtype[0] = '\0'; for (i = 0; i < MAXSAT; ++i) { for (j = 0; j < 380; ++j) { raw->subfrm[i][j] = 0; } for (j = 0; j < NFREQ; ++j) { raw->lockt[i][j] = 0.0; } for (j = 0; j < NFREQ; ++j) { raw->halfc[i][j] = 0; } raw->icpp[i] = raw->off[i] = raw->prCA[i] = raw->dpCA[i] = 0.0; } for (i = 0; i < MAXOBS; ++i) { raw->freqn[i] = 0; } raw->lexmsg = lexmsg0; raw->icpc = 0.0; raw->nbyte = raw->len = 0; raw->iod = raw->flag = raw->tbase = raw->outtype = 0; raw->tod = -1; for (i = 0; i < MAXRAWLEN; ++i) { raw->buff[i] = 0; } raw->opt[0] = '\0'; raw->receive_time = 0.0; raw->plen = raw->pbyte = raw->page = raw->reply = 0; raw->week = 0; raw->obs.data = NULL; raw->obuf.data = NULL; raw->nav.eph = NULL; raw->nav.alm = NULL; raw->nav.geph = NULL; raw->nav.seph = NULL; if (!(raw->obs.data = (obsd_t*)malloc(sizeof(obsd_t) * MAXOBS)) || !(raw->obuf.data = (obsd_t*)malloc(sizeof(obsd_t) * MAXOBS)) || !(raw->nav.eph = (eph_t*)malloc(sizeof(eph_t) * MAXSAT)) || !(raw->nav.alm = (alm_t*)malloc(sizeof(alm_t) * MAXSAT)) || !(raw->nav.geph = (geph_t*)malloc(sizeof(geph_t) * NSATGLO)) || !(raw->nav.seph = (seph_t*)malloc(sizeof(seph_t) * NSATSBS * 2))) { free_raw(raw); return 0; } raw->obs.n = 0; raw->obuf.n = 0; raw->nav.n = MAXSAT; raw->nav.na = MAXSAT; raw->nav.ng = NSATGLO; raw->nav.ns = NSATSBS * 2; for (i = 0; i < MAXOBS; ++i) { raw->obs.data[i] = data0; } for (i = 0; i < MAXOBS; ++i) { raw->obuf.data[i] = data0; } for (i = 0; i < MAXSAT; ++i) { raw->nav.eph[i] = eph0; } for (i = 0; i < MAXSAT; ++i) { raw->nav.alm[i] = alm0; } for (i = 0; i < NSATGLO; ++i) { raw->nav.geph[i] = geph0; } for (i = 0; i < NSATSBS * 2; ++i) { raw->nav.seph[i] = seph0; } for (i = 0; i < MAXSAT; ++i) { for (j = 0; j < NFREQ; ++j) { if (!(sys = satsys(i + 1, NULL))) { continue; } raw->nav.lam[i][j] = sys == SYS_GLO ? lam_glo[j] : lam_carr[j]; } } raw->sta.name[0] = raw->sta.marker[0] = '\0'; raw->sta.antdes[0] = raw->sta.antsno[0] = '\0'; raw->sta.rectype[0] = raw->sta.recver[0] = raw->sta.recsno[0] = '\0'; raw->sta.antsetup = raw->sta.itrf = raw->sta.deltype = 0; for (i = 0; i < 3; ++i) { raw->sta.pos[i] = raw->sta.del[i] = 0.0; } raw->sta.hgt = 0.0; return 1; } /* free receiver raw data control ---------------------------------------------- * free observation and ephemeris buffer in receiver raw data control struct * args : raw_t *raw IO receiver raw data control struct * return : none *-----------------------------------------------------------------------------*/ extern void free_raw(raw_t* raw) { trace(3, "free_raw:\n"); free(raw->obs.data); raw->obs.data = NULL; raw->obs.n = 0; free(raw->obuf.data); raw->obuf.data = NULL; raw->obuf.n = 0; free(raw->nav.eph); raw->nav.eph = NULL; raw->nav.n = 0; free(raw->nav.alm); raw->nav.alm = NULL; raw->nav.na = 0; free(raw->nav.geph); raw->nav.geph = NULL; raw->nav.ng = 0; free(raw->nav.seph); raw->nav.seph = NULL; raw->nav.ns = 0; } /* input receiver raw data from stream ----------------------------------------- * fetch next receiver raw data and input a message from stream * args : raw_t *raw IO receiver raw data control struct * int format I receiver raw data format (STRFMT_???) * unsigned char data I stream data (1 byte) * return : status (-1: error message, 0: no message, 1: input observation data, * 2: input ephemeris, 3: input sbas message, * 9: input ion/utc parameter, 31: input lex message) *-----------------------------------------------------------------------------*/ extern int input_raw(raw_t* raw, int format, unsigned char data) { trace(5, "input_raw: format=%d data=0x%02x\n", format, data); switch (format) { case STRFMT_OEM4: return input_oem4(raw, data); case STRFMT_OEM3: return input_oem3(raw, data); // case STRFMT_UBX : return input_ubx (raw,data); // case STRFMT_SS2 : return input_ss2 (raw,data); // case STRFMT_CRES : return input_cres (raw,data); // case STRFMT_STQ : return input_stq (raw,data); // case STRFMT_GW10 : return input_gw10 (raw,data); // case STRFMT_JAVAD: return input_javad(raw,data); // case STRFMT_NVS : return input_nvs (raw,data); // case STRFMT_BINEX: return input_bnx (raw,data); // case STRFMT_RT17 : return input_rt17 (raw,data); // case STRFMT_LEXR : return input_lexr (raw,data); } return 0; } /* input receiver raw data from file ------------------------------------------- * fetch next receiver raw data and input a message from file * args : raw_t *raw IO receiver raw data control struct * int format I receiver raw data format (STRFMT_???) * FILE *fp I file pointer * return : status(-2: end of file/format error, -1...31: same as above) *-----------------------------------------------------------------------------*/ extern int input_rawf(raw_t* raw, int format, FILE* fp) { trace(4, "input_rawf: format=%d\n", format); switch (format) { case STRFMT_OEM4: return input_oem4f(raw, fp); case STRFMT_OEM3: return input_oem3f(raw, fp); // case STRFMT_UBX : return input_ubxf (raw,fp); // case STRFMT_SS2 : return input_ss2f (raw,fp); // case STRFMT_CRES : return input_cresf (raw,fp); // case STRFMT_STQ : return input_stqf (raw,fp); // case STRFMT_GW10 : return input_gw10f (raw,fp); // case STRFMT_JAVAD: return input_javadf(raw,fp); // case STRFMT_NVS : return input_nvsf (raw,fp); // case STRFMT_BINEX: return input_bnxf (raw,fp); // case STRFMT_RT17 : return input_rt17f (raw,fp); // case STRFMT_LEXR : return input_lexrf (raw,fp); } return -2; }
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/rtklib/rtcm.c
/********************************************************************************* * The RTKLIB software package is distributed under the following BSD 2-clause * license (http://opensource.org/licenses/BSD-2-Clause) and additional two * exclusive clauses. Users are permitted to develop, produce or sell their own * non-commercial or commercial products utilizing, linking or including RTKLIB as * long as they comply with the license. * * Copyright (c) 2007-2013, T. Takasu, 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. * * - The software package includes some companion executive binaries or shared * libraries necessary to execute APs on Windows. These licenses succeed to the * original ones of these software. * * 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 HOLDER 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. ***********************************************************************************/ /*------------------------------------------------------------------------------ * rtcm.c : rtcm functions * * Copyright (C) 2009-2014 by T.TAKASU, All rights reserved. * * references : * [1] RTCM Recommended Standards for Differential GNSS (Global Navigation * Satellite Systems) Service version 2.3, August 20, 2001 * [2] RTCM Standard 10403.1 for Differential GNSS (Global Navigation * Satellite Systems) Services - Version 3, Octobar 27, 2006 * [3] RTCM 10403.1-Amendment 3, Amendment 3 to RTCM Standard 10403.1 * [4] RTCM Paper, April 12, 2010, Proposed SSR Messages for SV Orbit Clock, * Code Biases, URA * [5] RTCM Paper 012-2009-SC104-528, January 28, 2009 (previous ver of [4]) * [6] RTCM Paper 012-2009-SC104-582, February 2, 2010 (previous ver of [4]) * [7] RTCM Standard 10403.1 - Amendment 5, Differential GNSS (Global * Navigation Satellite Systems) Services - version 3, July 1, 2011 * [8] RTCM Paper 019-2012-SC104-689 (draft Galileo ephmeris messages) * [9] RTCM Paper 163-2012-SC104-725 (draft QZSS ephemeris message) * [10] RTCM Paper 059-2011-SC104-635 (draft Galileo and QZSS ssr messages) * [11] RTCM Paper 034-2012-SC104-693 (draft multiple signal messages) * [12] RTCM Paper 133-2012-SC104-709 (draft QZSS MSM messages) * [13] RTCM Paper 122-2012-SC104-707.r1 (draft MSM messages) * [14] RTCM Standard 10403.2, Differential GNSS (Global Navigation Satellite * Systems) Services - version 3, February 1, 2013 * [15] RTCM Standard 10403.2, Differential GNSS (Global Navigation Satellite * Systems) Services - version 3, with amendment 1/2, november 7, 2013 * [16] Proposal of new RTCM SSR Messages (ssr_1_gal_qzss_sbas_dbs_v05) * 2014/04/17 * * version : $Revision:$ $Date:$ * history : 2009/04/10 1.0 new * 2009/06/29 1.1 support type 1009-1012 to get synchronous-gnss-flag * 2009/12/04 1.2 support type 1010,1012,1020 * 2010/07/15 1.3 support type 1057-1068 for ssr corrections * support type 1007,1008,1033 for antenna info * 2010/09/08 1.4 fix problem of ephemeris and ssr sequence upset * (2.4.0_p8) * 2012/05/11 1.5 comply with RTCM 3 final SSR format (RTCM 3 * Amendment 5) (ref [7]) (2.4.1_p6) * 2012/05/14 1.6 separate rtcm2.c, rtcm3.c * add options to select used codes for msm * 2013/04/27 1.7 comply with rtcm 3.2 with amendment 1/2 (ref[15]) * 2013/12/06 1.8 support SBAS/BeiDou SSR messages (ref[16]) *-----------------------------------------------------------------------------*/ /** * file: rtcm.c * version: rtklib ver.2.4.2 * Copy from https://github.com/tomojitakasu/RTKLIB/tree/76b9c97257f304aedad38b5a6bbbac444724aab3/src/rtcm.c */ #include "rtklib.h" /* static const char rcsid[] = "$Id:$"; */ /* function prototypes -------------------------------------------------------*/ extern int decode_rtcm2(rtcm_t* rtcm); extern int decode_rtcm3(rtcm_t* rtcm); extern int encode_rtcm3(rtcm_t* rtcm, int type, int sync); /* constants -----------------------------------------------------------------*/ #define RTCM2PREAMB 0x66 /* rtcm ver.2 frame preamble */ #define RTCM3PREAMB 0xD3 /* rtcm ver.3 frame preamble */ /* initialize rtcm control ----------------------------------------------------- * initialize rtcm control struct and reallocate memory for observation and * ephemeris buffer in rtcm control struct * args : rtcm_t *raw IO rtcm control struct * return : status (1:ok,0:memory allocation error) *-----------------------------------------------------------------------------*/ extern int init_rtcm(rtcm_t* rtcm) { gtime_t time0 = {0}; obsd_t data0 = {{0}}; eph_t eph0 = {0, -1, -1}; geph_t geph0 = {0, -1}; ssr_t ssr0 = {{{0}}}; int i, j; trace(3, "init_rtcm:\n"); rtcm->staid = rtcm->stah = rtcm->seqno = rtcm->outtype = 0; rtcm->time = rtcm->time_s = time0; rtcm->sta.name[0] = rtcm->sta.marker[0] = '\0'; rtcm->sta.antdes[0] = rtcm->sta.antsno[0] = '\0'; rtcm->sta.rectype[0] = rtcm->sta.recver[0] = rtcm->sta.recsno[0] = '\0'; rtcm->sta.antsetup = rtcm->sta.itrf = rtcm->sta.deltype = 0; for (i = 0; i < 3; ++i) { rtcm->sta.pos[i] = rtcm->sta.del[i] = 0.0; } rtcm->sta.hgt = 0.0; rtcm->dgps = NULL; for (i = 0; i < MAXSAT; ++i) { rtcm->ssr[i] = ssr0; } rtcm->msg[0] = rtcm->msgtype[0] = rtcm->opt[0] = '\0'; for (i = 0; i < 6; ++i) { rtcm->msmtype[i][0] = '\0'; } rtcm->obsflag = rtcm->ephsat = 0; for (i = 0; i < MAXSAT; ++i) for (j = 0; j < NFREQ + NEXOBS; ++j) { rtcm->cp[i][j] = 0.0; rtcm->lock[i][j] = rtcm->loss[i][j] = 0; rtcm->lltime[i][j] = time0; } rtcm->nbyte = rtcm->nbit = rtcm->len = 0; rtcm->word = 0; for (i = 0; i < 100; ++i) { rtcm->nmsg2[i] = 0; } for (i = 0; i < 300; ++i) { rtcm->nmsg3[i] = 0; } rtcm->obs.data = NULL; rtcm->nav.eph = NULL; rtcm->nav.geph = NULL; printf("\r\n MAX SAT %d, MAX GLO %d.\r\n", MAXSAT, MAXPRNGLO); /* reallocate memory for observation and ephemris buffer */ if (!(rtcm->obs.data = (obsd_t*)malloc(sizeof(obsd_t) * MAXOBS)) || !(rtcm->nav.eph = (eph_t*)malloc(sizeof(eph_t) * MAXSAT)) || !(rtcm->nav.geph = (geph_t*)malloc(sizeof(geph_t) * MAXSAT))) { free_rtcm(rtcm); return 0; } rtcm->obs.n = 0; rtcm->nav.n = MAXSAT; rtcm->nav.ng = MAXSAT; for (i = 0; i < MAXOBS; ++i) { rtcm->obs.data[i] = data0; } for (i = 0; i < MAXSAT; ++i) { rtcm->nav.eph[i] = eph0; } for (i = 0; i < MAXSAT; ++i) { rtcm->nav.geph[i] = geph0; } return 1; } /* free rtcm control ---------------------------------------------------------- * free observation and ephemris buffer in rtcm control struct * args : rtcm_t *raw IO rtcm control struct * return : none *-----------------------------------------------------------------------------*/ extern void free_rtcm(rtcm_t* rtcm) { trace(3, "free_rtcm:\n"); /* free memory for observation and ephemeris buffer */ free(rtcm->obs.data); rtcm->obs.data = NULL; rtcm->obs.n = 0; free(rtcm->nav.eph); rtcm->nav.eph = NULL; rtcm->nav.n = 0; free(rtcm->nav.geph); rtcm->nav.geph = NULL; rtcm->nav.ng = 0; } /* input rtcm 2 message from stream -------------------------------------------- * fetch next rtcm 2 message and input a message from byte stream * args : rtcm_t *rtcm IO rtcm control struct * unsigned char data I stream data (1 byte) * return : status (-1: error message, 0: no message, 1: input observation data, * 2: input ephemeris, 5: input station pos/ant parameters, * 6: input time parameter, 7: input dgps corrections, * 9: input special message) * notes : before firstly calling the function, time in rtcm control struct has * to be set to the approximate time within 1/2 hour in order to resolve * ambiguity of time in rtcm messages. * supported msgs RTCM ver.2: 1,3,9,14,16,17,18,19,22 * refer [1] for RTCM ver.2 *-----------------------------------------------------------------------------*/ #if 0 extern int input_rtcm2(rtcm_t* rtcm, unsigned char data) { unsigned char preamb; int i; trace(5, "input_rtcm2: data=%02x\n", data); if ((data & 0xC0) != 0x40) { return 0; /* ignore if upper 2bit != 01 */ } for (i = 0; i < 6; ++i, data >>= 1) { /* decode 6-of-8 form */ rtcm->word = (rtcm->word << 1) + (data & 1); /* synchronize frame */ if (rtcm->nbyte == 0) { preamb = (unsigned char)(rtcm->word >> 22); if (rtcm->word & 0x40000000) { preamb ^= 0xFF; /* decode preamble */ } if (preamb != RTCM2PREAMB) { continue; } /* check parity */ if (!decode_word(rtcm->word, rtcm->buff)) { continue; } rtcm->nbyte = 3; rtcm->nbit = 0; continue; } if (++rtcm->nbit < 30) { continue; } else { rtcm->nbit = 0; } /* check parity */ if (!decode_word(rtcm->word, rtcm->buff + rtcm->nbyte)) { trace(2, "rtcm2 partity error: i=%d word=%08x\n", i, rtcm->word); rtcm->nbyte = 0; rtcm->word &= 0x3; continue; } rtcm->nbyte += 3; if (rtcm->nbyte == 6) { rtcm->len = (rtcm->buff[5] >> 3) * 3 + 6; } if (rtcm->nbyte < rtcm->len) { continue; } rtcm->nbyte = 0; rtcm->word &= 0x3; /* decode rtcm2 message */ return decode_rtcm2(rtcm); } return 0; } #endif /* input rtcm 3 message from stream -------------------------------------------- * fetch next rtcm 3 message and input a message from byte stream * args : rtcm_t *rtcm IO rtcm control struct * unsigned char data I stream data (1 byte) * return : status (-1: error message, 0: no message, 1: input observation data, * 2: input ephemeris, 5: input station pos/ant parameters, * 10: input ssr messages) * notes : before firstly calling the function, time in rtcm control struct has * to be set to the approximate time within 1/2 week in order to resolve * ambiguity of time in rtcm messages. * * to specify input options, set rtcm->opt to the following option * strings separated by spaces. * * -EPHALL : input all ephemerides * -STA=nnn : input only message with STAID=nnn * -GLss : select signal ss for GPS MSM (ss=1C,1P,...) * -RLss : select signal ss for GLO MSM (ss=1C,1P,...) * -ELss : select signal ss for GAL MSM (ss=1C,1B,...) * -JLss : select signal ss for QZS MSM (ss=1C,2C,...) * -CLss : select signal ss for BDS MSM (ss=2I,7I,...) * * supported RTCM 3 messages * (ref [2][3][4][5][6][7][8][9][10][11][12][13][14][15]) * * TYPE GPS GLOASS GALILEO QZSS BEIDOU SBAS * ---------------------------------------------------------------------- * OBS C-L1 : 1001~ 1009~ - - - - * F-L1 : 1002 1010 - - - - * C-L12 : 1003~ 1011~ - - - - * F-L12 : 1004 1012 - - - - * * NAV : 1019 1020 1045* 1044* 1047* - * - - 1046* - - - * * MSM 1 : 1071~ 1081~ 1091~ 1111*~ 1121*~ 1101*~ * 2 : 1072~ 1082~ 1092~ 1112*~ 1122*~ 1102*~ * 3 : 1073~ 1083~ 1093~ 1113*~ 1123*~ 1103*~ * 4 : 1074 1084 1094 1114* 1124* 1104* * 5 : 1075 1085 1095 1115* 1125* 1105* * 6 : 1076 1086 1096 1116* 1126* 1106* * 7 : 1077 1087 1097 1117* 1127* 1107* * * SSR OBT : 1057 1063 1240* 1246* 1258* - * CLK : 1058 1064 1241* 1247* 1259* - * BIAS : 1059 1065 1242* 1248* 1260* - * OBTCLK: 1060 1066 1243* 1249* 1261* - * URA : 1061 1067 1244* 1250* 1262* - * HRCLK : 1062 1068 1245* 1251* 1263* - * * ANT INFO : 1005 1006 1007 1008 1033 * ---------------------------------------------------------------------- * (* draft, ~ only encode) * * for MSM observation data with multiple signals for a frequency, * a signal is selected according to internal priority. to select * a specified signal, use the input options. * * rtcm3 message format: * +----------+--------+-----------+--------------------+----------+ * | preamble | 000000 | length | data message | parity | * +----------+--------+-----------+--------------------+----------+ * |<-- 8 --->|<- 6 -->|<-- 10 --->|<--- length x 8 --->|<-- 24 -->| * *-----------------------------------------------------------------------------*/ extern int input_rtcm3(rtcm_t* rtcm, unsigned char data) { trace(5, "input_rtcm3: data=%02x\n", data); /* synchronize frame */ if (rtcm->nbyte == 0) { if (data != RTCM3PREAMB) { return 0; } rtcm->buff[rtcm->nbyte++] = data; return 0; } rtcm->buff[rtcm->nbyte++] = data; if (rtcm->nbyte == 3) { rtcm->len = getbitu(rtcm->buff, 14, 10) + 3; /* length without parity */ } if (rtcm->nbyte < 3 || rtcm->nbyte < rtcm->len + 3) { return 0; } rtcm->nbyte = 0; /* check parity */ if (crc24q(rtcm->buff, rtcm->len) != getbitu(rtcm->buff, rtcm->len * 8, 24)) { trace(2, "rtcm3 parity error: len=%d\n", rtcm->len); return 0; } /* decode rtcm3 message */ return decode_rtcm3(rtcm); } /* input rtcm 2 message from file ---------------------------------------------- * fetch next rtcm 2 message and input a messsage from file * args : rtcm_t *rtcm IO rtcm control struct * FILE *fp I file pointer * return : status (-2: end of file, -1...10: same as above) * notes : same as above *-----------------------------------------------------------------------------*/ #if 0 extern int input_rtcm2f(rtcm_t* rtcm, FILE* fp) { int i, data = 0, ret; trace(4, "input_rtcm2f: data=%02x\n", data); for (i = 0; i < 4096; ++i) { if ((data = fgetc(fp)) == EOF) { return -2; } if ((ret = input_rtcm2(rtcm, (unsigned char)data))) { return ret; } } return 0; /* return at every 4k bytes */ } /* input rtcm 3 message from file ---------------------------------------------- * fetch next rtcm 3 message and input a messsage from file * args : rtcm_t *rtcm IO rtcm control struct * FILE *fp I file pointer * return : status (-2: end of file, -1...10: same as above) * notes : same as above *-----------------------------------------------------------------------------*/ extern int input_rtcm3f(rtcm_t* rtcm, FILE* fp) { int i, data = 0, ret; trace(4, "input_rtcm3f: data=%02x\n", data); for (i = 0; i < 4096; ++i) { if ((data = fgetc(fp)) == EOF) { return -2; } if ((ret = input_rtcm3(rtcm, (unsigned char)data))) { return ret; } } return 0; /* return at every 4k bytes */ } /* generate rtcm 2 message ----------------------------------------------------- * generate rtcm 2 message * args : rtcm_t *rtcm IO rtcm control struct * int type I message type * int sync I sync flag (1:another message follows) * return : status (1:ok,0:error) *-----------------------------------------------------------------------------*/ extern int gen_rtcm2(rtcm_t* rtcm, int type, int sync) { trace(4, "gen_rtcm2: type=%d sync=%d\n", type, sync); rtcm->nbit = rtcm->len = rtcm->nbyte = 0; /* not yet implemented */ return 0; } #endif /* generate rtcm 3 message ----------------------------------------------------- * generate rtcm 3 message * args : rtcm_t *rtcm IO rtcm control struct * int type I message type * int sync I sync flag (1:another message follows) * return : status (1:ok,0:error) *-----------------------------------------------------------------------------*/ #if 0 extern int gen_rtcm3(rtcm_t* rtcm, int type, int sync) { unsigned int crc; int i = 0; trace(4, "gen_rtcm3: type=%d sync=%d\n", type, sync); rtcm->nbit = rtcm->len = rtcm->nbyte = 0; /* set preamble and reserved */ setbitu(rtcm->buff, i, 8, RTCM3PREAMB); i += 8; setbitu(rtcm->buff, i, 6, 0); i += 6; setbitu(rtcm->buff, i, 10, 0); i += 10; /* encode rtcm 3 message body */ if (!encode_rtcm3(rtcm, type, sync)) { return 0; } /* padding to align 8 bit boundary */ for (i = rtcm->nbit; i % 8; ++i) { setbitu(rtcm->buff, i, 1, 0); } /* message length (header+data) (bytes) */ if ((rtcm->len = i / 8) >= 3 + 1024) { trace(2, "generate rtcm 3 message length error len=%d\n", rtcm->len - 3); rtcm->nbit = rtcm->len = 0; return 0; } /* message length without header and parity */ setbitu(rtcm->buff, 14, 10, rtcm->len - 3); /* crc-24q */ crc = crc24q(rtcm->buff, rtcm->len); setbitu(rtcm->buff, i, 24, crc); /* length total (bytes) */ rtcm->nbyte = rtcm->len + 3; return 1; } #endif
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/rtklib/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) cc_library( name = "rtklib", srcs = [ "novatel.c", "rcvraw.c", "rtcm.c", "rtcm3.c", "rtkcmn.c", ], linkstatic = True, alwayslink = True, hdrs = ["rtklib.h"], ) cc_binary( name = "librtklib.so", linkshared = True, linkstatic = True, deps = [":rtklib"] ) install( name = "install", data_dest = "3rd-rtklib", library_dest = "3rd-rtklib/lib", data = [ ":cyberfile.xml", ":3rd-rtklib.BUILD" ], targets = ["librtklib.so"] ) install_src_files( name = "headers", src_dir = ["."], dest = "3rd-rtklib/include", filter = "*.h", ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-rtklib/src", filter = "*", deps = [ ":headers", ] )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/rtklib/3rd-rtklib.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "rtklib", srcs = glob(["lib/*.so*"]), hdrs = glob(["include/*.h"]), strip_include_prefix = "include", visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/adolc/3rd-adolc.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) cc_library( name = "adolc", includes = ["include"], linkopts = [ "-ladolc", ], strip_include_prefix = "include", )
0