tjrothwell

http://thejackalofjavascript.com/raspberry-pi-node-js-led-em

Feb 21st, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.   * Inspired by: http://thejackalofjavascript.com/raspberry-pi-node-js-led-emit-morse-code/
  3.   */
  4. // Example: node morse.js sos
  5.  
  6. // Uncomment the following to test script when event loop spins forever
  7. // const spinTestExecFunction = process.nextTick
  8.  
  9. // Uncomment the following to test script when event loop is saturated
  10. // const spinTestExecFunction = setImmediate
  11.  
  12. const onoff = require("onoff");
  13. const Q = require("q");
  14. const gapDurationMillis = 10; /* Smallest unit of time to wait */
  15. const postDeactivateGaps = 5; /* How long to wait after using led */
  16. const codes = { /* Morse codes */
  17.         "." : {enableLed:true, gaps:10}, // dot
  18.         "_" : {enableLed:true, gaps:40}, // dash
  19.         "|" : {enableLed:false, gaps:20}, // letter end
  20.         ":" : {enableLed:false, gaps:0} // word separator
  21.     };
  22. const pattern = { /* Conversion from sourceLetter to morseCodes */
  23.         "a": "._|",
  24.         "b": "_...|",
  25.         "c": "_._.|",
  26.         "d": "_..|",
  27.         "e": ".|",
  28.         "f": ".._.|",
  29.         "g": "__.|",
  30.         "h": "....|",
  31.         "i": "..|",
  32.         "j": ".___|",
  33.         "k": "_._|",
  34.         "l": "._..|",
  35.         "m": "__|",
  36.         "n": "_.|",
  37.         "o": "___|",
  38.         "p": ".__.|",
  39.         "q": "__._|",
  40.         "r": "._.|",
  41.         "s": "...|",
  42.         "t": "_|",
  43.         "u": ".._|",
  44.         "v": "..._|",
  45.         "w": ".__|",
  46.         "x": "_.._|",
  47.         "y": "_.__|",
  48.         "z": "__..|",
  49.         "1": ".____|",
  50.         "2": "..___|",
  51.         "3": "...__|",
  52.         "4": "...._|",
  53.         "5": ".....|",
  54.         "6": "_....|",
  55.         "7": "__...|",
  56.         "8": "___..|",
  57.         "9": "____.|",
  58.         "0": "_____|",
  59.         ".": "._._._|",
  60.         ",": "__..__|",
  61.         "?": "..__..|",
  62.         "/": "_.._.|",
  63.         "@": ".__._.|",
  64.         " ": ":"
  65.     };
  66.  
  67. var main = function (text) {
  68.         var led = new onoff.Gpio(17, "out");
  69.         emitTextAsMorseCodeAsPromise(led, text)
  70.             .done(function (o) {
  71.                 console.info("DONE!");
  72.                 process.exit(0);
  73.             });
  74.     },
  75.     emitTextAsMorseCodeAsPromise = function (led, text) {
  76.         var promise = Q(),
  77.             normalizedText = text.toLowerCase()
  78.                 .replace(/[^a-z0-9\.,\?/@]+/g, " ");
  79.         console.info("Text to morse code: [" + normalizedText + "]");
  80.         normalizedText.split("")
  81.             .forEach(function (sourceLetter) {
  82.                 var morseCodes = pattern[sourceLetter];
  83.                 promise = promise.then(function () {
  84.                     console.log("morseCode: [" + sourceLetter + "] -> [" + morseCodes +"]");
  85.                 });
  86.                 morseCodes.split("")
  87.                     .forEach(function (morseCode) {
  88.                         promise = promise.then(function () {
  89.                             return emitMorseCodeAsPromise(led, morseCode);
  90.                         });
  91.                     });
  92.             });
  93.         return promise;
  94.     },
  95.     emitMorseCodeAsPromise = function (led, morseCode) {
  96.         return Q({led:led, morseCode:morseCode})
  97.             .then(function (bucket) {
  98.                 var code = codes[bucket.morseCode];
  99.                 if (!code) {
  100.                     throw new Error("Unknown code: ["+bucket.morseCode+"]");
  101.                 }
  102.                 bucket.code = code;
  103.                 console.log("emitting: [" + bucket.morseCode +"]");
  104.                 if (bucket.code.enableLed) { // activate
  105.                     bucket.led.writeSync(1);
  106.                 }
  107.                 return Q(bucket).delay(getGapDelay(bucket.code.gaps));
  108.             })
  109.             .then(function (bucket) {
  110.                 if (bucket.code.enableLed) { // deactivate
  111.                     bucket.led.writeSync(0);
  112.                     return Q(bucket).delay(getGapDelay(postDeactivateGaps));
  113.                 }
  114.                 return bucket;
  115.             });
  116.     },
  117.     getGapDelay = function (gaps) {
  118.         return gapDurationMillis * gaps;
  119.     };
  120.  
  121. // Add duration of script to console messages
  122. (function (con) {
  123.     var functions = {}, key, startTime = process.hrtime(),levelLabel = { "log" : "DEBUG", "info" : "INFO", "warn" : "WARN", "error" : "ERROR", "trace" : "TRACE" },getTime = function () {var runningTime = process.hrtime(startTime);return "" + runningTime[0] + "." + "0".repeat(9 - Math.ceil(Math.log10(runningTime[1]))) + runningTime[1];/* return new Date().toISOString().toString(); */};
  124.     for (key in con) {
  125.         if (typeof(con[key]) != "function") { continue; }
  126.         switch (key) { case "log": case "info": case "warn": case "error": case "trace":
  127.             functions[key] = con[key]; // original function
  128.             con[key] = (function(name) {return function () {Array.prototype.unshift.apply(arguments,["["+getTime()+"]","["+levelLabel[name]+"]"]);functions[name].apply(con, arguments);}})(key)
  129.             break;
  130.         default: break;
  131.     }}
  132. })(console);
  133.  
  134. // Start our app
  135. process.nextTick(function () {
  136.     main((process.argv[2] ? process.argv[2] : ""));
  137. });
  138.  
  139. (function spinForever () {
  140.     if (typeof spinTestExecFunction == "undefined") { return; }
  141.     process.stdout.write(".");
  142.     spinTestExecFunction(spinForever);
  143. })();
Add Comment
Please, Sign In to add comment