You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. var spawn = require("child_process").spawn;
  2. exports.list = list;
  3. exports.monitor = monitor;
  4. exports.unmonitor = unmonitor;
  5. exports.exit = exit;
  6. exports.init = init;
  7. var child;
  8. function init(cb) {
  9. child = spawn(__dirname+"/udev-monitor");
  10. var currstr = "";
  11. child.stdout.setEncoding("utf8");
  12. child.stdout.on("data", d => {
  13. var lines = d.toString().split("\n");
  14. currstr += lines[0];
  15. if (lines.length === 1)
  16. return;
  17. ondata(JSON.parse(currstr));
  18. for (var i = 1; i < lines.length -1; ++i) {
  19. ondata(JSON.parse(lines[i]));
  20. }
  21. currstr = lines[lines.length - 1];
  22. });
  23. child.stderr.on("data", d => console.error("udev error:", d.toString()));
  24. }
  25. var listq = [];
  26. var monitors = {};
  27. function ondata(obj) {
  28. if (obj instanceof Array) {
  29. if (listq.length === 0)
  30. return;
  31. var cb = listq.shift();
  32. cb(obj);
  33. } else {
  34. var ss = obj.SUBSYSTEM;
  35. if (monitors[ss]) {
  36. monitors[ss].forEach(cb => cb(obj));
  37. }
  38. if (monitors["*"]) {
  39. monitors["*"].forEach(cb => cb(obj));
  40. }
  41. }
  42. }
  43. function list(ss, cb) {
  44. listq.push(cb);
  45. child.stdin.write("list:"+ss+"\n");
  46. }
  47. function monitor(ss, cb) {
  48. if (monitors[ss] == null) {
  49. child.stdin.write("monitor:"+ss+"\n");
  50. monitors[ss] = [];
  51. }
  52. monitors[ss].push(cb);
  53. }
  54. function unmonitor(ss, cb) {
  55. if (monitors[ss] == null)
  56. throw new Error("Callback function for "+ss+" not registered");
  57. var removed = false;
  58. for (var i in monitors[ss]) {
  59. if (monitors[ss][i] === cb) {
  60. monitors[ss].splice(i, 1);
  61. removed = true;
  62. }
  63. }
  64. }
  65. function exit() {
  66. child.kill("SIGTERM");
  67. }