mirror of
https://github.com/node-red/node-red-nodes.git
synced 2023-10-10 13:36:58 +02:00
Add initial Sense HAT Input node
This commit is contained in:
parent
cd047ceab1
commit
c3b08270ad
177
hardware/sensehat/LICENSE
Normal file
177
hardware/sensehat/LICENSE
Normal file
@ -0,0 +1,177 @@
|
||||
|
||||
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
|
65
hardware/sensehat/README.md
Normal file
65
hardware/sensehat/README.md
Normal file
@ -0,0 +1,65 @@
|
||||
node-red-node-pi-sense-hat
|
||||
==========================
|
||||
|
||||
A <a href="http://nodered.org" target="_new">Node-RED</a> node to interact with
|
||||
a Raspberry Pi Sense HAT.
|
||||
|
||||
## Pre-requisites
|
||||
|
||||
The Sense HAT python drivers need to be installed manually:
|
||||
|
||||
```
|
||||
sudo apt-get update
|
||||
sudo apt-get install sense-hat
|
||||
sudo pip-3.2 install pillow
|
||||
```
|
||||
|
||||
See the <a href="http://pythonhosted.org/sense-hat/" target="_new">driver documentation</a>
|
||||
for more information.
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
Run the following command in your Node-RED user directory (typically `~/.node-red`):
|
||||
|
||||
npm install node-red-node-pi-sense-hat
|
||||
|
||||
## Usage
|
||||
|
||||
### Input Node
|
||||
|
||||
This node sends readings from the various sensors on the Sense HAT, grouped into three sets; motion events, environment events and joystick events.
|
||||
|
||||
#### Motion events
|
||||
|
||||
Motion events include readings from the accelerometer, gyroscope and magnetometer,
|
||||
as well as the current compass heading. They are sent at a rate of approximately 10
|
||||
per second. The `topic` is set to `motion` and the `payload` is an object with the
|
||||
following values:
|
||||
|
||||
- `acceleration.x/y/z` : the acceleration intensity in Gs
|
||||
-`gyroscope.x/y/z` : the rotational intensity in radians/s
|
||||
-`orientation.roll/pitch/yaw` : the angle of the axis in degrees
|
||||
-`compass` : the direction of North in degrees
|
||||
|
||||
#### Environment events
|
||||
|
||||
Environment events include readings from the temperature, humidity and pressure
|
||||
sensors. They are sent at a rate of approximately 1 per second. The `topic`
|
||||
is set to `environment` and the `payload` is an object
|
||||
with the following values:
|
||||
|
||||
-`temperature` : degrees Celsius
|
||||
-`humidity` : percentage of relative humidity
|
||||
-`pressure` : Millibars
|
||||
|
||||
#### Joystick events
|
||||
|
||||
Joystick events are sent when the Sense HAT joystick is interacted with. The
|
||||
`topic` is set to `joystick` and the `payload` is an object with the following values:
|
||||
|
||||
-`key` : one of `UP`, `DOWN`, `LEFT`, `RIGHT`, `ENTER`
|
||||
-`state` : the state of the key:
|
||||
-`0` : the key has been released
|
||||
-`1` : the key has been pressed
|
||||
-`2` : the key is being held down
|
24
hardware/sensehat/package.json
Normal file
24
hardware/sensehat/package.json
Normal file
@ -0,0 +1,24 @@
|
||||
{
|
||||
"name" : "node-red-node-pi-sense-hat",
|
||||
"version" : "0.0.1",
|
||||
"description" : "A Node-RED node to interact with a Raspberry Pi Sense HAT",
|
||||
"repository" : {
|
||||
"type":"git",
|
||||
"url":"https://github.com/node-red/node-red-nodes/tree/master/hardware/sensehat"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"keywords": [ "node-red", "sensehat", "astropi" ],
|
||||
"node-red" : {
|
||||
"nodes" : {
|
||||
"sensehat": "sensehat.js"
|
||||
}
|
||||
},
|
||||
"scripts" : {
|
||||
"postinstall" : "scripts/checklib.sh"
|
||||
},
|
||||
"author": {
|
||||
"name": "Nick O'Leary",
|
||||
"email": "nick.oleary@gmail.com",
|
||||
"url": "http://nodered.org"
|
||||
}
|
||||
}
|
14
hardware/sensehat/scripts/checklib.sh
Executable file
14
hardware/sensehat/scripts/checklib.sh
Executable file
@ -0,0 +1,14 @@
|
||||
#!/bin/bash
|
||||
|
||||
python -c "import sense_hat" 2> /dev/null
|
||||
|
||||
if [ $? -ne 0 ]
|
||||
then
|
||||
echo "WARNING : Can't find Sense HAT python library"
|
||||
echo "WARNING : Please install using the following commands"
|
||||
echo "WARNING : sudo apt-get update"
|
||||
echo "WARNING : sudo apt-get install sense-hat"
|
||||
echo "WARNING : sudo pip-3.2 install pillow"
|
||||
else
|
||||
echo "Sense HAT python library is installed"
|
||||
fi
|
17
hardware/sensehat/sensehat
Executable file
17
hardware/sensehat/sensehat
Executable file
@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Copyright 2016 IBM Corp.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
BASEDIR=$(dirname $0)
|
||||
sudo python -u $BASEDIR/sensehat.py $@
|
103
hardware/sensehat/sensehat.html
Normal file
103
hardware/sensehat/sensehat.html
Normal file
@ -0,0 +1,103 @@
|
||||
<!--
|
||||
Copyright 2016 IBM Corp.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-->
|
||||
|
||||
<script type="text/x-red" data-template-name="rpi-sensehat in">
|
||||
<div class="form-row">
|
||||
<label><i class="fa fa-arrow-right"></i> Outputs</label>
|
||||
<label style="width: auto" for="node-input-motion"><input style="vertical-align: top; width: auto; margin-right: 5px;" type="checkbox" id="node-input-motion"> Motion events</label>
|
||||
<div style="padding-left: 125px; margin-top: -5px; color: #bbb;">accelerometer, gyroscope, magnetometer, compass</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label></label>
|
||||
<label style="width: auto" for="node-input-env"><input style="vertical-align: top; width: auto; margin-right: 5px;" type="checkbox" id="node-input-env"> Environment events</label>
|
||||
<div style="padding-left: 125px; margin-top: -5px; color: #bbb;">temperature, humidity, pressure</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label></label>
|
||||
<label style="width: auto" for="node-input-stick"><input style="vertical-align: top; width: auto; margin-right: 5px;" type="checkbox" id="node-input-stick"> Joystick events</label>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
|
||||
<input type="text" id="node-input-name">
|
||||
</div>
|
||||
</script>
|
||||
|
||||
<script type="text/x-red" data-help-name="rpi-sensehat in">
|
||||
<p>Raspberry Pi Sense HAT input node.</p>
|
||||
<p>This node sends readings from the various sensors on the Sense HAT,
|
||||
grouped into three sets; motion events, environment events and joystick events.</p>
|
||||
<p><b>Motion events</b></p>
|
||||
<p>Motion events include readings from the accelerometer, gyroscope and magnetometer,
|
||||
as well as the current compass heading. They are sent at a rate of approximately 10
|
||||
per second. The <code>topic</code> is set to <code>motion</code> and the
|
||||
<code>payload</code> is an object with the following values:</p>
|
||||
<ul>
|
||||
<li><code>acceleration.x/y/z</code> : the acceleration intensity in Gs</li>
|
||||
<li><code>gyroscope.x/y/z</code> : the rotational intensity in radians/s</li>
|
||||
<li><code>orientation.roll/pitch/yaw</code> : the angle of the axis in degrees</li>
|
||||
<li><code>compass</code> : the direction of North in degrees</li>
|
||||
</ul>
|
||||
<p><b>Environment events</b></p>
|
||||
<p>Environment events include readings from the temperature, humidity and pressure
|
||||
sensors. They are sent at a rate of approximately 1 per second. The <code>topic</code>
|
||||
is set to <code>environment</code> and the <code>payload</code> is an object
|
||||
with the following values:</p>
|
||||
<ul>
|
||||
<li><code>temperature</code> : degrees Celsius</li>
|
||||
<li><code>humidity</code> : percentage of relative humidity</li>
|
||||
<li><code>pressure</code> : Millibars</li>
|
||||
</ul>
|
||||
<p><b>Joystick events</b></p>
|
||||
<p>Joystick events are sent when the Sense HAT joystick is interacted with. The
|
||||
<code>topic</code> is set to <code>joystick</code> and the <code>payload</code>
|
||||
is an object with the following values:</p>
|
||||
<ul>
|
||||
<li><code>key</code> : one of <code>UP</code>, <code>DOWN</code>, <code>LEFT</code>, <code>RIGHT</code>, <code>ENTER</code></li>
|
||||
<li><code>state</code> : the state of the key:
|
||||
<ul>
|
||||
<li><code>0</code> : the key has been released</li>
|
||||
<li><code>1</code> : the key has been pressed</li>
|
||||
<li><code>2</code> : the key is being held down</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
<script type="text/javascript">
|
||||
RED.nodes.registerType('rpi-sensehat in',{
|
||||
category: 'Raspberry Pi',
|
||||
paletteLabel: "Sense HAT",
|
||||
color:"#c6dbef",
|
||||
defaults: {
|
||||
name: { value:"" },
|
||||
motion: { value: true },
|
||||
env: { value: true },
|
||||
stick: { value: true }
|
||||
},
|
||||
inputs:0,
|
||||
outputs:1,
|
||||
icon: "rpi.png",
|
||||
label: function() {
|
||||
return this.name||"Sense HAT";
|
||||
},
|
||||
labelStyle: function() {
|
||||
return this.name?"node_label_italic":"";
|
||||
}
|
||||
});
|
||||
</script>
|
218
hardware/sensehat/sensehat.js
Normal file
218
hardware/sensehat/sensehat.js
Normal file
@ -0,0 +1,218 @@
|
||||
/**
|
||||
* Copyright 2016 IBM Corp.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
**/
|
||||
|
||||
module.exports = function(RED) {
|
||||
"use strict";
|
||||
var fs = require('fs');
|
||||
var spawn = require('child_process').spawn;
|
||||
|
||||
var hatCommand = __dirname+'/sensehat';
|
||||
|
||||
if ( !(1 & parseInt ((fs.statSync(hatCommand).mode & parseInt ("777", 8)).toString (8)[0]) )) {
|
||||
RED.log.error(hatCommand + " command is not executable");
|
||||
throw "Error : "+RED._("rpi-gpio.errors.mustbeexecutable");
|
||||
}
|
||||
|
||||
// the magic to make python print stuff immediately
|
||||
process.env.PYTHONUNBUFFERED = 1;
|
||||
|
||||
// Xaccel.x,y,z,gyro.x,y,z,orientation.roll,pitch,yaw,compass
|
||||
var HF_RE = /^X(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+)$/;
|
||||
// Ytemperature,humidity,pressure
|
||||
var LF_RE = /^Y(.+),(.+),(.+)$/;
|
||||
// K[U|L|R|D|E][0|1|2] - joystick event: direction,state
|
||||
var KEY_RE = /^K(.)(.)$/;
|
||||
var KEY_MAP = {
|
||||
"U":"UP",
|
||||
"D":"DOWN",
|
||||
"L":"LEFT",
|
||||
"R":"RIGHT",
|
||||
"E":"ENTER"
|
||||
};
|
||||
|
||||
var HAT = (function() {
|
||||
var hat = null;
|
||||
var onclose = null;
|
||||
var users = [];
|
||||
var motionUsers = 0;
|
||||
var envUsers = 0;
|
||||
var reconnectTimer = null;
|
||||
|
||||
var connect = function() {
|
||||
var buffer = "";
|
||||
hat = spawn(hatCommand);
|
||||
hat.stdout.on('data', function (data) {
|
||||
buffer += data.toString();
|
||||
var lines = buffer.split("\n");
|
||||
if (lines.length == 1) {
|
||||
return;
|
||||
}
|
||||
buffer = lines.pop();
|
||||
var m,msg;
|
||||
for (var i=0;i<lines.length;i++) {
|
||||
var line = lines[i];
|
||||
msg = null;
|
||||
if ((m = KEY_RE.exec(line)) !== null) {
|
||||
msg = {
|
||||
topic: "joystick",
|
||||
payload: {key: KEY_MAP[m[1]], state: Number(m[2])}
|
||||
}
|
||||
} else if ((m = LF_RE.exec(line)) !== null) {
|
||||
msg = {
|
||||
topic: "environment",
|
||||
payload: {temperature: Number(m[1]), humidity: Number(m[2]), pressure: Number(m[3])}
|
||||
}
|
||||
} else if ((m = HF_RE.exec(line)) !== null) {
|
||||
// Xaccel.x,y,z,gyro.x,y,z,orientation.roll,pitch,yaw,compass
|
||||
msg = {
|
||||
topic: "motion",
|
||||
payload: {
|
||||
acceleration: {
|
||||
x: Number(m[1]),
|
||||
y: Number(m[2]),
|
||||
z: Number(m[3])
|
||||
},
|
||||
gyroscope: {
|
||||
x: Number(m[4]),
|
||||
y: Number(m[5]),
|
||||
z: Number(m[6])
|
||||
},
|
||||
orientation: {
|
||||
roll: Number(m[7]),
|
||||
pitch: Number(m[8]),
|
||||
yaw: Number(m[9])
|
||||
},
|
||||
compass: Number(m[10])
|
||||
}
|
||||
}
|
||||
}
|
||||
if (msg && !onclose) {
|
||||
for (var j=0;j<users.length;j++) {
|
||||
var node = users[j];
|
||||
if (node.motion && msg.topic === "motion") {
|
||||
node.send(msg);
|
||||
} else if (node.env && msg.topic === 'environment') {
|
||||
node.send(msg);
|
||||
} else if (node.stick && msg.topic === 'joystick') {
|
||||
node.send(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
hat.stderr.on('data', function (data) {
|
||||
if (RED.settings.verbose) { RED.log.error("err: "+data+" :"); }
|
||||
});
|
||||
|
||||
hat.on('close', function (code) {
|
||||
hat = null;
|
||||
if (RED.settings.verbose) { RED.log.info(RED._("rpi-gpio.status.closed")); }
|
||||
if (onclose) {
|
||||
onclose();
|
||||
onclose = null;
|
||||
} else {
|
||||
reconnectTimer = setTimeout(function() {
|
||||
connect();
|
||||
},5000);
|
||||
}
|
||||
});
|
||||
|
||||
hat.on('error', function (err) {
|
||||
if (err.errno === "ENOENT") { RED.log.error(RED._("rpi-gpio.errors.commandnotfound")); }
|
||||
else if (err.errno === "EACCES") { RED.log.error(RED._("rpi-gpio.errors.commandnotexecutable")); }
|
||||
else { RED.log.error(RED._("rpi-gpio.errors.error")+': ' + err.errno); }
|
||||
});
|
||||
|
||||
if (motionUsers > 0) {
|
||||
hat.stdin.write('X1\n');
|
||||
}
|
||||
if (envUsers > 0) {
|
||||
hat.stdin.write('Y1\n');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
var disconnect = function(done) {
|
||||
if (hat !== null) {
|
||||
onclose = done;
|
||||
hat.kill('SIGKILL');
|
||||
hat = null;
|
||||
}
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
open: function(node) {
|
||||
if (!hat) {
|
||||
connect();
|
||||
}
|
||||
|
||||
if (node.motion) {
|
||||
if (motionUsers === 0) {
|
||||
hat.stdin.write('X1\n');
|
||||
}
|
||||
motionUsers++;
|
||||
}
|
||||
if (node.env) {
|
||||
if (envUsers === 0) {
|
||||
hat.stdin.write('Y1\n');
|
||||
}
|
||||
envUsers++;
|
||||
}
|
||||
users.push(node);
|
||||
},
|
||||
close: function(node,done) {
|
||||
if (node.motion) {
|
||||
motionUsers--;
|
||||
if (motionUsers === 0) {
|
||||
hat.stdin.write('X0\n');
|
||||
}
|
||||
}
|
||||
if (node.env) {
|
||||
envUsers--;
|
||||
if (envUsers === 0) {
|
||||
hat.stdin.write('Y0\n');
|
||||
}
|
||||
}
|
||||
users.splice(users.indexOf(node),1);
|
||||
if (users.length === 0) {
|
||||
disconnect(done);
|
||||
} else {
|
||||
done();
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
function SenseHatInNode(n) {
|
||||
RED.nodes.createNode(this,n);
|
||||
this.motion = n.motion;
|
||||
this.env = n.env;
|
||||
this.stick = n.stick;
|
||||
var node = this;
|
||||
HAT.open(this);
|
||||
|
||||
node.on("close", function(done) {
|
||||
HAT.close(this,done);
|
||||
});
|
||||
}
|
||||
RED.nodes.registerType("rpi-sensehat in",SenseHatInNode);
|
||||
}
|
160
hardware/sensehat/sensehat.py
Normal file
160
hardware/sensehat/sensehat.py
Normal file
@ -0,0 +1,160 @@
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Copyright 2016 IBM Corp.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# Commands:
|
||||
# C[R,G,B] - clear to colour (or off if no RGB provided)
|
||||
# R[rot] - rotate by rot (0,90,180,270)
|
||||
# P[x,y,R,G,B]+ - set individual pixel(s) to a colour
|
||||
# T[R,G,B:]Message - scroll a message (nb: if message contains ':' it must be prefixed with ':')
|
||||
# F[H|V] - flip horizontal|vertical
|
||||
# X[0|1] - high frequency reporting (accel/gyro/orientation/compass) off|on
|
||||
# Y[0|1] - low frequency reporting (temperature/humidity/pressure) off|on
|
||||
#
|
||||
# Outputs:
|
||||
# Xaccel.x,y,z,gyro.x,y,z,orientation.roll,pitch,yaw,compass
|
||||
# Ytemperature,humidity,pressure
|
||||
# K[U|L|R|D|E][0|1|2] - joystick event: direction,state
|
||||
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import glob
|
||||
import time
|
||||
import errno
|
||||
import select
|
||||
import struct
|
||||
|
||||
from sense_hat import SenseHat
|
||||
|
||||
EVENT_FORMAT = 'llHHI'
|
||||
EVENT_SIZE = struct.calcsize(EVENT_FORMAT)
|
||||
EVENT_NAMES = {103:'U',105:'L',106:'R',108:'D',28:'E'}
|
||||
|
||||
def get_stick():
|
||||
for evdev in glob.glob('/sys/class/input/event*'):
|
||||
try:
|
||||
with io.open(os.path.join(evdev, 'device', 'name'), 'r') as f:
|
||||
if f.read().strip() == 'Raspberry Pi Sense HAT Joystick':
|
||||
return os.path.join('/dev', 'input', os.path.basename(evdev))
|
||||
except IOError as e:
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
raise RuntimeError('unable to locate SenseHAT joystick device')
|
||||
|
||||
|
||||
stick_file = io.open(get_stick(),'rb')
|
||||
|
||||
SH = SenseHat()
|
||||
SH.set_rotation(0)
|
||||
SH.clear()
|
||||
|
||||
files = [sys.stdin,stick_file]
|
||||
last_hf_time = time.time()
|
||||
last_lf_time = time.time()
|
||||
|
||||
hf_interval = 0.09 # Approx 10/s
|
||||
lf_interval = 1
|
||||
|
||||
hf_enabled = False
|
||||
lf_enabled = False
|
||||
|
||||
|
||||
def process_command(data):
|
||||
global hf_enabled, lf_enabled
|
||||
if data[0] == "R":
|
||||
SH.set_rotation(float(data[1:]))
|
||||
elif data[0] == "C":
|
||||
data = data[1:].strip()
|
||||
if len(data) > 0:
|
||||
s = data.split(",")
|
||||
col = (int(s[0]),int(s[1]),int(s[2]))
|
||||
else:
|
||||
col = (0,0,0)
|
||||
SH.clear(col)
|
||||
elif data[0] == "P":
|
||||
data = data[1:].strip()
|
||||
s = data.split(',')
|
||||
for p in range(0,len(s),5):
|
||||
SH.set_pixel(int(s[p]),int(s[p+1]),int(s[p+2]),int(s[p+3]),int(s[p+4]))
|
||||
elif data[0] == "T":
|
||||
data = data[1:].strip()
|
||||
col = (255,255,255)
|
||||
s = data.split(':',1)
|
||||
if len(s) == 2:
|
||||
data = s[1]
|
||||
if len(s[0]) > 0:
|
||||
c = s[0].split(",")
|
||||
col = (int(c[0]),int(c[1]),int(c[2]))
|
||||
SH.show_message(data,text_colour=col)
|
||||
elif data[0] == "F":
|
||||
if data[1] == "H":
|
||||
SH.flip_h()
|
||||
elif data[1] == "V":
|
||||
SH.flip_v()
|
||||
elif data[0] == "X":
|
||||
if data[1] == '0':
|
||||
hf_enabled = False
|
||||
else:
|
||||
hf_enabled = True
|
||||
elif data[0] == "Y":
|
||||
if data[1] == '0':
|
||||
lf_enabled = False
|
||||
else:
|
||||
lf_enabled = True
|
||||
|
||||
def idle_work():
|
||||
global last_hf_time, last_lf_time
|
||||
now = time.time()
|
||||
if hf_enabled and (now-last_hf_time > hf_interval):
|
||||
orientation = SH.get_orientation()
|
||||
compass = SH.get_compass()
|
||||
gyro = SH.get_gyroscope_raw()
|
||||
accel = SH.get_accelerometer_raw()
|
||||
|
||||
print("X%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.4f,%0.0f"%(accel['x'],accel['y'],accel['z'],gyro['x'],gyro['y'],gyro['z'],orientation['roll'],orientation['pitch'],orientation['yaw'],compass))
|
||||
last_hf_time = now
|
||||
if lf_enabled and (now-last_lf_time > lf_interval):
|
||||
temperature = SH.get_temperature();
|
||||
humidity = SH.get_humidity();
|
||||
pressure = SH.get_pressure();
|
||||
print("Y%0.2f,%0.2f,%0.2f"%(temperature,humidity,pressure))
|
||||
last_lf_time = now
|
||||
|
||||
def process_joystick():
|
||||
event = stick_file.read(EVENT_SIZE)
|
||||
(tv_sec, tv_usec, type, code, value) = struct.unpack(EVENT_FORMAT, event)
|
||||
if type == 0x01:
|
||||
print ("K%s%s"%(EVENT_NAMES[code],value))
|
||||
|
||||
def main_loop():
|
||||
# while still waiting for input on at least one file
|
||||
while files:
|
||||
ready = select.select(files, [], [], 0.01)[0]
|
||||
if not ready:
|
||||
idle_work()
|
||||
else:
|
||||
for file in ready:
|
||||
if file == sys.stdin:
|
||||
line = file.readline()
|
||||
if not line: # EOF, remove file from input list
|
||||
sys.exit(0)
|
||||
elif line.rstrip(): # optional: skipping empty lines
|
||||
process_command(line)
|
||||
else:
|
||||
process_joystick()
|
||||
|
||||
try:
|
||||
main_loop()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
Loading…
x
Reference in New Issue
Block a user