Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //#############################################
  2. //##                  SETUP                  ##
  3. //#############################################
  4.  
  5. let IOTA = require('../node_modules/iota.lib.js');
  6. let MAM = require('./mam.node.js');
  7.  
  8. //#############################################
  9. //##          MAMSTREAM CONSTRUCTOR          ##
  10. //#############################################
  11.  
  12. function STREAM (_stream) {
  13.  
  14.   this.host = _stream.host || 'localhost';
  15.   this.port = _stream.port || 14265;
  16.  
  17.   this.id = _stream.id || 'IOTASensor1';
  18.   this.location = _stream.location || 'Home';
  19.   this.sources = [];
  20.  
  21.   this.seed = _stream.seed || generateSeed();//'WZKKGBDPF9OOBPPXRRLZUHCHPQNBUN9TGYIITJCSBACKPRWBJEYLHAR9AMQ9SWPVSLWULLICMMUFFQDYD' //generateSeed();
  22.   this.tree = null;
  23.  
  24.   this.wait = (_stream.wait == false ? false : true);   /* discards packets till the current packet has been send */
  25.   this.fetch = (_stream.fetch == true ? true : false);  /* enables permanent fetching*/
  26.   this.busy = false;
  27.   this.sync = false;
  28.  
  29.   this.initNode();
  30.  
  31.   // Initiate the mam state with the given seed at index 0.
  32.   this.mamState = MAM.init(this.iota, this.seed, 2, 0);
  33.   this.mamState = MAM.changeMode(this.mamState, 'restricted', 'olifa');
  34. }
  35.  
  36. //#############################################
  37. //##            ADD DATA SOURCE              ##
  38. //#############################################
  39.  
  40. STREAM.prototype.addSource = function(_s) {
  41.   this.sources.push(_s);
  42. }
  43.  
  44. //#############################################
  45. //##              HANDLE SOURCES             ##
  46. //#############################################
  47.  
  48. STREAM.prototype.handle = function() {
  49.  
  50.   /* abort sending while first fetch or lock until message is send */
  51.   if (this.sync || (this.wait && this.busy))
  52.          return null;
  53.  
  54.   /* if (this.wait) */
  55.     this.busy = true;
  56.  
  57.   let self = this;
  58.   var data = []
  59.  
  60.   self.sources.forEach(function(s) {
  61.     s().then(result => {
  62.     data.push(result);
  63.        if (data.length == self.sources.length)
  64.         self.send(data);
  65.    }).catch(err => { console.error(err); });
  66.   })
  67.  
  68. }
  69.  
  70. //#############################################
  71. //##              INITIATE MAM               ##
  72. //#############################################
  73.  
  74. STREAM.prototype.send = function(_data) {
  75.  
  76.  const scope = this;
  77.  const time = Date.now();
  78.  const ts = '\x1b[95m' + time + '\x1b[0m ';
  79.  
  80.  let json = {
  81.         'id':         this.id,
  82.         'location':   this.location,
  83.         'timestamp':  time,
  84.         'data':       _data,
  85.   }
  86.  
  87.  // Fetch all the messages in the stream.
  88.  fetchCount(json, scope).then(v => {
  89.  
  90.    /* finished fetching up */
  91.    this.sync = false;
  92.  
  93.    this.mamState = MAM.init(this.iota, this.seed, 2, v.messages.length);
  94.    this.mamState = MAM.changeMode(this.mamState, 'restricted', 'olifa')
  95.  
  96.    let newMessage = JSON.stringify(json);
  97.  
  98.    publish(newMessage, scope).then(result => {
  99.  
  100.      console.log(ts + '\x1b[32mSENT (hash: ' + result[0].hash + ')\x1b[0m');
  101.  
  102.      /* if (scope.wait) */
  103.           scope.busy = false;
  104.  
  105.    }).catch(err => { console.error(ts + '\x1b[41mERROR\x1b[0m (' + err + ')'); })
  106.  
  107.  }).catch(err => { console.error(ts + '\x1b[41mERROR\x1b[0m (' + err + ')'); });
  108.  
  109. }
  110.  
  111. //#############################################
  112. //##            INITIALISE IOTA              ##
  113. //#############################################
  114.  
  115. STREAM.prototype.initNode = function() {
  116.   this.iota = new IOTA({
  117.       'host': this.host,
  118.       'port': this.port
  119.   });
  120. }
  121.  
  122. //#############################################
  123. //##                  MaM                    ##
  124. //#############################################
  125.  
  126. async function fetchCount (_json, _scope) {
  127.  
  128.     let trytes = _scope.iota.utils.toTrytes('START');
  129.     let message = MAM.create(_scope.mamState, trytes);
  130.  
  131.     if (_scope.tree == null) {
  132.  
  133.       console.log('\n\x1b[45mThe first root:\x1b[0m');
  134.       console.log(message.root);
  135.       _scope.sync = true;
  136.  
  137.     } else { ++_scope.tree.messages.length; }
  138.  
  139.     console.log('\nJSON (\x1b[95mMaM\x1b[0m):');
  140.     console.log(_json);
  141.     console.log();
  142.  
  143.     if (_scope.fetch || _scope.tree == null) {
  144.          // Fetch all the messages upward from the first root.
  145.          console.log('\x1b[93m[fetching]\x1b[0m');
  146.          //_scope.tree = await MAM.fetch(message.root, 'public', null, null);
  147.          _scope.tree = await MAM.fetch(message.root, 'restricted', 'olifa', null);
  148.     }
  149.  
  150.     return _scope.tree;
  151. }
  152.  
  153. async function publish (_packet, _scope) {
  154.     let trytes = _scope.iota.utils.toTrytes(_packet)
  155.     let message = MAM.create(_scope.mamState, trytes);
  156.     // Set the mam state so we can keep adding messages.
  157.     _scope.mamState = message.state;
  158.     // Attach the message.
  159.     console.log('\x1b[93m[sending]\x1b[0m\n');
  160.     return await MAM.attach(message.payload, message.address);
  161. }
  162.  
  163. //#############################################
  164. //##                 HELPER                  ##
  165. //#############################################
  166.  
  167. function generateSeed () {
  168.  var seed = "";
  169.  var trytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ9";
  170.  
  171.  for (var i = 0; i < 81; i++)
  172.    seed += trytes.charAt(Math.floor(Math.random() * trytes.length));
  173.  
  174.  return seed;
  175. }
  176.  
  177. //#############################################
  178. //##                   EXPORTS               ##
  179. //#############################################
  180.  
  181. module.exports = STREAM;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement