
npm install moment iota.lib.js
/*
Author: Robert Lie (mobilefish.com)
The mam_publish.js file publishes random generated numbers on the tangle using MAM.
This file will work on a computer or Raspberry Pi.
The published data can be viewed using the mam_receive.js file or
https://www.mobilefish.com/services/cryptocurrency/mam.html (Select option: Data receiver)
Usage:
1) You can change the default settings: MODE, SIDEKEY, SECURITYLEVEL or TIMEINTERVAL
If you do, make the same changes in mam_receive.js file.
2) Start the app: node mam_publish.js
More information:
https://www.mobilefish.com/developer/iota/iota_quickguide_raspi_mam.html
*/
const Mam = require('./lib/mam.client.js');
const IOTA = require('iota.lib.js');
const moment = require('moment');
const iota = new IOTA({ provider: 'https://node.deviceproof.org' });
const MODE = 'restricted'; // public, private or restricted
const SIDEKEY = 'mysecret'; // Enter only ASCII characters. Used only in restricted mode
const SECURITYLEVEL = 3; // 1, 2 or 3
const TIMEINTERVAL = 30; // seconds
// Initialise MAM State
let mamState = Mam.init(iota, undefined, SECURITYLEVEL);
// Set channel mode
if (MODE == 'restricted') {
const key = iota.utils.toTrytes(SIDEKEY);
mamState = Mam.changeMode(mamState, MODE, key);
} else {
mamState = Mam.changeMode(mamState, MODE);
}
// Publish data to the tangle
const publish = async function(packet) {
// Create MAM Payload
const trytes = iota.utils.toTrytes(JSON.stringify(packet));
const message = Mam.create(mamState, trytes);
// Save new mamState
mamState = message.state;
console.log('Root: ', message.root);
console.log('Address: ', message.address);
// Attach the payload.
await Mam.attach(message.payload, message.address);
return message.root;
}
const generateJSON = function() {
// Generate some random numbers simulating sensor data
const data = Math.floor((Math.random()*89)+10);
const dateTime = moment().utc().format('DD/MM/YYYY hh:mm:ss');
const json = {"data": data, "dateTime": dateTime};
return json;
}
const executeDataPublishing = async function() {
const json = generateJSON();
console.log("json=",json);
const root = await publish(json);
console.log(`dateTime: ${json.dateTime}, data: ${json.data}, root: ${root}`);
}
// Start it immediately
executeDataPublishing();
setInterval(executeDataPublishing, TIMEINTERVAL*1000);
/*eslint no-console: 0, no-unused-vars: 0, no-undef:0, no-process-exit:0*/
/*eslint-env node, es6 */
"use strict";
const port = process.env.PORT || 3000;
const server = require("http").createServer();
const cds = require("@sap/cds");
//Initialize Express App for XSA UAA and HDBEXT Middleware
const xsenv = require("@sap/xsenv");
const passport = require("passport");
const xssec = require("@sap/xssec");
const xsHDBConn = require("@sap/hdbext");
const express = require("express");
global.__base = __dirname + "/";
//Iota
const Mam = require('./lib/mam.client.js');
const IOTA = require('iota.lib.js');
const iota = new IOTA({
provider: 'https://node.deviceproof.org'
});
const MODE = 'restricted'; // public, private or restricted
const SIDEKEY = 'mysecret'; // Enter only ASCII characters. Used only in restricted mode
let root;
let key;
let Socket = null;
//logging
var logging = require("@sap/logging");
var appContext = logging.createAppContext();
//Initialize Express App for XS UAA and HDBEXT Middleware
var app = express();
//Compression
app.use(require("compression")({
threshold: "1b"
}));
//Helmet for Security Policy Headers
const helmet = require("helmet");
app.use(helmet());
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "sapui5.hana.ondemand.com"],
scriptSrc: ["'self'", "sapui5.hana.ondemand.com"]
}
}));
// Sets "Referrer-Policy: no-referrer".
app.use(helmet.referrerPolicy({
policy: "no-referrer"
}));
passport.use("JWT", new xssec.JWTStrategy(xsenv.getServices({
uaa: {
tag: "xsuaa"
}
}).uaa));
app.use(logging.middleware({
appContext: appContext,
logNetwork: true
}));
app.use(passport.initialize());
app.use(
passport.authenticate("JWT", {
session: false
})
);
// Initialise MAM State
let mamState = Mam.init(iota);
// Set channel mode
if (MODE == 'restricted') {
key = iota.utils.toTrytes(SIDEKEY);
mamState = Mam.changeMode(mamState, MODE, key);
} else {
mamState = Mam.changeMode(mamState, MODE);
}
// Receive data from the tangle
const executeDataRetrieval = async function(rootVal, keyVal) {
let resp = await Mam.fetch(rootVal, MODE, keyVal, function(data) {
let json = JSON.parse(iota.utils.fromTrytes(data));
Socket.emit('client_data', {'dateTime': json.dateTime, 'data': json.data})
console.log(`dateTime: ${json.dateTime}, data: ${json.data}`);
});
executeDataRetrieval(resp.nextRoot, keyVal);
}
app.get("/node", (req, res) => {
var root = req.query.root;
console.log(root);
executeDataRetrieval(root, key);
res.send("Use the root:" + root);
});
//Start the Server
server.on("request", app);
// use socket.io
var io = require('socket.io').listen(server);
// define interactions with client
io.sockets.on('connection', function (socket) {
Socket = socket;
});
//Start the Server
server.listen(port, function () {
console.info(`HTTP Server: ${server.address().port}`);
});
{
"name": "serve",
"description": "Generated from ../package.json, do not change!",
"version": "1.0.0",
"dependencies": {
"@sap/cds": "^3.10.0",
"express": "^4.17.1",
"@sap/xssec": "^2.1.17",
"@sap/xsenv": "^2.0.0",
"hdb": "^0.17.0",
"@sap/hdbext": "^6.0.0",
"@sap/hana-client": "^2.4.139",
"@sap/textbundle": "latest",
"@sap/logging": "^5.0.1",
"@sap/audit-logging": "^3.0.0",
"nodemailer": "^6.2.1",
"passport": "~0.4.0",
"async": "^3.0.1",
"ws": "^7.0.0",
"accept-language-parser": "latest",
"node-xlsx": "^0.15.0",
"node-zip": "~1.1.1",
"xmldoc": "~1.1.2",
"winston": "^3.2.1",
"body-parser": "^1.19.0",
"elementtree": "latest",
"then-request": "latest",
"compression": "~1.7",
"helmet": "^3.18.0",
"iota.lib.js": "^0.4.7",
"socket.io": "^2.2.0",
"socket.io-client": "^2.2.0"
},
"engines": {
"node": "^8.9",
"npm": "^6"
},
"devDependencies": {},
"scripts": {
"postinstall": "cds build/all --project .. --clean",
"start": "node server.js"
},
"i18n": {
"folders": [
"_i18n"
]
},
"cds": {
"data": {
"driver": "hana"
}
}
}
<html>
<title>IOTA Tangle with SAP HANA XSA and Cloud Analytics</title>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
function bindEvent(element, eventName, eventHandler) {
if (element.addEventListener){
element.addEventListener(eventName, eventHandler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + eventName, eventHandler);
}
}
var socket = io.connect();
var iframeSource = 'REPLACE_WITH_SAP_ANALYTICS_CLOUD_APP_URL';
// Create the iframe
var iframe = document.createElement('iframe');
iframe.setAttribute('src', iframeSource);
iframe.setAttribute('id', 'the_iframe');
iframe.setAttribute('frameborder', 0);
iframe.setAttribute('style', 'overflow: hidden; height: 100%; width: 100%; position: absolute;');
document.body.appendChild(iframe);
// Send a message to the child iframe
var iframeEl = document.getElementById('the_iframe');
// Send a message to the child iframe
var sendMessage = function(msg) {
// Make sure you are sending a string, and to stringify JSON
iframeEl.contentWindow.postMessage(msg, '*');
};
// Listen to message from child window
bindEvent(window, 'message', function (e) {
console.log(e.data);
});
socket.on('client_data', function(data){
console.log(data.data);
var temperature = data.data.toString();
sendMessage(temperature);
});
</script>
</body>
</html>
{
"welcomeFile": "index.html",
"authenticationMethod": "route",
"routes": [{
"source": "/node(.*)",
"destination": "srv_api",
"csrfProtection": true,
"authenticationType": "none"
},{
"source": "/socket.io(.*)",
"destination": "srv_api",
"csrfProtection": true,
"authenticationType": "none"
}]
}
ID: ziota
_schema-version: "2.1"
version: 0.0.1
modules:
- name: srv
type: nodejs
path: srv
parameters:
memory: 512M
disk-quota: 256M
provides:
- name: srv_api
properties:
url: '${default-url}'
requires:
- name: zearnpfe-uaa
- name: web
type: html5
path: web
requires:
- name: zearnpfe-uaa
- name: srv_api
group: destinations
properties:
name: srv_api
url: '~{url}'
forwardAuthToken: true
resources:
- name: zearnpfe-uaa
type: com.sap.xs.uaa-space
parameters:
config-path: ./xs-security.json
{
"xsappname": "ziota",
"scopes": [{
"name": "$XSAPPNAME.Display",
"description": "display"
}, {
"name": "$XSAPPNAME.Create",
"description": "create"
}, {
"name": "$XSAPPNAME.Edit",
"description": "edit"
}, {
"name": "$XSAPPNAME.Delete",
"description": "delete"
}, {
"name": "$XSAPPNAME.DataGenerator",
"description": "data generator"
}, {
"name": "xs_authorization.read",
"description": "Read authorization information from UAA"
}, {
"name": "xs_authorization.write",
"description": "Write authorization information to UAA"
}, {
"name": "$XSAPPNAME.ODATASERVICEUSER",
"description": "Enter"
}, {
"name": "$XSAPPNAME.ODATASERVICEADMIN",
"description": "Enter"
}],
"attributes": [{
"name": "client",
"description": "Session Client",
"valueType": "int"
}, {
"name": "country",
"description": "country",
"valueType": "s"
}],
"role-templates": [{
"name": "Viewer",
"description": "View all records",
"scope-references": [
"$XSAPPNAME.Display"
],
"attribute-references": [
"client", "country"
]
}, {
"name": "Editor",
"description": "Edit and Delete records",
"scope-references": [
"$XSAPPNAME.Create",
"$XSAPPNAME.Edit",
"$XSAPPNAME.Delete",
"$XSAPPNAME.Display",
"$XSAPPNAME.DataGenerator",
"$XSAPPNAME.ODATASERVICEUSER",
"$XSAPPNAME.ODATASERVICEADMIN"
],
"attribute-references": [
"client"
]
}]
}
int1 = ConvertUtils.stringToInteger(message);
https://<HTML_APP_URL>:<HTML_APP_PORT>/node?root=CHANNEL_ID
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
20 | |
19 | |
9 | |
7 | |
5 | |
5 | |
5 | |
5 | |
5 | |
4 |