Template:Language - Swift Write Code: Difference between revisions

From Phidgets Support
(Created page with "{{WriteCode_Intro|Swift|Swift}} === Step One: Initialize and Open === You will need to declare your Phidget object in your code. For example, we can declare a digital input o...")
 
No edit summary
 
Line 1: Line 1:
{{WriteCode_Intro|Swift|Swift}}
{{WriteCode_Intro|Swift|Swift}}


=== Step One: Initialize and Open ===
=== Step One: Create and Address===
You will need to declare your Phidget object in your code. For example, we can declare a digital input object like this:
You will need to create your Phidget object in your code. For example, we can create a digital input object like this:
<syntaxhighlight lang="swift">
<syntaxhighlight lang=swift>
let ch = DigitalInput()
let ch = DigitalInput()
</syntaxhighlight>
</syntaxhighlight>


Next, we can address which Phidget we want to connect to by setting parameters such as ''DeviceSerialNumber''.


Next, the Phidget object needs to be opened:
<syntaxhighlight lang=swift>
<syntaxhighlight lang="swift">
ch.setDeviceSerialNumber(496911);
ch.open()
</syntaxhighlight>
</syntaxhighlight>


 
Although we are not including it on this page, you should handle the return codes of all Phidget functions. Here is an example of the previous code with error handling:
Although we are not including it on this page, you need to include error handling for all Phidget functions. Here is an example of the previous code with error handling:
<syntaxhighlight lang=swift>
<syntaxhighlight lang="swift">
do{
do{
   try ch.open
   try ch.open
Line 23: Line 22:
</syntaxhighlight>
</syntaxhighlight>


=== Step Two: Wait for Attachment (Plugging In) of the Phidget ===
=== Step Two: Open and Wait for Attachment===
Simply calling open does not guarantee you can use the Phidget immediately. To use a Phidget, it must be plugged in (attached). We can handle this by using event driven programming and tracking the attach events. Alternatively, we can modify our code so we wait for an attachment:
 
<syntaxhighlight lang="swift">
After we have specified which Phidget to connect to, we can open the Phidget object like this:
<syntaxhighlight lang=swift>
ch.open(timeout: 5000)
ch.open(timeout: 5000)
</syntaxhighlight>
</syntaxhighlight>
Waiting for attachment will block indefinitely until a connection is made, or until the timeout value is exceeded.


To use a Phidget, it must be plugged in (attached). We can handle this by calling '''open(''timeout'')''', which will block indefinitely until a connection is made, or until the timeout value is exceeded. Simply calling '''open()''' does not guarantee you can use the Phidget immediately.
Alternately, you could verify the device is attached by using event driven programming and tracking the attach events.
To use events to handle attachments, we have to modify our code slightly:
<syntaxhighlight lang=swift>
PhidgetDigitalInputHandle ch;
PhidgetDigitalInput_create(&ch);


To use events, we have to modify our code slightly:
<syntaxhighlight lang="swift">
ch.attach.addHandler(attach_handler)
ch.attach.addHandler(attach_handler)
Phidget_open(ch)
Phidget_open(ch)
</syntaxhighlight>
</syntaxhighlight>


Next, we have to declare the function that will be called when an attach event is fired - in this case the function ''attach_handler'' will be called.
Next, we have to declare the function that will be called when an attach event is fired - in this case the function ''onAttachHandler'' will be called:
 
<syntaxhighlight lang=swift>
<syntaxhighlight lang="swift">
func attach_handler(sender: Phidget){
func attach_handler(sender: Phidget){
   let attachedDevice = sender as! DigitalInput
   let attachedDevice = sender as! DigitalInput
Line 45: Line 49:
}
}
</syntaxhighlight>
</syntaxhighlight>
We recommend using this attach handler to set any initialization parameters for the channel such as DataInterval and ChangeTrigger from within the AttachHandler, so the parameters are set as soon as the device becomes available.


=== Step Three: Do Things with the Phidget ===
=== Step Three: Do Things with the Phidget ===
We recommend the use of event driven programming when working with Phidgets. In a similar way to handling an attach event as described above, we can also add an event handler for a state change event:
We recommend the use of event driven programming when working with Phidgets. In a similar way to handling an attach event as described above, we can also add an event handler for a state change event:
 
<syntaxhighlight lang=swift>
<syntaxhighlight lang="swift">
ch.attach.addHandler(attach_handler)
ch.attach.addHandler(attach_handler)
ch.stateChange.addhandler(stateChange_handler)
ch.stateChange.addhandler(stateChange_handler)
Line 55: Line 60:
</syntaxhighlight>
</syntaxhighlight>


This code will connect a function and an event. In this case, the ''stateChange_handler'' function will be called when there has been a change to the devices input. Next, we need to create the ''stateChange_handler'' function:
This code will connect a function to an event. In this case, the ''onStateChangeHandler'' function will be called when there has been a change to the channel's input. Next, we need to create the ''onStateChangeHandler'' function:
<syntaxhighlight lang="swift">
<syntaxhighlight lang=swift>
func stateChange_handler(sender: DigitalInput, state: Bool){
func stateChange_handler(sender: DigitalInput, state: Bool){
   if(state){
   if(state){
Line 67: Line 72:
</syntaxhighlight>
</syntaxhighlight>


If you are using multiple Phidgets in your program, check out our page on [[Using Multiple Phidgets]] for information on how to properly address them and use them in events.


If events do not suit your needs, you can also poll the device directly for data using code like this:
If events do not suit your needs, you can also poll the device directly for data using code like this:
<syntaxhighlight lang="swift">
<syntaxhighlight lang=swift>
var state = ch.getState()
var state = ch.getState()
stateLabel.text = state ? "True" : "False"
stateLabel.text = state ? "True" : "False"
</syntaxhighlight>
</syntaxhighlight>
'''Important Note:''' There will be a period of time between the attachment of a Phidget sensor and the availability of the first data from the device. Any attempts to get this data before it is ready will result in an error code, and a specific nonsensical result. See more information on this on our page for [[Unknown Values]].
====Enumerations====
Some Phidget devices have functions that deal with specific predefined values called enumerations. Enumerations commonly provide readable names to a set of numbered options.
Enumerations with Phidgets in Swift will take the form of '''Phidget22Swift.EnumerationType.enumerationName'''.
For example, specifying a SensorType to use the 1142 for a voltage input would look like:
<syntaxhighlight lang=swift>
Phidget22Swift.VoltageSensorType.PN_1142
</syntaxhighlight>
and specifying a K-Type thermocouple for a temperature sensor would be:
<syntaxhighlight lang=swift>
Phidget22Swift.ThermocoupleType.K
</syntaxhighlight>
The Phidget error code for timing out could be specified as:
<syntaxhighlight lang=swift>
Phidget22Swift.ErrorCode.timeout
</syntaxhighlight>
You can find the Enumeration Type under the ''Enumerations'' section of the {{Phidget22API}} for your device, and the Enumeration Name in the drop-down list within.


=== Step Four: Close ===
=== Step Four: Close ===
At the end of your program, be sure to close your device.
At the end of your program, be sure to close your device:
<syntaxhighlight lang="swift">
<syntaxhighlight lang=swift>
ch.close()
ch.close()
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 16:49, 13 September 2018

By following the instructions for your operating system and compiler above, you now have working examples and a project that is configured. This teaching section will help you understand how the examples were written so you can start writing your own code.


Remember: your main reference for writing Swift code will be the Phidget22 API Manual and the example code.

Step One: Create and Address

You will need to create your Phidget object in your code. For example, we can create a digital input object like this:

let ch = DigitalInput()

Next, we can address which Phidget we want to connect to by setting parameters such as DeviceSerialNumber.

ch.setDeviceSerialNumber(496911);

Although we are not including it on this page, you should handle the return codes of all Phidget functions. Here is an example of the previous code with error handling:

do{
  try ch.open
}catch let error as PhidgetError{
  //handle error
}

Step Two: Open and Wait for Attachment

After we have specified which Phidget to connect to, we can open the Phidget object like this:

ch.open(timeout: 5000)

To use a Phidget, it must be plugged in (attached). We can handle this by calling open(timeout), which will block indefinitely until a connection is made, or until the timeout value is exceeded. Simply calling open() does not guarantee you can use the Phidget immediately.

Alternately, you could verify the device is attached by using event driven programming and tracking the attach events.

To use events to handle attachments, we have to modify our code slightly:

PhidgetDigitalInputHandle ch;
PhidgetDigitalInput_create(&ch);

ch.attach.addHandler(attach_handler)
Phidget_open(ch)

Next, we have to declare the function that will be called when an attach event is fired - in this case the function onAttachHandler will be called:

func attach_handler(sender: Phidget){
  let attachedDevice = sender as! DigitalInput
  //configure device here
}

We recommend using this attach handler to set any initialization parameters for the channel such as DataInterval and ChangeTrigger from within the AttachHandler, so the parameters are set as soon as the device becomes available.

Step Three: Do Things with the Phidget

We recommend the use of event driven programming when working with Phidgets. In a similar way to handling an attach event as described above, we can also add an event handler for a state change event:

ch.attach.addHandler(attach_handler)
ch.stateChange.addhandler(stateChange_handler)
ch.open()

This code will connect a function to an event. In this case, the onStateChangeHandler function will be called when there has been a change to the channel's input. Next, we need to create the onStateChangeHandler function:

func stateChange_handler(sender: DigitalInput, state: Bool){
  if(state){
    //state is true
  }
  else{
    //State is false
  }
}

If you are using multiple Phidgets in your program, check out our page on Using Multiple Phidgets for information on how to properly address them and use them in events.

If events do not suit your needs, you can also poll the device directly for data using code like this:

var state = ch.getState()
stateLabel.text = state ? "True" : "False"

Important Note: There will be a period of time between the attachment of a Phidget sensor and the availability of the first data from the device. Any attempts to get this data before it is ready will result in an error code, and a specific nonsensical result. See more information on this on our page for Unknown Values.

Enumerations

Some Phidget devices have functions that deal with specific predefined values called enumerations. Enumerations commonly provide readable names to a set of numbered options.

Enumerations with Phidgets in Swift will take the form of Phidget22Swift.EnumerationType.enumerationName.

For example, specifying a SensorType to use the 1142 for a voltage input would look like:

Phidget22Swift.VoltageSensorType.PN_1142

and specifying a K-Type thermocouple for a temperature sensor would be:

Phidget22Swift.ThermocoupleType.K

The Phidget error code for timing out could be specified as:

Phidget22Swift.ErrorCode.timeout

You can find the Enumeration Type under the Enumerations section of the Phidget22 API for your device, and the Enumeration Name in the drop-down list within.

Step Four: Close

At the end of your program, be sure to close your device:

ch.close()