Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
blocks:drivers:example [2018-03-05 21:10]
admin
blocks:drivers:example [2023-06-12 11:11] (current)
admin Clarified connect callback parameters
Line 3: Line 3:
 The WOCustomDrvr.ts file demonstrates how to write a driver for a device that provides a TCP "socket" based control protocol. The WOCustomDrvr.ts file demonstrates how to write a driver for a device that provides a TCP "socket" based control protocol.
  
-This example driver communicates with Dataton WATCHOUT production software, controlling some basic+This example driver communicates with [[https://www.dataton.com/products/watchout|Dataton WATCHOUT]] production software, controlling some basic
 functions. It's provided only as an example, since Blocks already has full functions. It's provided only as an example, since Blocks already has full
 support for controlling WATCHOUT built-in. Using WATCHOUT as an example device support for controlling WATCHOUT built-in. Using WATCHOUT as an example device
Line 10: Line 10:
   - Many of you are already familiar with WATCHOUT.   - Many of you are already familiar with WATCHOUT.
   - The production software UI clearly shows what's going on.   - The production software UI clearly shows what's going on.
-  - It's available as a free download, so anyone can use it to try out the driver+  - It's available as a [[https://www.dataton.com/downloads/watchout|free download]], so anyone can use it to try out the driver.
- +
-Open the driver using the Atom editor, and follow along in the code as you read this walk-through.+
  
 +Open the driver using a [[blocks:drivers:tools|code editor]], and follow along in the code as you read this walk-through.
 ===== Import Statements =====  ===== Import Statements ===== 
  
-At the very top of the file, there are import statements, referencing other files and their content. These other files provide definitions of system functions used to communicate with the device, such as the NetworkTCP interface imported from the "system/Network" file. You can navigate to referenced classes or files by command-clicking (Mac) or control-clicking (Windows) these items in the Atom editor. The referenced files contain the relevant declarations, and often also contain comments that further describe the referenced functions.+At the very top of the file, there are import statements, referencing other files and their content.  
 + 
 +<code> 
 +import {NetworkTCP} from "system/Network"; 
 +import {Driver} from "system_lib/Driver"; 
 +import * as Meta from "system_lib/Metadata"; 
 +</code> 
 + 
 +These other files provide definitions of system functions used to communicate with the device, such as the NetworkTCP interface imported from the "system/Network" file. You can navigate to referenced classes or files by command-clicking (Mac) or control-clicking (Windows) these items in the editor. The referenced files contain the relevant declarations, and often also contain comments that further describe the referenced functions.
  
-Not only does this provide relevant documentation. It also provides information for the TypeScript compiler as well as for the [[blocks:drivers:tools|Atom]] editor. The Atom editor uses this information to guide you when writing code, often providing hints as you type, showing available functions, parameters, etc. If you make a mistake, this is often highlighted in red by the Atom editor and/or flagged by the TypeScript compiler.+Not only does this provide relevant documentation. It also provides information for the TypeScript compiler as well as for the [[blocks:drivers:tools|code editor]]. The code editor uses this information to guide you when writing code, often providing hints as you type, showing available functions, parameters, etc. If you make a mistake, this is often highlighted in red by the code editor and/or flagged by the TypeScript compiler.
  
 =====  Driver Class Declaration =====  =====  Driver Class Declaration ===== 
Line 35: Line 42:
 =====  Instance Variables =====  =====  Instance Variables ===== 
  
-At the top of the class, you typically define any variables used by the driver to keep track of its state. Variables are typed; either explicitly, as the pendingQueries which is of type Dictionary<Query>, or implicitly by assigning them a value.+At the top of the class, you typically define any variables used by the driver to keep track of its state.  
 + 
 +<code> 
 +private pendingQueries: Dictionary<Query> = {}; 
 +private mAsFeedback = false;    // Set while processing feedback, to only fire events 
 + 
 +private mConnected = false;    // Connected to WATCHOUT 
 +private mPlaying = false;    // Most recent state (obtained from WO initially) 
 +private mStandBy = false; 
 +private mLevel = 0;        // Numeric state of Output 
 + 
 +private mLayerCond = 0; 
 +</code> 
 + 
 + 
 +Variables are typed; either explicitly, as the pendingQueries which is of type Dictionary<Query>, or implicitly by assigning them a value.
  
 A driver may be used by multiple devices (for instance, controlling three projectors, all of the same brand and model). In this case, each driver instance will get its own private set of instance variables. A driver may be used by multiple devices (for instance, controlling three projectors, all of the same brand and model). In this case, each driver instance will get its own private set of instance variables.
Line 41: Line 63:
 ===== Constructor ===== ===== Constructor =====
  
 +The driver must have a constructor function.
  
-The driver must have a constructor function, which must take a single parameter of the type specified as part of the class declaration. In this example, this parameter is the NetworkTCP object, subsequently used to communicate with the TCP socket.+<code> 
 +public constructor(private socket: NetworkTCP) { 
 +    super(socket); 
 +    ... 
 +</code>
  
-This parameter must be passed to the //Driver// base class using the //super// keywordas shown.+The driver constructor has a single parameter of the type specified as part of the class declaration. In this example, this parameter is the NetworkTCP objectsubsequently used to communicate with the TCP socket.
  
 +This parameter must be passed to the //Driver// base class using the //super// keyword, as shown.
 ==== Event Subscriptions ==== ==== Event Subscriptions ====
  
-The constructor is a good place for one-time initializations, such as event subscriptions. The example driver subscribes to the 'connect' and 'textReceived' events. These event subscriptions are similar to how //addEventListener// is used in web browsers to listen to DOM events. You can find all available events described in the Network.ts file. Jump directly to the relevant declaration by command/control-clicking the //subscribe// call. +The constructor is a good place for one-time initializations, such as event subscriptions. The example driver subscribes to the 'connect' and 'textReceived' events.  
 + 
 +<code> 
 +socket.subscribe('connect', (sender, message)=>
 +    this.connectStateChanged(); 
 +}); 
 +</code> 
 + 
 +Event subscriptions are similar to how //addEventListener// is used in web browsers to listen to DOM events. The 'connect' event indicates that the connection status of the socket has changed or failed (as indicated by the type field of the message parameter). All events are described in the Network.ts file, so always look there for full details. Jump directly to the relevant declaration by command/control-clicking //subscribe// call. 
  
-When the subscribed-to event occurs, the function body following the //[[https://basarat.gitbooks.io/typescript/docs/arrow-functions.html|lambda]]// => operator will be invoked. Either do what needs to be done here, or call a function defined elsewhere in the driver.+When the subscribed-to event occurs, the function body following the //[[https://basarat.gitbooks.io/typescript/docs/arrow-functions.html|lambda]]// => operator will be invoked. Either do what needs to be done right here, if its only a line or two, or call a function defined elsewhere in the driver.
  
  
Line 65: Line 101:
  
 A property is internally represented by one or two accessor functions. These use the keywords //get// and //set//, followed by the name of the property. The //set// function will be called when the property is set, and the //get// function will be called when its current value is requested. A property is internally represented by one or two accessor functions. These use the keywords //get// and //set//, followed by the name of the property. The //set// function will be called when the property is set, and the //get// function will be called when its current value is requested.
 +
 +<code>
 +@Meta.property("Layer condition flags")
 +public set layerCond(cond: number) {
 +    if (this.mLayerCond !== cond) {
 +        this.mLayerCond = cond;
 +        this.tell("enableLayerCond " + cond);
 +    }
 +}
 +public get layerCond(): number {
 +    return this.mLayerCond;
 +}
 +</code>
 +
 +The example defines a property named //layerCond//, which is numeric. When set it is stored in the //mLayerCond// instance variable, so the driver can keep track of the most recently set state, and return this in the //get// function also shown above. In addition to storing it, the setter also calls the //tell// function to tell WATCHOUT about this using the //enableLayerCond// protocol command.
  
 Some properties may not be controllable, but could still make sense to read out. For a projector, a "lamp failure" indication fits the bill here. In this case, you only need to provide the //get// function, since it makes no sense to //set// this state from outside. This makes the property //read-only//, and you will not be able to assign a button to set it from the outside. Some properties may not be controllable, but could still make sense to read out. For a projector, a "lamp failure" indication fits the bill here. In this case, you only need to provide the //get// function, since it makes no sense to //set// this state from outside. This makes the property //read-only//, and you will not be able to assign a button to set it from the outside.
Line 76: Line 127:
 For a numeric property, you can also use //min// and //max// decorators, as shown for the //input// property in the example driver, specifying the minimum and maximum numeric value the property may take. For a numeric property, you can also use //min// and //max// decorators, as shown for the //input// property in the example driver, specifying the minimum and maximum numeric value the property may take.
  
 +<code>
 +@Meta.property("Generic input level")
 +@Meta.min(0)
 +@Meta.max(1)
 +public set input(level: number) {
 +    this.tell("setInput In1 " + level);
 +    this.mLevel = level;
 +}
 +public get input() {
 +    return this.mLevel;
 +}
 +</code>
  
 +===== Callable Functions =====
 +
 +Whenever possible, use //properties// to expose device features. This allows the feature to be directly bound to a button, slider, or similar panel control. Properties can also be controlled from //tasks//, and can be used to trigger tasks, or as part of task conditions.
 +
 +However, some features of a device or protocol may not allow themselves to be exposed as a simple property value. Such features can instead be exposed as a callable function. 
 +
 +<code>
 +@Meta.callable("Play or stop any auxiliary timeline")
 +public playAuxTimeline(
 +    @Meta.parameter("Name of aux timeline to control") name: string,
 +    @Meta.parameter("Whether to start the timeline") start: boolean
 +) {
 +    this.tell((start ? "run " : "kill ") + name);
 +}
 +</code>
 +
 +This example exposes the ability to start and stop an arbitrary timeline by name. While it would be possible to expose a property for each timeline to control this behavior, that would require you to:
 +
 +  * Know the name of each timeline ahead of time, as you write the driver.
 +  * Provide separate get/set functions for the //running// state of each timeline.
 +
 +In some cases this is neither possible nor desirable. Then you can instead provide a function, taking the desired number of //parameters// of the desired types. The //playAuxTimeline// function shown above accepts two parameters:
 +
 +  - **name**, a string specifying the name of the timeline.
 +  - **start**, a boolean specifying whether to start (true) or stop (false) the timeline.
 +
 +A function can take any number of parameters of different types. A function marked as // callable// using the decorator shown above will be exposed for use from tasks. The description you provide for the //callable// decorator, as well as the //parameter// decorators will be shown in Blocks when editing the task.
 +
 +:!: While a function can be called from a task and scripts, it can not be directly linked to a button or slider, or used as a task trigger or condition.
 +
 +
 +===== Internal Functions =====
 +
 +You may want to define functions that are only used inside the driver, as a way of making the code more modular or self documenting, or to define some internal functionality not directly exposed to buttons and tasks. Such functions are marked as //private//.
 +
 +<code>
 +/**
 + Connection state changed. If became connected, poll WO for some initial
 + status. Called as a result of the 'connect' subscription done in the
 + constructor.
 + */
 +private connectStateChanged() {
 +    this.connected = this.socket.connected; // Propagate state to clients
 +    if (this.socket.connected)
 +        this.getInitialStatus();
 +    else
 +        this.discardAllQueries();
 +}
 +</code>
 +
 +The //connectStateChanged// function is called from the 'connect' subscription mentioned earlier in this document. The code in this function could instead have been placed directly inside the 'connect' subscription's body. But breaking it out into its own function like this makes the code more readable and potentially reusable.
 +
 +===== Parsing Data =====
 +
 +A device driver typically does three basic things.
 +
 +  * Exposing desired functionality of the device through //properties// and //callable functions//, allowing them to be easily accessed from other parts of Blocks.
 +  * Sending commands to the device to control it according to how those properties are set or functions are called,
 +  * Receiving data coming back from the device, indicating its current state, error conditions, or similar.
 +
 +This last point is often the hardest to get right, and often involves the following steps:
 +
 +  - Provoke the device to send the data you're interested in. In most cases, devices only send data in response to commands. This can either be an acknowledgement of the command (or an error message if the command failed for some reason), or a reply to a question posed by the command.
 +  - Parse out the part of the data coming from the device you're interested in.
 +  - Act intelligently on the data. E.g., handle any errors, or update exposed properties according to a change of some state in the device.
 +
 +For devices that communicate using a text based protocol, regular expressions often come in handy when parsing the data.
 +
 +<code>
 +private static kReplyParser = /\[([^\]]+)\](\w*)[\s]?(.*)/;
 +</code>
 +
 +[[https://en.wikipedia.org/wiki/Regular_expression|Regular expressions]] are [[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions| directly supported]] by the scripting language. Just as strings are delimited by single or double quotes, regular expression are delimited by a forward slash.
 +
 +While the regular expression syntax is quite powerful, it is also often hard to read and understand. When developing and testing a regular expression, you may therefore want to use an online service such as [[https://regex101.com|this one]]. Here you can enter sample data, representative of what's sent by the device, and work on the regular expression until it does what you want. Then copy the resulting expression and paste it into the driver.
 +
 +The //textReceived// function uses the regular expression shown above to parse replies received from WATCHOUT, handing the results off to their associated queries for further processing. 
 +
 +<code>
 +private textReceived(text: string) {
 +    const pieces = WOCustomDrvr.kReplyParser.exec(text);
 +    if (pieces && pieces.length > 3) {
 +        const id = pieces[1];
 +        const what = pieces[2];
 +        const query = this.pendingQueries[id];
 +        if (query) {
 +            delete this.pendingQueries[id]; // Now taken
 +            query.handleResult(what, pieces[3]);
 +        } else // No corresponding query found
 +            console.warn("Unexpected reply", text);
 +    } else
 +        console.warn("Spurious data", text);
 +}
 +</code>
 +
 +The fact that WATCHOUT allows you to tag each question, and then returns that same tag in the associated reply makes it easy to match them up. That's not always the case. Also, WATCHOUT accepts numerous commands sent back to back, possibly intermixed with questions. Many devices have limits on how fast you can send commands. Sometimes you need to wait for a command to be acknowledged by some returned data before you can send further commands. In other cases, you may have to limit how fast you send commands, and the maximum command rate may not be well documented. 
 +===== Promises =====
 +
 +Communicating with a device often means sending a command at one point in time that results in a reply or other action later on. For example:
 +
 +  * Asking a question that will be replied to by the device in due course.
 +  * Giving a command that is expected to cause some result, and then doing something else if the result hasn't arrived in time.
 +
 +Since you can not (and **must not**) have your code sit tight and wait for the answer to come back, or for the maximum time to elapse, you must instead use a [[https://scotch.io/tutorials/understanding-javascript-promises-pt-i-background-basics|Promise]] to deal with such situations.
 +
 +<code>
 +private ask(question: string): Promise<string> {
 +    if (this.socket.connected) {
 +        const query = new Query(question);
 +        this.pendingQueries[query.id] = query;
 +        this.socket.sendText(query.fullCmd);
 +        return query.promise;
 +    } else
 +        console.error("Can't ask. Not connected");
 +}
 +</code>
 +
 +A //promise// is an object that tracks the future outcome of the action. When this future outcome becomes clear, the promise will call a function provided by you. Alternatively, if the action fails, it calls another function to deal with that situation.
 +
 +The //getInitialStatus// function shows how a promise can be used.
 +
 +<code>
 +private getInitialStatus() {
 +    this.ask('getStatus').then(reply => {
 +        this.mAsFeedback = true; // Calling setters for feedback only
 +        const pieces = reply.split(' ');
 +        if (pieces[4] === 'true') {    // Show is active
 +            // Go through setters to notify any change listeners out there
 +            this.playing = (pieces[7] === 'true');
 +            this.standBy = (pieces[9] === 'true');
 +        }
 +        this.mAsFeedback = false;
 +    });
 +}
 +</code>
 +
 +Here you can see how the //then// function is called to pick up the outcome of the question asked. Note that the body inside the function won't be invoked until the reply to the //getStatus// question comes back from WATCHOUT.
 +
 +
 +===== Custom Classes =====
 +
 +For more complex functionality, you can define your own classes inside a driver, or in a library module (a separate TypeScript file store in the //script/lib// directory). Define the class inside the driver file if it's only used by that driver. Store more general purposes classes in ther own files in the //script/lib// directory, allowing them to be used from multiple drivers.
 +
 +<code>
 +class Query {
 +    ...
 +</code>
  
- +Just like the driver itself, such classes define their own instance variables, constructor and functions. You instantiate objects of your custom class using the //new// keyword, as shown above in the example under //Promises//.