Home > Blog > Thunderheads > Thunderheads: September 2011

Thunderheads: September 2011

What’s Your Story?
— Tell Us How You Use iDigi —

There are a lot of interesting projects and applications that utilize our wireless technology and the iDigi® Device Cloud™, such as:

  • E2 America’s automated building energy control system, used to reduce energy consumption and demand by optimizing HVAC efficiency. More >
  • Inteligistics’ Dynamic Smart Box™, an intelligent inventory tracking system that connects tens of thousands of shipping containers worldwide. More >
  • AddEnergie’s remote electric vehicle (EV) charging stations, which rely on Digi®technology to enable remote energy management. More >

Tell us your story
The iDigi Solutions Architecture team is looking for new and interesting applications. Share your ideas, projects, questions, etc. with us. You can contact the team atthunderheads@digi.com.

Projects from the Mind of Mark
Mark Geller’s Arduino Project
Part Three

In the first two parts of this project log, I showed you how to send serial commands to an Arduino serial project using XBee® modules, aConnectPort® X2 gateway and iDigi web services. For this installment, I’m going to walk you through creating a native iOS application to send serial commands to the same Arduino project using iDigi web services.

Mark Geller at work in Minnetonka, MN


Before You Get Started
For this project I will be using Xcode running on an Apple computer to create a native iOS application. The application shown below will run fine in Apple’s iOS Simulator that is included with Xcode. If you are interested in distributing iOS applications on Apple’s App Store, or if you want to run your iOS programs on more than the iOS Simulator, then you will need to sign up for Apple’s iOS developer program.

Setting Up A Project in Xcode
To create your project, open Xcode and select “File > New > New Project…” and then select the “View-based Application.” Click the “Next” button and enter a name for your application. I named my application “XBeeSerial,” selected “iPhone” for the device family and deselected the check box next to “Include Unit Tests.” Click the “Next” button to create your project.

Xcode will automatically create several files for you. For this project, we are only going to edit the XBeeSerialViewController files.

Building the User Interface
Select the “XBeeSerialViewController.xib” file to open Interface Builder. Drag a Label control, a Text Input control and a Round Rect Button control onto the main view. Double click the Label control and change the text to “Command:”. Double click the button control and change the text to “Send Serial Command.”

Select the “XBeeSerialViewController.h” file in Xcode to open it. This file defines the interface for our view controller class. We need to add a variable to reference the text input control, a variable that will hold data when we call an iDigi® Dia web service and a method signature for the sendCommand function. Change:

@interface XBeeSerialViewController :UIViewController    to@interface XBeeSerialViewController :UIViewController {UITextField *commandField_;NSMutableData *data_;}@property (nonatomic, retain) IBOutlet UITextField *commandField;@property (nonatomic, retain) NSMutableData *data;- (IBAction)sendCommand:(id)sender; 

Save your changes.

Select the “XBeeSerialViewController.xib” file in Xcode to open it. Hold down the “control” key while you click and drag from the “File’s Owner” box in the placeholders pallet to the command text input. Select “commandField” from the dialog box that pops up. Now hold down the “control” key while you click and drag from the “Send Serial Command” button to the “File’s Owner” box. Select “sendCommand:” from the dialog box that pops up. Save your changes.

Editing the Implementation File
Select the “XBeeSerialViewController.m” file in Xcode to view its source. Add “@synthesize commandField=commandField_, data=data_;” just under the “@implementation XBeeSerialViewController” directive at the top of the file. That code will instruct the iOS compiler to automatically create functions that will allow us to read and write data to the commandField and data variables.

Now add some string constants for the iDigi web service URL, iDigi username, iDigi password, gateway ID for the ConnectPort X2 gateway and an XML wrapper for the SCI Python callback command we will send to the iDigi Device Cloud. This code is similar to what I created in Part II when I created the mobile web interface. Add the following lines to the top of the file, just under the “#import” statement:

NSString *const SERVER_URL = @”https:\developer.idigi.com/ws/sci”;NSString *const USERNAME = @”username”;NSString *const PASSWORD = @”password”;NSString *const GATEWAY = @”00000000-00000000-0004F3FF-FF000000″;NSString *const REQUEST = @”<sci_request version=”1.0″><send_message><targets><device id=”%@”/></targets><rci_request version=”1.1″><do_command target=”idigi_dia”><channel_set name=”xbee_serial_terminal0.write” value=”%@”/></do_command></rci_request><send_message><sci_request>”;Remember to change the values of the username, password, and gateway constants to your own username, password and gateway ID.

Add the following code to the bottom of the file just before the ” @end ” directive:

-(void)dealloc {    [commandField_ release];    [data_ release];    [super dealloc];}When building iOS applications, it is very important to manage your memory by releasing all variables that are created and retained by your classes.

Calling an iDigi Dia Web Service
Calling a web service command in iOS is fairly simple. You set up the connection object, assign a class to handle responses from the connection object and implement the methods that the connection object will call. We are going to set up the command object and assign a handler in the “sendCommand” function:

- (IBAction)sendCommand: (id)sender {    NSLog(@”Sending Command”);    [self.commandField resignFirstResponder];    NSURL *url = [NSURL URLWithString:SERVER_URL];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    [request setHTTPMethod:@"POST"];    NSString *data = [NSString stringWithFormat:REQUEST, GATEWAY, self.commandField.text];    [request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];    [connection start];} 

There is a lot going on in this code. First we send a “resignFirstResponder” message to the text field on the user interface, which will hide the keyboard control. Next, we create an NSMutableURLRequest object that the connection object will send to iDigi. Next we add the xml payload to the URL Request object, substituting the Gateway ID and text input control data for the text placeholders in the REQUEST constant. Next we create an NSURLConnection and assign the XBeeSerialViewController object as the connection delegate. The last line tells the connection object to send an asynchronous request.

We now need to code 5 delegate methods to handle calls from the connection object. The first function we will implement will handle setting up an authenticated session with the iDigi Device Cloud:

- (void)connection: (NSURLConnection *)connection didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge *)challenge {
NSURLCredential *credential = [NSURLCredential credentialWithUser:USERNAME password:PASSWORD
persistence:NSURLCredentialPersistenceForSession];     [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; }

When the connection object sends a web service command to the iDigi Device Cloud, it will receive an authentication challenge, much like how a security prompt will pop up in iDigi Manager Pro™ when using the web service console.

The next method we are going to implement will handle any errors that may come up when this application attempts to send commands to the iDigi Device Cloud:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {    NSLog(@”%@”, [error localizedDescription]);} 

When the connection object successfully connects, it will send a “didReceiveResponse” message to its delegate letting it know that it received back a 200 response from the remote server, and it will send a series of “didReceiveData” messages for each block of data it gets back from the server. Here are the two methods that will respond to those messages:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {    NSLog(@”Received response.”);    [self.data setLength:0];}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {    NSLog(@”Receiving data.”);    [self.data appendData:data];}The last method we need to implement is the “connectionDidFinishLoading” method, which the connection object calls after it finishes loading data from a remote server:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {    NSLog(@”Finished loading data”);    NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];    NSLog(@”%@”, responseText);    [responseText release];}The final step is to test your project using the iPhone simulator in Xcode. Click the “Run” button to launch your project. Enter a command in the text field and touch the “Send Serial Command” button to send your command to your Arduino serial project.

Source Code for Xcode Project
It is simple to create an iOS application that will send ascii serial commands to remote devices using the iDigi Device Cloud and iDigi Dia. You can download the source code for the Xcode project, simply click here.

Upcoming Events
WaveForum 2011 Toronto
October 19-20, 2011

WaveForum has provided education on the latest advances in wireless M2M device networking for more than six years. Now Digihas expanded their educational offering to include WaveForum online webinars and regional WaveForum developers’ conferences.

This October, WaveForum is coming to Toronto, Canada. This two-day event will offer over 20 different technical sessions covering a variety of wireless topics and is designed for a wide range of skill levels.


Take advantage of early bird pricing and save $100 off the price of registration.
But hurry, offer expires September 23, 2011.



Wireless Connectivity in the Backyard
— The iDigi Garden —

iDigi Garden — September is here. We brought in the tomatoes and if somebody doesn’t bring the peppers in soon, I’m taking them all. The iDigi garden has given us some great vegetables and it also demonstrated the effectiveness of our wireless hardware and management tools. Using XBee modulesConnectPort X gateways, theiDigi Device Cloud and a variety of sensors, regulators and related devices we created a self-regulating, self-maintaining irrigation system.


Stay up-to-date with the latest news and information.
Follow Digi on TwitterFacebook and YouTube.


Posted on: No Comments

Leave a Reply

Contact a Digi expert and get started today! CONTACT US

Desktop Site