├── .npmignore
├── icons
└── predix-timeseries.png
├── readme_images
├── data_ingest_conencted.png
└── data_query_authenticated.png
├── locales
└── en-US
│ └── predix-timeseries.json
├── package.json
├── README.md
├── predix-timeseries.html
├── predix-timeseries-setup.md
├── LICENSE
└── predix-timeseries.js
/.npmignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | npm-debug.log
--------------------------------------------------------------------------------
/icons/predix-timeseries.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SenseTecnic/node-red-contrib-predix-timeseries/develop/icons/predix-timeseries.png
--------------------------------------------------------------------------------
/readme_images/data_ingest_conencted.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SenseTecnic/node-red-contrib-predix-timeseries/develop/readme_images/data_ingest_conencted.png
--------------------------------------------------------------------------------
/readme_images/data_query_authenticated.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SenseTecnic/node-red-contrib-predix-timeseries/develop/readme_images/data_query_authenticated.png
--------------------------------------------------------------------------------
/locales/en-US/predix-timeseries.json:
--------------------------------------------------------------------------------
1 | {
2 | "predix-timeseries":{
3 | "label":{
4 | "aggregations":"Get all available aggregations",
5 | "datapoints":"Query datapoints",
6 | "query-current":"Query for current value",
7 | "tags":"Get all tags"
8 | },
9 | "error":{
10 | "unauthorized":"Unable to authorized with this server"
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "node-red-contrib-predix-timeseries",
3 | "version": "0.0.6",
4 | "description": "A set of Node-RED nodes for GE Predix Timeseries",
5 | "author": {
6 | "name": "Michael Qiu"
7 | },
8 | "dependencies": {
9 | "ws": "0.8.1",
10 | "request": "2.76.0"
11 | },
12 | "keywords": [
13 | "node-red",
14 | "predix",
15 | "timeseries"
16 | ],
17 | "license": "Apache-2.0",
18 | "repository": {
19 | "type": "git",
20 | "url": "git+https://github.com/SenseTecnic/node-red-contrib-predix-timeseries.git"
21 | },
22 | "node-red": {
23 | "nodes": {
24 | "predix-timeseries":"predix-timeseries.js"
25 | }
26 | },
27 | "maintainers": [
28 | {
29 | "name": "Michael Qiu",
30 | "email": "mqiu@sensetecnic.com"
31 | }
32 | ]
33 | }
34 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # node-red-contrib-predix-timeseries
2 |
3 |
4 | These are [Node-RED](http://nodered.org) nodes that interface with the Timeseries microservices on [General Electric's Predix platform](https://www.ge.com/digital/predix) specifically for the functions of data ingestion and data query. The nodes simplify the process of data ingestion and data query without requiring users to develop an actual application on the Predix platform. For more information on Predix, please refer to [Predix resource](https://www.predix.io/resources).
5 |
6 | For more information of these nodes, please refer to the tutorial on [http://developers.sensetecnic.com](http://developers.sensetecnic.com/article/tutorial-using-fred-to-interface-timeseries-on-predix/)
7 |
8 | For a quick way to setup the Timeseries microservice on Predix, please refer to [predix-timeseries-setup-guide](https://github.com/SenseTecnic/node-red-contrib-predix-timeseries/blob/master/predix-timeseries-setup.md).
9 |
10 | ## Pre-requesites
11 |
12 | To run these nodes, you need to have a running Predix Timeseries service on the GE's Predix platform. Please refer to [predix-timeseries-setup-guide](https://github.com/SenseTecnic/node-red-contrib-predix-timeseries/blob/master/predix-timeseries-setup.md).
13 |
14 | ## Install
15 |
16 | Run the follwing command in the root directory of your Node-RED install.
17 | Usually this is `~/.node-red` .
18 | ```
19 | npm install node-red-contrib-predix-timeseries
20 | ```
21 |
22 | ## Usage
23 |
24 | ### Timeseries Ingest node: Write data to timeseries
25 |
26 | To setup the Timeseries ingest node, first setup the Timeseries client configuration by entering the information of your timeseries instance, such as the UAA url, Client ID, Client secret and the Predix-Zone-Id. If you are not sure where to obtain these values, please refer to the [predix-timeseries-setup-guide](https://github.com/SenseTecnic/node-red-contrib-predix-timeseries/blob/master/predix-timeseries-setup.md). For a better understanding of the timeseries data structure, please refer to the [predix timeseries document](https://www.predix.io/docs/?r=816498#F0PrUNk2).
27 |
28 | The current default ws url is wss://gateway-predix-data-services.run.aws-usw02-pr.ice.predix.io/v1/stream/messages, if you have a different ws url, please feel free to contact the author of this node.
29 |
30 | If you have entered all correct information and deploy, you should see the node showing "Connected".
31 | 
32 |
33 | Once the node is connected, user is able send data in the incoming message. The fields include:
34 |
35 | 1. msg.payload.messageId: the ID of this data ingestion message
36 | 2. msg.payload.body: main part of the data ingestion message, which include three fields:
37 | * name: the tag names for timeseries
38 | * datapoints: the datapoints in array form, which include timestamp, measurement and quality
39 | * attributes(optional): attributes are key/value pairs used to store data associated with a tag
40 |
41 | For detail usage of the node, please refer to the tutorial on [http://developers.sensetecnic.com](http://developers.sensetecnic.com/article/tutorial-using-fred-to-interface-timeseries-on-predix/)
42 |
43 |
44 | ### Timeseries Query node: Query data from timeseries
45 |
46 | To setup the Timeseries ingest node, first setup the Timeseries client configuration by entering the information of your timeseries instance, such as the UAA url, Client ID, Client secret and the Predix-Zone-Id. If you are not sure where to obtain these values, please refer to the [predix-timeseries-setup-guide](https://github.com/SenseTecnic/node-red-contrib-predix-timeseries/blob/master/predix-timeseries-setup.md). For a better understanding of the timeseries data structure, please refer to the [predix timeseries document](https://www.predix.io/docs/?r=816498#F0PrUNk2).
47 |
48 | The current default API base url is https://time-series-store-predix.run.aws-usw02-pr.ice.predix.io/v1/, if you have a different url, please feel free to contact the author of this node.
49 |
50 | Once you have all the correct information and deploy the flow, you should see the node showing "Authenticated".
51 | 
52 |
53 | The data query node has a drop down menu with 4 options. They are referring to four API endpoints of the [Preix timeseries data services](https://www.predix.io/api#!/Asset).
54 |
55 | * Get all available aggregations
56 | * Query datapoints
57 | * Query for current value
58 | * Get all tags
59 |
60 |
61 | For sample codes on the query command and node setup, please refer to our tutorial on [http://developers.sensetecnic.com](http://developers.sensetecnic.com/article/tutorial-using-fred-to-interface-timeseries-on-predix/)
62 |
63 |
64 |
--------------------------------------------------------------------------------
/predix-timeseries.html:
--------------------------------------------------------------------------------
1 |
25 |
26 |
44 |
45 |
64 |
65 |
103 |
104 |
114 |
115 |
134 |
135 |
151 |
152 |
170 |
171 |
178 |
--------------------------------------------------------------------------------
/predix-timeseries-setup.md:
--------------------------------------------------------------------------------
1 |
2 | # How to set up a Predix Time Series Microservice for access by Node-RED (Updated on Feb 22, 2017)
3 |
4 | This guide will show you how to set up a timeseries service on Predix platform binded with just a placeholder front-end Webapp. This guide includes 3 major steps, including:
5 |
6 | 1. Set up a placeholder front-end app.
7 | 2. Set up a UAA instance
8 | 3. Set up a Timeseries instance
9 | 4. Update UAA settings
10 |
11 | Once this is done you can ingest and query data though the API explorer tab in Predix Toolkit, or even better, Node-RED using the node-red-contrib-predix-timeseries nodes.
12 |
13 | ## Pre-requesites
14 |
15 | To setup a timeseries service on General Electric's Predix platform, you will need:
16 | - a developer account. For more information on getting a developer account, visit [Predix Developer Network](https://www.predix.io/).
17 |
18 | - Cloud Foundry CLI: http://docs.cloudfoundry.org/cf-cli/
19 |
20 | - Git: https://git-scm.com/
21 |
22 | - Ruby + DevKit: https://www.ruby-lang.org/en/downloads/ https://github.com/oneclick/rubyinstaller/wiki/Development-Kit
23 |
24 | Now let's start the setup.
25 |
26 | ## 1. Setup a placeholder front-end app
27 |
28 | 1. Use the Cloud Foundry CLI to log into Cloud Foundry
29 |
30 | cf login -a
31 |
32 | where the API-ENDPOINT could be one of these:
33 |
34 | Predix Basic: https://api.system.aws-usw02-pr.ice.predix.io
35 | Predix Select: https://api.system.asv-pr.ice.predix.io
36 | Predix Japan: https://api.system.aws-jp01-pr.ice.predix.io
37 | Predix UK: https://api.system.dc-uk01-pr.ice.predix.io
38 |
39 | 2. Clone the hello-world sample app from predix github to your local
40 |
41 | git clone https://github.com/PredixDev/Predix-HelloWorld-WebApp
42 |
43 | 3. Edit the manifest.yml file within the Predix-HelloWorld-Webapp with the following info
44 |
45 | applications:
46 | - name: Predix-HelloWorld-WebApp-
47 | buildpack: predix_openresty_buildpack
48 | memory: 64M
49 | stack: cflinuxfs2
50 |
51 | 4. Inside the Predix-HelloWorld-Webapp
52 |
53 | cf push
54 |
55 | 5. Verify the app is uploaded in Cloud Foundry by
56 |
57 | cf apps
58 | you can also enter this in the browser to check the webpage
59 |
60 | https://Predix-HelloWorld-WebApp-.run.aws-usw02-pr.ice.predix.io
61 |
62 | ## 2. Set up a UAA instance
63 |
64 | 6. Now, create an UAA instance, the easy way would be enter this in the command terminal:
65 |
66 | cf create-service predix-uaa Free -secure-uaa-instance -c '{"adminClientSecret":""}'
67 |
68 | In this command, it really depends on what tier of UAA service is available for you. You might use either **"Free"** or **"Tiered"** service for your UAA instance.
69 |
70 | If you are working on a Windows machine, you would use this instead:
71 |
72 | cf create-service predix-uaa Tiered -secure-uaa-instance -c '{\"adminClientSecret\":\"\"}'
73 |
74 | 7. Then, login to the [Predix Developer Network console](https://www.predix.io/), find your space, and then in the service instances tab, find the UAA service that you just created, click on it.
75 | * You should see a "configure service instance" button on the right hand side, click on it
76 | * Now you will be prompted to enter the admin password for the UAA instance that you just created
77 | * Once you login, you will see your UAA url at the bottom at the dashboard, copy this url for later use.
78 |
79 | 8. Now you would need to loggin the [Predix Toolkit site](https://predix-toolkit.run.aws-usw02-pr.ice.predix.io/).
80 | * Click "Login as admin" on the left-hand panel, then Enter the UAA url along with your admin password, click submit. You should see a response with token.
81 | * Click "Create a client Id", this will be also referred as app client id later on. Enter the client id with a client secret, click submit and you should see a response with token.
82 | * Click "create a user", this will create a user for you
83 | * You can verify by clicking "User Password Login", enter credentials and submit. You should see a response with token.
84 | * Then you can click "check token", in which you should see the decoded token
85 |
86 | ## 3. Set up a Timeseries instance
87 |
88 | 9. In the Predix Developer Network console page, go to catalog -> timeseries -> at the bottom of the page click "subscribe"
89 |
90 | 10. Now fill in the info for new servicve instance
91 | * org/space should be related to your account
92 | * UAA field should be the UAA instance url that you just created
93 | * service instance name would be -timeseries-instance for convention.
94 | * click create service and now you should see the new service instance under your console.
95 |
96 | 11. Your would need to bind the timeseries service with the placeholder app, go to the command terminal and enter:
97 |
98 | cf bind-service Predix-HelloWorld-WebApp- -timeseries-instance
99 |
100 | 12. Now, edit manifest.yml file just like we did for the front-end app. Add in the following fields at the bottom:
101 |
102 | services:
103 | - -secure-uaa-instance
104 | - -timeseries-instance
105 | env:
106 | clientId:
107 | base64ClientCredential:
108 |
109 | Note: if you are working on a Windows environment, you can use an online Base64 encoding tool.
110 |
111 | Now save the yml file, and do a "cf push" again. Once it's done, verify with "cf env Predix-HelloWorld-WebApp-". You will see the config of this app, and we will need these values for the next step. The value of "zone-http-header-value" will be the that you need.
112 |
113 | ## 4. Update UAA settings
114 |
115 | 13. Now, go back to Predix Toolkit site, we need to add timeseries in the authorties.
116 | * login as admin like when you set up UAA instance
117 | * click Get Client ID on the left panel, and you should see the info of the client
118 | * click "Update Client ID", where you will enter these three new authorities for the placeholder app. Note that you will find your timeseries zone id from the command "cf env Predix-HelloWorld-WebApp-" that you did in previous step.
119 |
120 | timeseries.zones..user
121 | timeseries.zones..ingest
122 | timeseries.zones..query
123 |
124 | * validate the token by clicking "check token", you should see the newly added authorities in the token, with the correct timeseries zone id.
125 |
126 | 14. You will also need to grant access privilege to the client and user that you will be using to access the Timeseries instance. You can do this in the UAA instance configuration by adding the corresponding groups to the users that you will be using. The other more efficient way would be adding these groups in the command terminal. Note that you will need to be very careful as you might accidently wipe the admin policies of your UAA instance.
127 |
128 | * You will need to have uaac installed on your workstation. If you have not yet installed that, just enter
129 |
130 | gem install cf-uaac
131 |
132 | * You will need to target to the UAA instance by:
133 |
134 | uaac target
135 |
136 | * Login as admin by:
137 |
138 | uaac token client get admin
139 | Client secret: ****** //Your admin password
140 |
141 | * Create new groups that we will be using by:
142 |
143 | uaac group add timeseries.zones..user
144 | uaac group add timeseries.zones..ingest
145 | uaac group add timeseries.zones..query
146 |
147 | * Assuming you have already had your user set up in the previous step, we will add the corresponding previlege(s) to the user. Note that you can grant only ingest or only query access to the user. We are adding all the previleges here for showcase:
148 |
149 | uaac member add timeseries.zones..user
150 | uaac member add timeseries.zones..ingest
151 | uaac member add timeseries.zones..query
152 |
153 | * You will also need to update the scope list of the client. To do this, enter:
154 |
155 | uaac client get
156 |
157 | and you will be able to see the original scope list you have with the current client ID. For example, the default values should be "uaa.none openid"
158 |
159 | To update the scope list that contains only the default values, you will need to enter:
160 |
161 | uaac client update --scope "timeseries.zones..user timeseries.zones..query timeseries.zones..ingest uaa.none openid"
162 |
163 | You can validate the scope list in the response.
164 |
165 | * If things go well, we can now verify the user previleges by decoding the user token:
166 |
167 | uaac token owner get
168 | Client secret: ****** //client secret
169 | Password: ******** //user password
170 | uaac token decode
171 |
172 | And you should be able to see the user privileges in the scope field of the user token.
173 |
174 |
175 | ## Finishing
176 |
177 | Now that the timeseries instance is set up and ready to use. You can ingest and query data though the API explorer tab in Predix Toolkit.
178 |
179 |
180 |
181 |
182 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
--------------------------------------------------------------------------------
/predix-timeseries.js:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * Copyright 2013, 2017 IBM Corp.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | *
17 | * Modifications copyright (C) 2017 Sense Tecnic Systems, Inc.
18 | *
19 | **/
20 |
21 | var request = require('request');
22 | var ws = require("ws");
23 |
24 | const SECONDS_CONVERT_TO_MS = 1000;
25 | const defaultQueryUrlPrefix = "https://time-series-store-predix.run.aws-usw02-pr.ice.predix.io/v1/";
26 | const defaultWsURL = "wss://gateway-predix-data-services.run.aws-usw02-pr.ice.predix.io/v1/stream/messages";
27 | const originPath = "http://localhost/";
28 |
29 | module.exports = function(RED){
30 | "use strict";
31 |
32 | function timeseriesClientNode(n){
33 |
34 | RED.nodes.createNode(this,n);
35 | var node = this;
36 |
37 | node.UAAurl = n.UAAurl;
38 | node.queryUrlPrefix = (n.queryUrlPrefix === '') ? defaultQueryUrlPrefix : n.queryUrlPrefix;
39 | node.wsUrl = (n.wsUrl === '') ? defaultWsURL : n.wsUrl;
40 | node.clientID = node.credentials.clientID;
41 | node.clientSecret = node.credentials.clientSecret;
42 | node.predixZoneId = n.predixZoneId;
43 |
44 | //add the oauth endpoint to the UAA host url
45 | node.UAAurl += '/oauth/token';
46 |
47 | var buffer = new Buffer(node.clientID+":"+node.clientSecret);
48 | node.base64ClientCredential = buffer.toString('base64');
49 |
50 | var options ={
51 | url: node.UAAurl,
52 | headers:{
53 | 'Content-Type':'application/x-www-form-urlencoded',
54 | 'Pragma':'no-cache',
55 | 'Cache-Control':'no-cache',
56 | 'authorization':'Basic '+node.base64ClientCredential
57 | },
58 | method:'POST',
59 | body:'username='+node.credentials.userID+'&password='+node.credentials.userSecret+'&grant_type=password'
60 | };
61 |
62 | request(options, function(error, response, body){
63 | if(response && response.statusCode!==200){
64 | node.error(response.statusCode+": "+response.statusMessage);
65 | node.emit('unauthenticated','');
66 | } else if(response){
67 | try {
68 | node.accessToken = JSON.parse(response.body).access_token;
69 | node.refreshToken = JSON.parse(response.body).refresh_token;
70 |
71 | node.emit('authenticated','');
72 | node.tokenExpiryTime = (new Date).getTime() + JSON.parse(response.body).expires_in*SECONDS_CONVERT_TO_MS;
73 | } catch (err) {
74 | node.emit('accessTokenError');
75 | }
76 | } else {
77 | node.error("Invalid request");
78 | node.emit('unauthenticated','');
79 | }
80 | });
81 |
82 | this.on('close', function(){
83 | /* nothing for now */
84 | });
85 | }
86 |
87 | RED.nodes.registerType("timeseries-client", timeseriesClientNode, {
88 | credentials:{
89 | clientID:{type:"text"},
90 | clientSecret: { type:"password"},
91 | userID:{type:"text"},
92 | userSecret:{type:"password"}
93 | }
94 | });
95 |
96 | timeseriesClientNode.prototype.checkTokenExpire = function() {
97 | return ((new Date).getTime() >= this.tokenExpiryTime );
98 | };
99 |
100 | timeseriesClientNode.prototype.renewToken = function(/*Node*/handler, callback){
101 |
102 | var options ={
103 | url: handler.UAAurl,
104 | headers:{
105 | 'Content-Type':'application/x-www-form-urlencoded',
106 | 'Pragma':'no-cache',
107 | 'Cache-Control':'no-cache',
108 | 'authorization':'Basic '+handler.base64ClientCredential
109 | },
110 | method:'POST',
111 | body: 'refresh_token='+handler.refreshToken+'&grant_type=refresh_token'
112 | };
113 |
114 | request(options,function(error, response, body){
115 | if(response && response.statusCode!==200){
116 | handler.error(response.statusCode+": "+response.statusMessage);
117 | handler.emit('unauthenticated','');
118 | if(callback != null){
119 | callback(new Error('unauthenticated'), false);
120 | };
121 | } else if(response){
122 | try {
123 | handler.accessToken = JSON.parse(response.body).access_token;
124 | handler.refreshToken = JSON.parse(response.body).refresh_token;
125 | handler.emit('authenticated','');
126 | handler.tokenExpiryTime = (new Date).getTime() + JSON.parse(response.body).expires_in*SECONDS_CONVERT_TO_MS;
127 | if(callback != null){
128 | callback(null, true);
129 | };
130 | } catch (err) {
131 | handler.emit('accessTokenError');
132 | if(callback != null){
133 | callback(new Error('accessTokenError'), false);
134 | };
135 | }
136 | } else {
137 | handler.error("Invalid request");
138 | handler.emit('unauthenticated','');
139 | if(callback != null){
140 | callback(new Error('invalid'), false);
141 | }
142 | }
143 | });
144 | };
145 |
146 | function timeseriesIngestNode(config){
147 | RED.nodes.createNode(this,config);
148 | var node = this;
149 | var isWsConnected = false;
150 | this.server = RED.nodes.getNode(config.server);
151 |
152 | if(this.server){
153 | node.predixZoneId = node.server.predixZoneId;
154 | node.accessToken = node.server.accessToken;
155 |
156 | if(node.predixZoneId && node.accessToken){
157 | startconn();
158 | };
159 |
160 | this.server.on('authenticated', function() {
161 | node.log("[Predix Timeseries]: authenticated");
162 | node.unauthorized = false;
163 | node.status({fill:"green",shape:"dot",text:"Authenticated"});
164 | node.predixZoneId = node.server.predixZoneId;
165 | node.accessToken = node.server.accessToken;
166 | startconn();
167 | });
168 |
169 | this.server.on('unauthenticated',function() {
170 | node.log("[Predix Timeseries]: unauthenticated");
171 | node.unauthorized = true;
172 | node.status({fill:"red",shape:"ring",text:"Unauthenticated"});
173 | node.predixZoneId = "";
174 | node.accessToken = "";
175 | });
176 |
177 | this.server.on('accessTokenError',function() {
178 | node.error("[Predix Timeseries]: access token error");
179 | node.unauthorized = true;
180 | node.status({fill:"red",shape:"ring",text:"Access Error"});
181 | node.predixZoneId = "";
182 | node.accessToken = "";
183 | });
184 | } else {
185 | node.status({fill:"yellow", shape:"dot",text:"Missing config"});
186 | }
187 |
188 | //ws connection
189 | function startconn(){
190 | node.log("[Predix Timeseries]: start connection");
191 | var opts = {};
192 | if(node.predixZoneId && node.accessToken) {
193 | opts={
194 | headers:{
195 | 'predix-zone-id':node.predixZoneId,
196 | 'authorization':'Bearer '+node.accessToken,
197 | 'origin':originPath
198 | }
199 | };
200 | } else {
201 | if (!node.accessToken) {
202 | node.status({fill:"red",shape:"ring",text:"missing access token"});
203 | } else if (!node.predixZoneId) {
204 | node.status({fill:"red",shape:"ring",text:"missing predix zone id"});
205 | }
206 | return;
207 | }
208 | var socket = new ws(wsURL, opts);
209 | node.connection = socket;
210 | handleConnection(node.connection);
211 | }
212 |
213 | function handleConnection(/*socket*/socket){
214 | socket.on('open', function(){
215 | node.log("[Predix Timeseries]: websocket is connected");
216 | isWsConnected = true;
217 | node.emit('opened','');
218 | node.status({fill:"green",shape:"dot",text:"Connected"});
219 | });
220 |
221 | socket.on('close',function(code, data){
222 | node.log("[Predix Timeseries]: websocket is closed");
223 | isWsConnected = false;
224 | node.status({fill:"red",shape:"ring",text:"Closed"});
225 | node.emit('closed');
226 |
227 | //reconnect
228 | if(node.accessToken != ""){
229 | clearTimeout(node.tout);
230 | node.emit('reconnecting');
231 | node.status({fill:"yellow",shape:"ring",text:"Reconnecting"});
232 | node.tout = setTimeout(function(){ startconn(); }, 3000);
233 | };
234 | });
235 |
236 | socket.on('error', function(err){
237 | isWsConnected = false;
238 | node.error(err);
239 |
240 | node.status({fill:"red",shape:"ring",text:"Error"});
241 |
242 | if(node.server.checkTokenExpire()){
243 | node.server.renewToken(node.server);
244 | if(node.accessToken != ""){
245 | clearTimeout(node.tout);
246 | node.emit('reconnecting');
247 | node.status({fill:"yellow",shape:"ring",text:"Reconnecting"});
248 | node.tout = setTimeout(function(){ startconn(); }, 3000);
249 | }
250 | }
251 | });
252 |
253 | socket.on('message',function(data){
254 | node.log(data);
255 | var statusCode;
256 | try {
257 | statusCode = JSON.parse(data).statusCode;
258 | } catch (err) {
259 | node.error("Invalid status code");
260 | }
261 | if(statusCode !== 202 ){
262 | node.error(statusCode + ": " + "Ingest error");
263 | };
264 | })
265 | }
266 |
267 | this.on("input", function(msg){
268 | var payload;
269 | if (msg.hasOwnProperty("payload")) {
270 | if (!Buffer.isBuffer(msg.payload)) { // if it's not a buffer make sure it's a string.
271 | payload = RED.util.ensureString(msg.payload);
272 | } else {
273 | payload = msg.payload;
274 | }
275 | }
276 | if(isWsConnected === true){
277 | if (payload) {
278 | try {
279 | node.connection.send(payload);
280 | } catch(err){
281 | node.error(err);
282 | }
283 | }
284 | } else {
285 | node.error("[Predix Timeseries]: Websocket not connected");
286 | }
287 | });
288 | }
289 | RED.nodes.registerType("timeseries-ingest", timeseriesIngestNode);
290 |
291 | function timeseriesQueryNode(config){
292 | RED.nodes.createNode(this,config);
293 | var node = this;
294 | var requestMethod ='';
295 | node.queryType = config.queryType;
296 |
297 | this.server = RED.nodes.getNode(config.server);
298 |
299 | if(this.server){
300 | node.accessToken = this.server.accessToken;
301 | node.predixZoneId = node.server.predixZoneId;
302 | this.server.on('authenticated', function() {
303 | node.unauthorized = false;
304 | node.status({fill:"green",shape:"dot",text:"Authenticated"});
305 | node.predixZoneId = node.server.predixZoneId;
306 | node.accessToken = node.server.accessToken;
307 | });
308 | this.server.on('unauthenticated',function() {
309 | node.unauthorized = true;
310 | node.status({fill:"red",shape:"ring",text:"Unauthenticated"});
311 | node.predixZoneId = "";
312 | node.accessToken = "";
313 | });
314 | this.server.on('accessTokenError',function() {
315 | node.unauthorized = true;
316 | node.status({fill:"red",shape:"ring",text:"Access Error"});
317 | node.predixZoneId = "";
318 | node.accessToken = "";
319 | });
320 | } else {
321 | node.status({fill:"yellow", shape:"dot",text:"Missing server config"});
322 | }
323 |
324 | switch(node.queryType){
325 | case "aggregations":
326 | node.apiEndpoint = node.server.queryUrlPrefix + "aggregations";
327 | requestMethod = 'GET';
328 | break;
329 | case "datapoints":
330 | node.apiEndpoint = node.server.queryUrlPrefix + "datapoints";
331 | requestMethod = 'POST';
332 | break;
333 | case "currentDatapoints":
334 | node.apiEndpoint = node.server.queryUrlPrefix + "datapoints/latest";
335 | requestMethod = 'POST';
336 | break;
337 | case "tags":
338 | node.apiEndpoint = node.server.queryUrlPrefix + "tags";
339 | requestMethod = 'GET';
340 | break;
341 | default:
342 | node.apiEndpoint = node.server.queryUrlPrefix;
343 | };
344 |
345 | function requestCall(msg){
346 | if (msg.hasOwnProperty("payload")){
347 | var body;
348 | try {
349 | body = JSON.stringify(msg.payload)
350 | } catch (err) {
351 | node.error("Failed to parse msg.payload: " + err);
352 | return;
353 | }
354 | var options ={
355 | url: node.apiEndpoint,
356 | headers:{
357 | 'predix-zone-id':node.predixZoneId,
358 | 'authorization':'Bearer '+node.accessToken
359 | },
360 | method:requestMethod,
361 | body:body
362 | };
363 |
364 | request(options, function(error, response, body){
365 | if(error){
366 | node.error(error);
367 | } else if(response) {
368 | if (response.statusCode!==200){
369 | node.error(response.statusCode+": "+response.body);
370 | } else {
371 | node.send({payload:response.body});
372 | }
373 | }
374 | });
375 | }
376 | };
377 |
378 | this.on('input', function(msg){
379 | if (node.server.checkTokenExpire()){
380 | node.server.renewToken(node.server, function(err, bool){
381 | if(bool === true){
382 | requestCall(msg);
383 | } else {
384 | node.error(err);
385 | }
386 | });
387 | } else {
388 | requestCall(msg);
389 | };
390 | });
391 | }
392 | RED.nodes.registerType("timeseries-query", timeseriesQueryNode);
393 | }
394 |
395 |
--------------------------------------------------------------------------------