Node-RED-Weather-Routing-Logistics

Signed-off-by: John Walicki <johnwalicki@gmail.com>
main
John Walicki 5 years ago
parent 35e7788e6a
commit 2e16d27289

@ -0,0 +1,3 @@
TWCAPIKEY=
HEREAPIKEY=
WATSON_TTS=

111
.gitignore vendored

@ -1 +1,110 @@
*.backup
# Secrets
.env
.flow_cred.json.backup
.flow.json.backup
secrets.sh
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port

@ -0,0 +1,33 @@
FROM registry.access.redhat.com/ubi8:8.4 as build
LABEL stage=builder
RUN dnf module install --nodocs -y nodejs:14 python39 --setopt=install_weak_deps=0 --disableplugin=subscription-manager \
&& dnf install --nodocs -y git make gcc gcc-c++ --setopt=install_weak_deps=0 --disableplugin=subscription-manager \
&& dnf clean all --disableplugin=subscription-manager
RUN mkdir -p /opt/app-root/src
WORKDIR /opt/app-root/src
COPY ./package.json /opt/app-root/src/package.json
RUN npm install --no-audit --no-update-notifier --no-fund --production
COPY ./server.js /opt/app-root/src/
COPY ./settings.js /opt/app-root/src/
COPY ./.env /opt/app-root/src/
COPY ./flow.json /opt/app-root/src/flow.json
COPY ./flow_cred.json /opt/app-root/src/flow_cred.json
## Release image
FROM registry.access.redhat.com/ubi8/nodejs-14-minimal:1
COPY --from=build /opt/app-root/src /opt/app-root/src/
WORKDIR /opt/app-root/src
ENV PORT 1880
ENV NODE_ENV=production
#ENV TWCAPIKEY=
#ENV HEREAPIKEY=
#ENV WATSON_TTS=
EXPOSE 1880
CMD ["node", "/opt/app-root/src/server.js", "/opt/app-root/src/flow.json"]

@ -0,0 +1,201 @@
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 [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT 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,0 +1,53 @@
# Makefile for Node-RED-Weather-Routing-Logistic
DOCKERHUB_ID:=
IMG_NAME:="node-red-weather-routing-logistics"
IMG_VERSION:="1.0.0"
ARCH:="amd64"
# Store the secrets in a .env file (see ./.env.example)
# or modify the Makefile "run" rule below to run the
# docker container with -e environment variables
# or store them directly in the Dockerfile
TWCAPIKEY:=
HEREAPIKEY:=
WATSON_TTS:=
# Leave blank for open DockerHub containers
# CONTAINER_CREDS:=-r "registry.wherever.com:myid:mypw"
CONTAINER_CREDS:=
default: build run
build:
docker build --rm -t $(DOCKERHUB_ID)/$(IMG_NAME):$(IMG_VERSION) .
docker image prune --filter label=stage=builder --force
dev: stop build
docker run -it --name ${IMG_NAME} \
$(DOCKERHUB_ID)/$(IMG_NAME):$(IMG_VERSION) /bin/bash
run: stop
docker run -d \
--name ${IMG_NAME} \
--env-file .env \
-p 1880:1880 \
--restart unless-stopped \
$(DOCKERHUB_ID)/$(IMG_NAME):$(IMG_VERSION)
test:
xdg-open http://127.0.0.1:1880
ui:
xdg-open http://127.0.0.1:1880/ui
push:
docker push $(DOCKERHUB_ID)/$(IMG_NAME):$(IMG_VERSION)
stop:
@docker rm -f ${IMG_NAME} >/dev/null 2>&1 || :
clean:
@docker rmi -f $(DOCKERHUB_ID)/$(IMG_NAME):$(IMG_VERSION) >/dev/null 2>&1 || :
.PHONY: build dev run push test ui stop clean

@ -1,9 +1,101 @@
Weather-Routing-Logistics
=========================
# Node-RED Weather Routing Logistics Dashboard
Build a Node-RED Dashboard which overlays TWC weather maps on a HERE truck routing map
Node-RED Dashboard which overlays TWC weather maos on a HERE truck routing map
This example might be useful for a package logistics company who wants to build logistics applications using TWC APIs that can help improve route planning, driver safety and equipment safety.  Using The Weather Company APIs to alert drivers of storm warnings and forecasts, wind advisories, winter conditions, and real time driving updates can improve package delivery times and protect drivers.
### About
It uses [The Weather Company APIs](https://www.ibm.com/products/weather-operations-center/data-packages) to display a near real-time North America Satellite / Radar Weather map on a [Node-RED](https://nodered.org) Dashboard. It could be extended to display TWC forecast map tiles of winter advisories, hail alerts, wind conditions, etc.
This is your project's README.md file. It helps users understand what your
project does, how to use it and anything else they may need to know.
This Node-RED flow retrieves map tiles from the [TWC Current Conditions](https://ibm.co/TWCecc) package and, specifically, the [Current Conditions Gridded Tiler APIs](https://ibm.co/v2EHCg). There are many TWC weather map tile layers available. One of the APIs returns satellite and weather radar tiles. See the [Node-RED-TWC-Weather-Radar-Map](https://github.com/johnwalicki/Node-RED-TWC-Weather-Radar-Map) repository for additional examples.
It also uses the [HERE.com Routing APIs](https://developer.here.com/documentation#routing_and_navigation_section) to build a map navigation dashboard and plots the truck route on a [Node-RED](https://nodered.org) Dashboard.
To assist the driver during hazardous driving conditions, it uses the [Watson Text to Speech](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-about#about) service to narrate the route.
This example flow and Node-RED Dashboard might be useful as part of a [Call for Code](https://developer.ibm.com/callforcode/) solution that uses TWC and HERE Technologies APIs. Natural disaster applications could guide someone to safety.
### Prerequistes
- [Install Node-RED](https://nodered.org/docs/getting-started/) on your system or in the cloud
- This flow can be deployed to [IBM Cloud](https://cloud.ibm.com/registration) by creating a [Node-RED Starter Application](https://developer.ibm.com/components/node-red/tutorials/how-to-create-a-node-red-starter-application/)
- This flow requires Node-RED v1.3 or higher
- [Add the following nodes](https://nodered.org/docs/user-guide/runtime/adding-nodes) to your Node-RED palette
- [node-red-dashboard](https://flows.nodered.org/node/node-red-dashboard)
- [node-red-contrib-here-maps](https://github.com/johnwalicki/node-red-contrib-here-maps)
- [node-red-node-ui-table](https://flows.nodered.org/node/node-red-node-ui-table)
- [node-red-contrib-web-worldmap](https://flows.nodered.org/node/node-red-contrib-web-worldmap)
- [node-red-node-watson](https://flows.nodered.org/node/node-red-node-watson)
- Signup for a [HERE Developer account](https://developer.here.com)
- Signup for an [IBM Cloud](https://cloud.ibm.com/registration) account
- Create a (free) instance of [Watson Text to Speech](https://cloud.ibm.com/catalog/services/text-to-speech)
- If you are participating in the [2021 Call for Code](https://developer.ibm.com/callforcode/) you can [register](https://developer.ibm.com/callforcode/tools/weather/) for a time limited TWC API key.
- Learn more about the TWC APIs used in this Node-RED flow by reading the [TWC Current Conditions API documentation](https://ibm.co/TWCecc)
## API Keys
Set your TWC API, HERE API and Watson Text to Speech keys as environment variables before starting Node-RED
```sh
export TWCAPIKEY=<TWC API KEY>
export HEREAPIKEY=<HERE API KEY>
export WATSON_TTS=<Watson Text to Speech API KEY>
```
## Node-RED flow in this repository:
---
### A flow that displays a Weather Map and Navigation Route
![Weather Routing Logistics Navigation Dashboard](screenshots/Node-RED-TWC-Logistics-Routing-Dashboard.png?raw=true "Weather Logistics Navigation Dashboard")
<p align="center">
<strong>Get the Code: <a href="flow.json">Node-RED flow for Weather Logistics Routing / Navigation</strong></a>
</p>
![Weather Routing Logistics flow](screenshots/Node-RED-WeatherRoutingLogistics-flow.png?raw=true "Weather Logistics Navigation flow")
This flow has four sections:
1. The **Starting and Destination Locations / Geocode** section displays a Node-RED Dashboard form which prompts the navigator
to enter their starting location and ending destination. The flow then calls the [HERE Geocode Search API](https://developer.here.com/documentation/geocoding-search-api/dev_guide/index.html) to determine the latitude and longitude of the two waypoints.
1. The **Request Driving Navigation Instructions** section calls the [HERE Routing API](https://developer.here.com/documentation/routing/dev_guide/topics/introduction.html) to calculate the route between the two locations. It builds a table of these driving instructions and displays a summary of the route distance and driving duration.
1. The **Draw Map and Route** section moves the truck on the node-red-contrib-web-worldmap as the navigator clicks on the **Navigation Preview** button. It loads the TWC Weather Satellite Radar tile overlays onto the worldmap to warn the driver of impending weather conditions.
1. The **Read the Driving Instructions** section determines if the mute slider is on / off and uses the Watson Text to Speech service to read the driving instructions aloud. Paste your Watson Text to Speech credentials into the node.
---
## Containerization
You might want to deploy this Node-RED flow to IBM Cloud Code Engine. The first step is to build a container. This repository includes a `Makefile` and a `Dockerfile` to assist in building a container.
- Log into your Docker Hub account so the container can be hosted for Cloud deployment.
```sh
docker login
```
- Edit the variable at the top of the Makefile, if necessary. If you plan to push it to a Docker registry, make sure you enter your docker ID.
- Change the following `Makefile` line:
```make
DOCKERHUB_ID:=<your docker registry account>
```
- Enter the TWC, HERE, Watson TTS API Keys in the .env file (see .env.example for formatting)
- Build the container, run the container, test the Node-RED Dashboard in the container, push the container to the Docker registry.
```sh
make build
make run
make test
make ui
make push
```
### Authors
- [John Walicki](https://github.com/johnwalicki)
---
Enjoy! Give us [feedback](https://github.com/johnwalicki/Node-RED-Weather-Routing-Logistics/issues) if you have suggestions on how to improve this tutorial.
## License
This tutorial is licensed under the Apache Software License, Version 2. Separate third party code objects invoked within this code pattern are licensed by their respective providers pursuant to their own separate licenses. Contributions are subject to the [Developer Certificate of Origin, Version 1.1 (DCO)](https://developercertificate.org/) and the [Apache Software License, Version 2](http://www.apache.org/licenses/LICENSE-2.0.txt).

File diff suppressed because it is too large Load Diff

@ -1 +1,5 @@
{}
{
"e3d8a028.af557": {
"apikey": "${HEREAPIKEY}"
}
}

@ -1,12 +1,37 @@
{
"name": "Weather-Routing-Logistics",
"description": "Node-RED Dashboard which overlays TWC weather maos on a HERE truck routing map ",
"version": "0.0.1",
"dependencies": {},
"description": "Node-RED Dashboard which overlays TWC weather maps on a HERE truck routing map",
"version": "1.0.0",
"repository": {
"type": "git",
"url": "git+https://github.com/johnwalicki/Node-RED-Weather-Routing-Logistics.git"
},
"keywords": [
"node-red",
"weather",
"twc",
"forecast",
"routing",
"logistics",
"trucking",
"here",
"radar"
],
"author": "John Walicki <johnwalicki@gmail.com>",
"license": "Apache-2.0",
"dependencies": {
"node-red": "1.3.x",
"node-red-contrib-here-maps": "github:johnwalicki/node-red-contrib-here-maps.git",
"node-red-contrib-twc-weather": "0.x",
"node-red-contrib-web-worldmap": "2.x",
"node-red-dashboard": "2.x",
"node-red-node-ui-table": "0.x",
"node-red-node-watson": "0.x"
},
"node-red": {
"settings": {
"flowFile": "flow.json",
"credentialsFile": "flow_cred.json"
}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

@ -0,0 +1,110 @@
// Requires statements and code for non-production mode usage
// if (!process.env.NODE_ENV || !process.env.NODE_ENV === 'production') {
// require('appmetrics-dash').attach();
//}
var http = require('http');
var https = require('https');
var util = require("util");
var express = require("express");
var crypto = require("crypto");
try { bcrypt = require('bcrypt'); }
catch(e) { bcrypt = require('bcryptjs'); }
var nopt = require("nopt");
var path = require("path");
var fs = require("fs-extra");
var RED = require("node-red");
// var health = require('@cloudnative/health-connect');
// Create an Express app
var server;
var app = express();
process.env.NODE_RED_HOME = __dirname;
// Add a simple route for static content served from 'public'
app.use("/",express.static("public"));
//var healthcheck = new health.HealthChecker();
//app.use('/live', health.LivenessEndpoint(healthcheck));
//app.use('/ready', health.ReadinessEndpoint(healthcheck));
//app.use('/health', health.HealthEndpoint(healthcheck));
// Create the settings object from file
var settings = require("./settings.js");
var fs = require("fs");
if (process.env.NODE_RED_TLS_CERT && process.env.NODE_RED_TLS_KEY) {
settings.https = {
"key" : fs.readFileSync(process.env.NODE_RED_TLS_KEY),
"cert" : fs.readFileSync(process.env.NODE_RED_TLS_CERT)
};
if (process.env.NODE_RED_TLS_CA) {
settings.https.ca = fs.readFileSync(process.env.NODE_RED_TLS_CA);
}
if (process.env.NODE_RED_TLS_PASS_FILE) {
settings.https.passphrase = fs.readFileSync(process.env.NODE_RED_TLS_PASS_FILE);
} else if (process.env.NODE_RED_TLS_PASS_ENV) {
settings.https.passphrase = process.env.NODE_RED_TLS_PASS_ENV;
}
settings.requireHttps = true;
}
if (settings.https) {
server = https.createServer(settings.https,function(req,res) {app(req,res);});
} else {
server = http.createServer(function(req,res) {app(req,res);});
}
server.setMaxListeners(0);
function formatRoot(root) {
if (root[0] != "/") {
root = "/" + root;
}
if (root.slice(-1) != "/") {
root = root + "/";
}
return root;
}
if (settings.httpRoot === false) {
settings.httpAdminRoot = false;
settings.httpNodeRoot = false;
} else {
settings.httpRoot = settings.httpRoot||"/";
settings.disableEditor = settings.disableEditor||false;
}
if (settings.httpAdminRoot !== false) {
settings.httpAdminRoot = formatRoot(settings.httpAdminRoot || settings.httpRoot || "/");
settings.httpAdminAuth = settings.httpAdminAuth || settings.httpAuth;
} else {
settings.disableEditor = true;
}
if (settings.httpNodeRoot !== false) {
settings.httpNodeRoot = formatRoot(settings.httpNodeRoot || settings.httpRoot || "/");
settings.httpNodeAuth = settings.httpNodeAuth || settings.httpAuth;
}
if (settings.uiPort === undefined){
settings.uiPort = 1880;
}
settings.uiHost = settings.uiHost||"0.0.0.0";
// Initialise the runtime with a server and settings
RED.init(server,settings);
// Serve the editor UI from /red
app.use(settings.httpAdminRoot,RED.httpAdmin);
// Serve the http nodes UI from /api
app.use(settings.httpNodeRoot,RED.httpNode);
server.listen(settings.uiPort);
// Start the runtime
RED.start();

@ -0,0 +1,276 @@
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
// The `https` setting requires the `fs` module. Uncomment the following
// to make it available:
//var fs = require("fs");
module.exports = {
// the tcp port that the Node-RED web server is listening on
uiPort: process.env.PORT || 1880,
// By default, the Node-RED UI accepts connections on all IPv4 interfaces.
// To listen on all IPv6 addresses, set uiHost to "::",
// The following property can be used to listen on a specific interface. For
// example, the following would only allow connections from the local machine.
//uiHost: "127.0.0.1",
// Retry time in milliseconds for MQTT connections
mqttReconnectTime: 15000,
// Retry time in milliseconds for Serial port connections
serialReconnectTime: 15000,
// Retry time in milliseconds for TCP socket connections
//socketReconnectTime: 10000,
// Timeout in milliseconds for TCP server socket connections
// defaults to no timeout
//socketTimeout: 120000,
// Maximum number of messages to wait in queue while attempting to connect to TCP socket
// defaults to 1000
//tcpMsgQueueSize: 2000,
// Timeout in milliseconds for HTTP request connections
// defaults to 120 seconds
//httpRequestTimeout: 120000,
// The maximum length, in characters, of any message sent to the debug sidebar tab
debugMaxLength: 1000,
// The maximum number of messages nodes will buffer internally as part of their
// operation. This applies across a range of nodes that operate on message sequences.
// defaults to no limit. A value of 0 also means no limit is applied.
//nodeMaxMessageBufferLength: 0,
// To disable the option for using local files for storing keys and certificates in the TLS configuration
// node, set this to true
//tlsConfigDisableLocalFiles: true,
// Colourise the console output of the debug node
//debugUseColors: true,
// The file containing the flows. If not set, it defaults to flows_<hostname>.json
flowFile: 'flow.json',
// To enabled pretty-printing of the flow within the flow file, set the following
// property to true:
//flowFilePretty: true,
// By default, credentials are encrypted in storage using a generated key. To
// specify your own secret, set the following property.
// If you want to disable encryption of credentials, set this property to false.
// Note: once you set this property, do not change it - doing so will prevent
// node-red from being able to decrypt your existing credentials and they will be
// lost.
credentialSecret: false,
// By default, all user data is stored in a directory called `.node-red` under
// the user's home directory. To use a different location, the following
// property can be used
userDir: '/opt/app-root/src/',
// Node-RED scans the `nodes` directory in the userDir to find local node files.
// The following property can be used to specify an additional directory to scan.
nodesDir: '/opt/app-root/src/nodes',
// By default, the Node-RED UI is available at http://localhost:1880/
// The following property can be used to specify a different root path.
// If set to false, this is disabled.
//httpAdminRoot: false,
//httpAdminRoot: "/admin",
// Some nodes, such as HTTP In, can be used to listen for incoming http requests.
// By default, these are served relative to '/'. The following property
// can be used to specify a different root path. If set to false, this is
// disabled.
httpNodeRoot: '/',
// The following property can be used in place of 'httpAdminRoot' and 'httpNodeRoot',
// to apply the same root to both parts.
//httpRoot: '/red',
// When httpAdminRoot is used to move the UI to a different root path, the
// following property can be used to identify a directory of static content
// that should be served at http://localhost:1880/.
httpStatic: '/',
// The maximum size of HTTP request that will be accepted by the runtime api.
// Default: 5mb
//apiMaxLength: '5mb',
// If you installed the optional node-red-dashboard you can set it's path
// relative to httpRoot
ui: { path: "ui" },
// Securing Node-RED
// -----------------
// To password protect the Node-RED editor and admin API, the following
// property can be used. See http://nodered.org/docs/security.html for details.
//adminAuth: {
// type: "credentials",
// users: [{
// username: "admin",
// password: "$2a$08$zZWtXTja0fB1pzD4sHCMyOCMYz2Z6dNbM6tl8sJogENOMcxWV9DN.",
// permissions: "*"
// }]
//},
// To password protect the node-defined HTTP endpoints (httpNodeRoot), or
// the static content (httpStatic), the following properties can be used.
// The pass field is a bcrypt hash of the password.
// See http://nodered.org/docs/security.html#generating-the-password-hash
//httpNodeAuth: {user:"user",pass:"$2a$08$zZWtXTja0fB1pzD4sHCMyOCMYz2Z6dNbM6tl8sJogENOMcxWV9DN."},
//httpStaticAuth: {user:"user",pass:"$2a$08$zZWtXTja0fB1pzD4sHCMyOCMYz2Z6dNbM6tl8sJogENOMcxWV9DN."},
// The following property can be used to enable HTTPS
// See http://nodejs.org/api/https.html#https_https_createserver_options_requestlistener
// for details on its contents.
// See the comment at the top of this file on how to load the `fs` module used by
// this setting.
//
//https: {
// key: fs.readFileSync('privatekey.pem'),
// cert: fs.readFileSync('certificate.pem')
//},
// The following property can be used to cause insecure HTTP connections to
// be redirected to HTTPS.
//requireHttps: true,
// The following property can be used to disable the editor. The admin API
// is not affected by this option. To disable both the editor and the admin
// API, use either the httpRoot or httpAdminRoot properties
//disableEditor: false,
// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
//httpNodeCors: {
// origin: "*",
// methods: "GET,PUT,POST,DELETE"
//},
// If you need to set an http proxy please set an environment variable
// called http_proxy (or HTTP_PROXY) outside of Node-RED in the operating system.
// For example - http_proxy=http://myproxy.com:8080
// (Setting it here will have no effect)
// You may also specify no_proxy (or NO_PROXY) to supply a comma separated
// list of domains to not proxy, eg - no_proxy=.acme.co,.acme.co.uk
// The following property can be used to add a custom middleware function
// in front of all http in nodes. This allows custom authentication to be
// applied to all http in nodes, or any other sort of common request processing.
//httpNodeMiddleware: function(req,res,next) {
// // Handle/reject the request, or pass it on to the http in node by calling next();
// // Optionally skip our rawBodyParser by setting this to true;
// //req.skipRawBodyParser = true;
// next();
//},
// The following property can be used to pass custom options to the Express.js
// server used by Node-RED. For a full list of available options, refer
// to http://expressjs.com/en/api.html#app.settings.table
//httpServerOptions: { },
// The following property can be used to verify websocket connection attempts.
// This allows, for example, the HTTP request headers to be checked to ensure
// they include valid authentication information.
//webSocketNodeVerifyClient: function(info) {
// // 'info' has three properties:
// // - origin : the value in the Origin header
// // - req : the HTTP request
// // - secure : true if req.connection.authorized or req.connection.encrypted is set
// //
// // The function should return true if the connection should be accepted, false otherwise.
// //
// // Alternatively, if this function is defined to accept a second argument, callback,
// // it can be used to verify the client asynchronously.
// // The callback takes three arguments:
// // - result : boolean, whether to accept the connection or not
// // - code : if result is false, the HTTP error status to return
// // - reason: if result is false, the HTTP reason string to return
//},
// The following property can be used to seed Global Context with predefined
// values. This allows extra node modules to be made available with the
// Function node.
// For example,
// functionGlobalContext: { os:require('os') }
// can be accessed in a function block as:
// global.get("os")
functionGlobalContext: {
// os:require('os'),
// jfive:require("johnny-five"),
// j5board:require("johnny-five").Board({repl:false})
},
// `global.keys()` returns a list of all properties set in global context.
// This allows them to be displayed in the Context Sidebar within the editor.
// In some circumstances it is not desirable to expose them to the editor. The
// following property can be used to hide any property set in `functionGlobalContext`
// from being list by `global.keys()`.
// By default, the property is set to false to avoid accidental exposure of
// their values. Setting this to true will cause the keys to be listed.
exportGlobalContextKeys: false,
// Context Storage
// The following property can be used to enable context storage. The configuration
// provided here will enable file-based context that flushes to disk every 30 seconds.
// Refer to the documentation for further options: https://nodered.org/docs/api/context/
//
//contextStorage: {
// default: {
// module:"localfilesystem"
// },
//},
// The following property can be used to order the categories in the editor
// palette. If a node's category is not in the list, the category will get
// added to the end of the palette.
// If not set, the following default order is used:
//paletteCategories: ['subflows', 'input', 'output', 'function', 'social', 'mobile', 'storage', 'analysis', 'advanced'],
// Configure the logging output
logging: {
// Only console logging is currently supported
console: {
// Level of logging to be recorded. Options are:
// fatal - only those errors which make the application unusable should be recorded
// error - record errors which are deemed fatal for a particular request + fatal errors
// warn - record problems which are non fatal + errors + fatal errors
// info - record information about the general running of the application + warn + error + fatal errors
// debug - record information which is more verbose than info + info + warn + error + fatal errors
// trace - record very detailed logging + debug + info + warn + error + fatal errors
// off - turn off all logging (doesn't affect metrics or audit)
level: "info",
// Whether or not to include metric events in the log output
metrics: false,
// Whether or not to include audit events in the log output
audit: false
}
},
// Customising the editor
editorTheme: {
projects: {
// To enable the Projects feature, set this value to true
enabled: false
}
}
};
Loading…
Cancel
Save

Powered by TurnKey Linux.