Brain4itWatchController.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Brain4itWatchController.js
  3. *
  4. * @author realor
  5. */
  6. import { Controller } from './Controller.js'
  7. import { Brain4it } from '../lib/Brain4it.js'
  8. Brain4it.monitors = {}
  9. class Brain4itWatchController extends Controller {
  10. constructor(object, name) {
  11. super(object, name)
  12. this.url = ''
  13. this.module = 'your_module'
  14. this.accessKey = 'access_key'
  15. this.func = '@function_to_call'
  16. this.output = 0
  17. this.autoStart = false
  18. this._monitor = null
  19. this._functionKey = null
  20. this._callback = this.callback.bind(this)
  21. this._onNodeChanged = this.onNodeChanged.bind(this)
  22. }
  23. onStart() {
  24. this.application.addEventListener('scene', this._onNodeChanged)
  25. this.watch()
  26. }
  27. onStop() {
  28. this.application.removeEventListener('scene', this._onNodeChanged)
  29. this.unwatch()
  30. }
  31. onNodeChanged(event) {
  32. if (event.type === 'nodeChanged' && this.hasChanged(event)) {
  33. this.watch()
  34. }
  35. }
  36. callback(name, value) {
  37. console.info('MONITOR ' + name + ' = ' + value)
  38. this.output = value
  39. this.application.notifyObjectsChanged(this.object, this)
  40. }
  41. watch() {
  42. let url = this.url
  43. if (url.trim().length === 0) return
  44. if (url[0] === '/') {
  45. url = document.location.protocol + '//' + document.location.host + url
  46. }
  47. let module = this.module
  48. let accessKey = this.accessKey || ''
  49. let func = this.func
  50. let moduleKey = url + '/' + module + '/' + accessKey
  51. let functionKey = moduleKey + '/' + func
  52. if (functionKey !== this._functionKey) {
  53. this.unwatch()
  54. let monitor = Brain4it.monitors[moduleKey]
  55. if (monitor === undefined) {
  56. monitor = new Brain4it.Monitor(url, module, accessKey)
  57. Brain4it.monitors[moduleKey] = monitor
  58. }
  59. this._monitor = monitor
  60. this._functionKey = functionKey
  61. this._func = func
  62. console.info('WATCH', func)
  63. monitor.watch(this._func, this._callback)
  64. }
  65. }
  66. unwatch() {
  67. if (this._monitor) {
  68. console.info('UNWATCH')
  69. this._monitor.unwatch(this._func, this._callback)
  70. this._monitor = null
  71. this._functionKey = null
  72. this._func = null
  73. }
  74. }
  75. }
  76. Controller.addClass(Brain4itWatchController)
  77. export { Brain4itWatchController }