Having gone from spending countless hours staring at HTML5 CANVAS, I’m now at the “meh” stage as it starts to dawn on my how it works.
And so it was that I stumbled on RGraph – or put another way, Christmas for widget-lovers.
If you’ve been following these blog entries you’ll know that Node-Red has TEMPLATES in the UI – and that you can put your own stuff into the templates and that recently the fog has lifted on getting variables in and out of the templates.
In recent blogs I’ve been constantly improving a thermostat control page and that took me off looking for a gauge with two pointers – one to show temperature, the other to show humidity.
And that’s when I stumbled upon RGraph. If you read this – and understand it – you will open the doors to a boatload of gauges, thermometers, charts and graphs so tuck in:
First things first, if you’ve already played with Node-Red in here you will likely have made a /myjs folder (home/pi/.node-red/public/myjs or similar – defined in your Node-Red settings.js file) to put various Javascript files in. Well, add this lot in a sub-folder called RGraph – you can call it freddy if you like but I thought it reasonable to use the name the way they use it. I grabbed the latest stable version from here. Inside there is a folder called RGraph – and inside that is a folder called libraries – I grabbed the contents of that folder and put it inside my /public/RGraph folder. It may be there is a use for other stuff in there – but for now that’s all I’ve taken.
So – then I dropped in a template – made it 6*6 and inside that template I put this lot – code shown below.
Now, if you don’t like my colours – change them. You can change just about anything including the size but you may need to adjust the font size if you do that. Experiment!
To change the two pointers – which I’ve chosen to call temperature and humidity – you might use them for petrol and oil – or whatever….I simply pass MSG as is common in Node-Red – but not msg.template – instead msg.temperature and msg.humidity – you can call them whatever you like.
The point of this is not to demonstrate my crap taste in colours – once you follow what I’ve done here – that entire, massive library of CANVAS-related gauges and charts is yours for the taking! You can make the gauges interactive – but as I had two, not one pointers in this example, I skipped that. Details are in the extensive RGraph documentation. Copy me and drop them an encouraging lines to say MORE IOT PLEASE!!
Oh and if you don’t like animation – where I say “grow” say “draw”.
(As an aside, I got this working today as well – https://www.codeproject.com/Articles/304874/HTML-Canvas-Aqua-Gauge) very pretty but doesn’t scale well.
Prerequisites: Far too often in blogs like this we “assume” that everyone is keeping up – if not – may I suggest a quick look at this page I put up specifically to give a little background – which might help explain this article.
[pcsh lang=”js” tab_size=”4″ message=”” hl_lines=”” provider=”manual”]
<script src="/myjs/RGraph/RGraph.common.core.js" ></script>
<script src="/myjs/RGraph/RGraph.gauge.js" ></script>
<script language="javascript" type="text/javascript">
(function(scope){
scope.$watch('msg', function(msg) {
gauge3.value=[msg.temperature,msg.humidity];
gauge3.grow();
});
})(scope);
var gauge3 = new RGraph.Gauge({
id: 'cvs',
min: 0,
max: 100,
value: [23,60],
options: {
titleTop: 'Temperature',
titleTopSize: '16',
titleTopFont: 'Impact',
titleTopColor: '#ff8888',
titleTopPos: 0.25,
titleBottom: 'Humidity',
titleBottomSize: '14',
titleBottomFont: 'Impact',
titleBottomColor: '#8888ff',
titleBottomPos: 0.3,
backgroundColor: 'black',
backgroundGradient: true,
centerpinColor: '#666',
needleSize: [null, 50],
needleColors: ['Gradient(transparent:yellow:orange:#ff8888:#ff8888)',
'Gradient(transparent:cyan:green:blue:blue)'],
textColor: 'white',
tickmarksBigColor: 'white',
tickmarksMediumColor: 'white',
tickmarksSmallColor: 'white',
borderWidth: 1,
borderOuter: '#666',
borderInner: '#3333',
colorsRanges: [
[0,10,'rgba(0,0,255,0.6)'],
[10,20,'rgba(0,128,255,0.6)'],
[20,30,'rgba(0,255,255,0.6)'],
[30,40,'rgba(0,255,128,0.6)'],
[40,50,'rgba(0,255,0,0.6)'],
[50,60,'rgba(128,255,0,0.6)'],
[60,70,'rgba(255,255,0,0.6)'],
[70,80,'rgba(255,128,0,0.6)'],
[80,90,'rgba(255,64,0,0.6)'],
[90,100,'rgba(255,0,0,1']
],
textAccessible: true
}
});
gauge3.grow();
</script>
<canvas id="cvs" width="300" height="300">[No canvas support]</canvas>
[/pcsh]
Thanks Pete.
Hi Pete,
is it possible to get a copy/snippet of your ‘settings.js’ file. I am still trying to get to grips with how node-red works and an example would help me to understand this post a much better
Thanks
Terry
I don’t know how much good this will do you but here it is..
/**
* 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”);
var i2c = require(“i2c-bus”);
var mySettings;
try {
mySettings = require(“/home/pi/.node-red/redvars.js”);
} catch(err) {
mySettings = {};
}
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,
// 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_.json
flowFile: ‘flows.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: “a-secret-key”,
// By default, all user data is stored in the Node-RED install directory. To
// use a different location, the following property can be used
//userDir: ‘/home/nol/.node-red/’,
// Node-RED scans the `nodes` directory in the install directory to find nodes.
// The following property can be used to specify an additional directory to scan.
//nodesDir: ‘/home/nol/.node-red/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: ‘/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 specifiy a different root path. If set to false, this is
// disabled.
//httpNodeRoot: ‘/red-nodes’,
// 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: ‘/home/nol/node-red-static/’,
// 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 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
//},
// Anything in this hash is globally available to all functions.
// It is accessed as context.global.
// eg:
// // functionGlobalContext: { os:require(‘os’) }
// can be accessed in a function block as:
// context.global.os
// functionGlobalContext: {
// os:require(‘os’),
// jfive:require(“johnny-five”),
// j5board:require(“johnny-five”).Board({repl:false})
// },
// 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
}
}
,
httpStatic: ‘/home/pi/.node-red/public’,
functionGlobalContext: {
os:require(‘os’),
moment:require(‘moment’),
fs:require(‘fs’),
i2c:require(‘i2c-bus’),
mySettings:mySettings
},
adminAuth: {
type: “credentials”,
users: [{
username: “admin”,
password: “$2a$08$inogsZ/vlrK6bFuhrI6KjOWmNlFiDDX5VlRA4AUWOhnty/fakpW2G”,
permissions: “*”
}]
},
httpNodeAuth: {user:”user”, pass:”$2a$08$QUcnR199toq/9eJMs4ZjeeAzeQ/N2AnyKCKN03pZWUEp62I6d1hDK”},
editorTheme: {
page: {
css: “/home/pi/.node-red/midnight.css”,
scripts: “/home/pi/.node-red/theme-tomorrow.js”
}
}
}
Hi Pete!
Really great work! Just a quick question: would it be possible to have the numeric value of the temperature instead of the “Humidity” sign on the bottom side of the gauge? And how would I have it updated each time the gauge receive a message?
Thank you so much for your work!
Roberto (from Italy)
Hi Pete,
I saw this page – and since you seem to be liking RGraph I wondered if you wanted to post an update about it. Since January I’ve been adding more SVG libraries which is now up to 13 base charts types. A few more variations can be be made – for example the Horizontal Bar chart can be customised to make a Horizontal Progress bar and similarly the vertical Bar chart can be customised to make Vertical Progress Bar.
There’s also a Semi-circular Progress in both SVG and also canvas flavours.
Going forward I’ll (eventually) add more SVG chart types – including a Gauge chart (like the canvas Gauge chart)
Cheers!
Richard
Hello
thanks for the great manuals you give us here. I work now with Raspberry Pie & MQTT & Node Red. I make it like you write here but i dont see anything in the Dashboard.
I change the variable “httpStatic” in the settings.js
What can i do?
best regards
Werner
Did you PUT anything in the dashboard?
Suggest a trip over to the Node-Red site where they have more info on the settings.js file – and also the Google Groups discussion area where there is a specific Node-Red Dashboard area.
Yes, an other html example which only show text works fine
i google so much, but i dont find any solution
you write that the variable in settings.js must be changed for the folder where rgraph is saved. Was it the right variable i have changed?
Hi Pete
I note that the section relating to getting values back from RGraph has been removed so maybe you have resolved the issue but just in case here is how I did it.
I added a line to the options of the object which created a listener namely
eventsClick: myClick,
I then added the function
function myClick (e)
{
var obj = e.target.__object__;
alert(obj.getValue(e));
}
Obviously I have done this as an alert but I am sure you can adapt this to a send easily enough
Steve