{"id":249,"date":"2014-08-05T02:17:56","date_gmt":"2014-08-05T02:17:56","guid":{"rendered":"http:\/\/bitcows.com\/?p=249"},"modified":"2014-08-05T02:17:56","modified_gmt":"2014-08-05T02:17:56","slug":"create-a-socket-based-iphone-app-and-server-for-raspberry-pi","status":"publish","type":"post","link":"https:\/\/bitcows.com\/?p=249","title":{"rendered":"Create A Socket Based iPhone App and Server for Raspberry Pi"},"content":{"rendered":"<p>If you read my <a href=\"http:\/\/bitcows.com\/?p=209\">previous article<\/a> about controlling a Raspberry Pi with an iPhone. This article expands on that and shows you how to create a socket based iPhone app and server to do even more!<\/p>\n<p><strong>Required items:<\/strong><br \/>\n&#8211; Xcode<br \/>\n&#8211; Python<br \/>\n&#8211; WiFi<br \/>\n&#8211; Patience<br \/>\n&#8211; <a href=\"http:\/\/twistedmatrix.com\/trac\/wiki\/Downloads\" target=\"_blank\" rel=\"noopener\">Twisted<\/a> <\/p>\n<p><strong>Assumptions:<\/strong><br \/>\n&#8211; You read the last article<br \/>\n&#8211; You know how to access your Pi via SSH<\/p>\n<p><strong>Lets begin<\/strong><br \/>\nYou should already have python on your Raspberry Pi but you might not have twisted. So in order to install that open a command line and type in the following command. This will install the twisted module onto your Raspberry Pi.<\/p>\n<pre class=\"prettyprint\">sudo apt-get install python-twisted<\/pre>\n<p>If you don&#8217;t want to type the server code you can get the server here if you like. In  your terminal just copy and past the following lines.<\/p>\n<pre class=\"prettyprint\">wget http:\/\/mypocket-technologies.com\/iphoneserver<\/pre>\n<p>Here we have the python script that is responsible for listening to the network and turning on or off the LED. You will note that this is a little different script than from my <a href=\"http:\/\/bitcows.com\/?p=209\">previous article<\/a> but it does the exact same thing. <\/p>\n<pre class=\"prettyprint\">from twisted.internet.protocol import Protocol, Factory\nfrom twisted.internet import reactor\n\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BOARD) ## Use board pin numbering\nGPIO.setup(7, GPIO.OUT) ## Setup GPIO Pin 7 to OUT\n\nclass RaspberryLight(Protocol):\n\tdef connectionMade(self):\n\t\t#self.transport.write(\"\"\"connected\"\"\")\n\t\tself.factory.clients.append(self)\n\t\tprint \"clients are \", self.factory.clients\n\n\tdef connectionLost(self, reason):\n\t\tprint \"connection lost \", self.factory.clients\n\t\tself.factory.clients.remove(self)\n\n\n\tdef dataReceived(self, data):\n\t\t\tmsg = \"\"\n\n\t\t\tif (data == 'P7H'):\n\t\t\t\tmsg = \"Pin 7 is now High\"\n\t\t\t\tGPIO.output(7, True)\n\n\t\t\telif (data == 'P7L'):\n\t\t\t\tmsg = \"Pin 7 is now Low\"\n\t\t\t\tGPIO.output(7, False)\n\n\n\t\t\tprint msg\n\nfactory = Factory()\nfactory.protocol = RaspberryLight\nfactory.clients = []\n\nreactor.listenTCP(7777, factory)\nprint \"RaspberryLight server started\"\nreactor.run()\n<\/pre>\n<p>Once you have python script in place you can start the server<\/p>\n<pre class=\"prettyprint\">sudo nice -10 python iphoneserver<\/pre>\n<p><strong>ALRIGHT ALREADY GET TO THE IPHONE CODE<\/strong><br \/>\nFirst we will deal with the <em><strong>ViewController.h<\/strong><\/em> file.<br \/>\nAdd the following in the interface. We need variables for input and output steams as well as the UISegmentedControl.<br \/>\nWell also need to make a Method so that the toggle button will do something.<\/p>\n<pre class=\"prettyprint\">@property (nonatomic, retain) NSInputStream *inputStream;\n@property (nonatomic, retain) NSOutputStream *outputStream;\n@property (weak, nonatomic) IBOutlet UISegmentedControl *lightToggle;\n\n- (IBAction)ToggleLight:(id)sender;\n<\/pre>\n<p>Now make sure you add the delegate <em><strong>NSStreamDelegate<\/strong><\/em> to the interface<\/p>\n<pre class=\"prettyprint\">@interface ViewController : UIViewController&lt;NSStreamDelegate&gt;<\/pre>\n<p><strong>Moving On<\/strong><\/p>\n<p>So believe it or not connecting to a network is pretty easy. Theres basically only a few lines of code..<br \/>\nThe first thing we want to do is create a method that will do the connection. So in your <strong><em>ViewController.m<\/em><\/strong> file of your controller you will want to add this. Replace the [YOUR IP ADDRESS HERE] with your own IP (something like 192.168.0.112)<\/p>\n<pre class=\"prettyprint\">- (void)initNetworkCommunication {\n    CFReadStreamRef readStream;\n    CFWriteStreamRef writeStream;\n    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@\"[YOUR IP ADDRESS HERE]\", 7777, &readStream, &writeStream);\n    _inputStream = (NSInputStream *)CFBridgingRelease(readStream);\n    _outputStream = (NSOutputStream *)CFBridgingRelease(writeStream);\n    \n    [_inputStream setDelegate:self];\n\t[_outputStream setDelegate:self];\n    \n    [_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];\n\t[_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];\n    \n    [_inputStream open];\n\t[_outputStream open];\n    \n}<\/pre>\n<p>Next well need to call that so in the <strong>viewDidLoad<\/strong> lets make our networkConnection<\/p>\n<pre class=\"prettyprint\">[self initNetworkCommunication];<\/pre>\n<p>In that same <strong>viewDidLoad<\/strong> set the segmentIndex so that it off by default.<\/p>\n<pre class=\"prettyprint\">_lightToggle.selectedSegmentIndex = 1;<\/pre>\n<p>Now we need to connect our button with some code. Here we are getting the sender, in this case a UISegmentedControl and grabbing the tag and which segmentIndex that has been selected. We build a NSString and use the NSData Object to encode and send it to our output stream. The response string should either be P7L or P7H (high or low)<\/p>\n<pre class=\"prettyprint\">- (IBAction)ToggleLight:(id)sender {\n    \n    UISegmentedControl *button = ((UISegmentedControl*)sender);\n    long tag = button.tag;\n    \n    NSString *response  = [NSString stringWithFormat:@\"P%ld%@\", tag , button.selectedSegmentIndex?@\"L\" : @\"H\"];\n    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];\n    [_outputStream write:[data bytes] maxLength:[data length]];\n    \n}<\/pre>\n<p>If we open up our storyboard we want to do some connecting. So first grab a segment button and drag it to into the UIView. In the Attribute Inspector find the tag attribute and set it to 7. This is our pin number we are targeting.<br \/>\n<img decoding=\"async\" src=\"http:\/\/bitcows.com\/wp-content\/uploads\/2014\/08\/Screen-Shot-2014-08-04-at-7.03.44-PM.png\" alt=\"\" width=\"500\" class=\"alignnone size-full wp-image-269\" \/><\/p>\n<p>Next click the Connections Inspector that&#8217;s the circle with the arrow in it <img decoding=\"async\" src=\"https:\/\/cdn3.iconfinder.com\/data\/icons\/iconic-1\/32\/arrow_right_alt1-512.png\" width=\"20\"\/>. Now look for the touch up inside event, and click the + symbol and drag the line to the first responder box icon, then choose ToggleLight.<\/p>\n<p>Do the same thing for Referencing Outlets only drag it to the View Controller icon.<br \/>\n<img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/bitcows.com\/wp-content\/uploads\/2014\/08\/Screen-Shot-2014-08-04-at-7.09.39-PM.png\" alt=\"\" width=\"524\" height=\"354\" class=\"alignnone size-full wp-image-272\" \/><br \/>\n<img decoding=\"async\" src=\"http:\/\/bitcows.com\/wp-content\/uploads\/2014\/08\/Screen-Shot-2014-08-04-at-7.04.11-PM.png\" alt=\"\" width=\"200\" class=\"alignnone size-full wp-image-270\" \/><\/p>\n<p>That should be it! run it and you should see messages coming over the terminal!<\/p>\n<p><strong>UPDATE<\/strong>: Want to run your python script automatically? Heres what you need to do.<\/p>\n<p>-Create a file called automaterStarter.sh<br \/>\nType in <\/p>\n<pre class=\"prettyprint\">\n\n#! \/bin\/sh\n# \/etc\/init.d\/automatorlauncher.sh\n\n### BEGIN INIT INFO\n# Provides:          automaterStarter.sh\n# Required-Start:    $remote_fs $syslog\n# Required-Stop:     $remote_fs $syslog\n# Should-Start:      $portmap\n# Should-Stop:       $portmap\n# X-Start-Before:    nis\n# X-Stop-After:      nis\n# Default-Start:     2 3 4 5\n# Default-Stop:      0 1 6\n# X-Interactive:     true\n# Short-Description: Example initscript\n# Description:       This file should be used to construct scripts to be\n#                    placed in \/etc\/init.d.\n### END INIT INFO\ncd \/home\/pi\nsudo nice -10 python iphoneserver.py&\ncd \/<\/pre>\n<p>Save the file and place it in your <strong><em>\/etc\/init.d<\/em><\/strong> folder of your raspberry pi. Lastly run this command<\/p>\n<pre class=\"prettyprint\">sudo update-rc.d automaterStarter.sh defaults<\/pre>\n<p>Reboot and your should have python running automatically<\/p>\n<p><a href=\"https:\/\/github.com\/djmason9\/SocketApp\/releases\/tag\/1.0.0\" target=\"_blank\" rel=\"noopener\">Get the project code here.<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you read my previous article about controlling a Raspberry Pi with an iPhone. This article expands on that and shows you how to create a socket based iPhone app and server to do even more! Required items: &#8211; Xcode &#8211; Python &#8211; WiFi &#8211; Patience &#8211; Twisted Assumptions: &#8211; You read the last article&hellip;<\/p>\n<p class=\"more-link\"><a href=\"https:\/\/bitcows.com\/?p=249\" class=\"themebutton\">Read More<\/a><\/p>\n","protected":false},"author":1,"featured_media":277,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12,15,16],"tags":[49,59],"class_list":["post-249","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-electronics","category-ios","category-code-examples","tag-ios-2","tag-raspberry-pi"],"_links":{"self":[{"href":"https:\/\/bitcows.com\/index.php?rest_route=\/wp\/v2\/posts\/249","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bitcows.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bitcows.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bitcows.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bitcows.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=249"}],"version-history":[{"count":0,"href":"https:\/\/bitcows.com\/index.php?rest_route=\/wp\/v2\/posts\/249\/revisions"}],"wp:attachment":[{"href":"https:\/\/bitcows.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=249"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bitcows.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=249"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bitcows.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=249"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}