intel / iotivity-node

Node.js bindings for IoTivity
https://www.iotivity.org/
42 stars 44 forks source link

addEventListeners seems really complicated when you want to expose multiple sensors at the same time #41

Open kenchris opened 8 years ago

kenchris commented 8 years ago

Instead of

    oic.addEventListener("updaterequest", onLightUpdate);
    oic.addEventListener("observerequest", onLightObserve);
    oic.addEventListener("deleterequest", onLightDelete);
    ...

and handling all sensors inside each method, wouldn't it not be better to give it an object instead, like Bleno does with Characteristics. That also allows you to easily share objects/value for each sensor instead of relying on global variables. And it allows you to inherit from common objects when they are very similar in spirit.

pseudocode (ignore naming) [the *Callback methods are modelled after latest ES6 compatible Custom Elements spec]:

class BlueLED extends oic.Resource {
  constructor() {
    this._value = 0.5;
    this._onlyGrow = true;

    super({
      deviceId: oic.device.uuid,
      path: "/light/ambience/blue",
      resourceTypes: [ "light" ],
      interfaces: [ "/oic/if/rw" ],

      discoverable: true,
      observable: true,

      properties: { 
        color: "blue",
        dimmer: this._value;
      }
    })
  }

  updateRequestCallback(value) {
     if (this._onlyGrow)
       this._value = Math.max(this._value, value);
  }

  deleteRequestCallback() {
  }
}

function startServer() {
  oic.registerResource(new BlueLED())
  .catch(function(err) { 
    console.log(err)
  });
}
zolkis commented 8 years ago

Looks good, it's mostly syntactic sugar. Your method is complementing events but AFAICT is not replacing them. What is the callback dispatching mechanism? We need support from the main loop. What idioms are better known by developers? Events at least are pretty well known.

kenchris commented 8 years ago

They should be called async on the object itself (so it becomes ). I don't see why main loop support would be needed, as all the resources will be registered in one place.

I like that you naturally keep the relevant code together and this method might be popularized with custom elements and node.js libraries like noble.