Using Events: Difference between revisions
(Created page with "Category:Programming{{Recommended_Flow_Links|{{Flow Page Number|{{PAGENAME}} }} }} __NOTOC__ If you are new to Phidgets, or event-driven programming, chances are your fir...") |
No edit summary |
||
Line 111: | Line 111: | ||
==When should I poll?== | ==When should I poll?== | ||
If all you need is a simple program that reads a small amount of data from a device, it is possible to write a program that | If all you need is a simple program that reads a small amount of data from a device, it is possible to write a program that opens a channel, waits for attachment, reads the data, and closes the channel. In that case, the code to implement and set event handlers might not be worth the effort. When polling, '''error checking becomes very important''', as accessing some channel properties while the channel is detached, or before any data comes back from the Phidget, will result in an error or exception that could kill the program. There will always be a race between checking the {{Code|Attached}} property and accessing a data or state property. | ||
When in doubt, use event handlers. | When in doubt, use event handlers. | ||
{{Flow_Navigation_Buttons|{{Flow Page Number|{{PAGENAME}} }} }} | {{Flow_Navigation_Buttons|{{Flow Page Number|{{PAGENAME}} }} }} |
Revision as of 17:11, 6 March 2019
10 . Using Events
If you are new to Phidgets, or event-driven programming, chances are your first instinct will be to poll for everything. Polling is the action of repeatedly checking a variable or property to see if it has changed, and is generally done in-line from the main body of your application. While this can be effective in smaller applications, this quickly becomes inefficient. You also risk missing a change your program is waiting for, if it polls for data too slowly.
Events
The Phidget library allows for the use of event-driven programming. This allows your program to react to certain stimuli as they happen, rather than having to constantly check for changes. By setting up event handlers, you are setting up functions that run every time the event associated with them occurs. Once they have been assigned, these functions run independently from the main body of code. For example, a State Change event handler for a DigitalInput
channel will run every time the input state changes. Similarly, Attach and Detach events will occur when a device channel attaches to and detaches from your program (e.g. is plugged in and unplugged).
Using events can be very useful for tasks such as recording every data point from a Phidget sensor, reacting to a button being pressed, or initializing a channel as soon as it is attached. This frees up the main body of your program from having to constantly check the status of the Phidget, which can significantly clean up many applications.
Special Considerations
When using events, you must be mindful of keeping the code handling the event running as quickly as possible. If the event handler takes longer than the interval between events, this will cause the events to pile up and fall out of sync with the time they occur, and eventually start being lost.
When using events, you will need to be careful about what you share between the event and your main code. This is because events can happen at any time, so any variables shared with them could change unexpectedly.
Recommendations
We recommend all but the simplest program should set handlers that will be called when a channel attaches, detaches, sends an error, or receives new sensor data.
Initializing a channel should be done from the attach event handler, so it will always be configured as intended, even if something causes it to be unplugged and plugged back in.
Error Events
Make sure not to ignore using the Phidget error event handler, as many Phidgets will send critical information to the program using error events, such as when a sensor takes a measurement outside of its valid range, or activates some safety feature.
Linking Data to Events
When you're using events in your program, it may become useful to link certain information to the event for a given Phidget channel. Some programming languages provide a convenient way of doing exactly that, though the specifics depend on the programming language you are using:
Python is dynamically interpreted, and objects follow a less rigid structure than in other languages. To link a variable with a given Phidget object to have it available from the event, you can add it to the Phidget object that will be triggering the event. Then, you can access the information using the self
parameter of the event.
For example, if we wanted to group a number with a Phidget channel to be used in an event:
def onStateChangeHandler(self, state):
#We can now access and even change "myVariable" from the event
print(self.myVariable)
self.myVariable += 1
ch = DigitalInput()
#Addressing info here
#Here we create an attribute of ch called "myVariable", and assign it the information to store
#We'll use an integer here for simplicity, but this could be anything, even a second Phidget Handle
ch.myVariable = 0
ch.setOnStateChangeHandler(onStateChangeHandler)
ch.openWaitForAttachment(5000)
# The rest of your code here....
For example, if we wanted to link a number with a specific event for a Phidget channel:
static void CCONV onStateChangeHandler(PhidgetDigitalInputHandle pdih, void *ctx, int state) {
//We can now access the information at the pointer from the event
int* myIntPtr = (int*)ctx;
printf("Int: %d\n", *myIntPtr);
(*myIntPtr) ++;
}
int main() {
PhidgetDigitalInputHandle ch = NULL;
int myIntMain = 0;
PhidgetDigitalInput_create(&ch);
//Addressing info here
//Here we pass "myStringMain" as the context pointer so we can access it from the event
//This can be a pointer to any variable or structure, or even a second Phidget handle
PhidgetDigitalInput_setOnStateChangeHandler(ch, onStateChangeHandler, &myIntMain);
Phidget_openWaitForAttachment((PhidgetHandle)ch, 5000);
//The rest of your code here...
}
self
parameter of the event.
For example, if we wanted to group a number with a Phidget channel to be used in an event:
function stateChange(state) {
//We can now access and even change "myVariable" from the event
console.log(this.myVariable);
this.myVariable += 1;
}
...
var ch = new phidget22.DigitalInput();
...
//Here we create a property of ch called "myVariable", with the information to store
//We'll use an integer here for simplicity, but this could be anything,
//even a second Phidget Handle
ch.myVariable = 0
ch.onStateChange = stateChange;
ch.open();
//The rest of your code here...
When should I poll?
If all you need is a simple program that reads a small amount of data from a device, it is possible to write a program that opens a channel, waits for attachment, reads the data, and closes the channel. In that case, the code to implement and set event handlers might not be worth the effort. When polling, error checking becomes very important, as accessing some channel properties while the channel is detached, or before any data comes back from the Phidget, will result in an error or exception that could kill the program. There will always be a race between checking the Attached
property and accessing a data or state property.
When in doubt, use event handlers.