IoT: raspberry pi 3 how to blink led from iPhone

Internet of Things: raspberry pi 3 – how to blink led from iPhone?

Here’s a tech stack:
– raspberry pi 3 + led
– node-red hosted in AWS/anywhere – should be available in internet
– node js script on raspberry pi connected to node-red via web socket
– swift/ios app which makes http requests to node-red

Let’s start from node-red configuration (it’s a really cool tool for wiring together hardware devices, APIs and online services). All we need is to have “http GET” input, let specify the following path “/mmled/status” for it. and we want to wire it with Output/”Listen on” “web socket” with “/ws/mmled” path. We might also want to add “pay load” node.
So with several “debug” nodes (convenient way to debug our endpoint) it should look something like this:

nodered

At this point if we will GET https://{nore-red-host}/mmled/status?value=1 we will see the following things:
– {“value”: 1} in the debug panel
– the same message we will get in case if we are listening the “wss://{nore-red-host}/ws/mmled” socket.

Let’s check it, here is the node js “server” script which we going to start like “sudo node server” on raspberry pi:

var W3CWebSocket = require('websocket').w3cwebsocket;
var Gpio = require('onoff').Gpio;
var led = new Gpio(17, 'out');  
var client = new W3CWebSocket('wss://{node-red-host}/ws/mmled');
 
client.onerror = function() {
    console.log('Connection Error');
};
 
client.onopen = function() {
    console.log('WebSocket Client Connected');
};
 
client.onclose = function() {
    console.log('echo-protocol Client Closed');
    if (led) led.unexport();
};
 
client.onmessage = function(e) {
    if (typeof e.data === 'string') {
        console.log("Received: '" + e.data + "'");
        try {
            var data = JSON.parse(e.data);
            var newValue = parseInt(data.value);
            console.log('got new value = ' + newValue);
            led.writeSync(newValue);
        } catch (ex) {
            console.log('invalid JSON in e.data');
        }
    }
};

Ok, let’s digg into the magic, first of all what is

var Gpio = require('onoff').Gpio;
var led = new Gpio(17, 'out');

if you will google “raspberry pi 3 pins” you’ll find where “GPIO 17” – you basically need to connect it to resistor + led + GND
after that you’ll have a chance to turn led on with this line – “led.writeSync(1);” and turn it off with “led.writeSync(0);“. So the circuit is the following:
raspberry pi [DPIO 17 pin] -> resistor -> led -> raspberry pi [GND pin]

Everything else we need to connect and listen socket and to react on the value change. run the script with

sudo node server

and try to GET https://{node-red-host}/mmled/status?value=1
and and try to GET https://{node-red-host}/mmled/status?value=0 to toggle the led. It’s awesome, at this step you can enable/disable your LED from internet!

Let’s create a new “single view” xcode project and drop a “switch” UI element on the view. Go to “Assistant editor” and bind the switch’s “action” to the code. Here is the controller’s code:

import UIKit
 
class ViewController: UIViewController {
 
    let ledUrl = "https://{node-red-host}/mmled/status"
 
    func setLed(status: Bool) {
        let finalUrl = ledUrl + "?value=" + (status ? "1" : "0")
        print("final url = " + finalUrl)
        let nsUrl = NSURL(string: finalUrl)
        let task = NSURLSession.sharedSession().dataTaskWithURL(nsUrl!) {(data, response, error) in
            print(NSString(data: data!, encoding: NSUTF8StringEncoding))
        }
 
        task.resume()
    }
 
    @IBAction func onChange(sender: UISwitch) {
        setLed(sender.on);
    }
 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

It’s just sending GET request with the value 1 or 0 on toggle/switch change. That’s it, if you’ll run the app and toggle the switch you’ll see the message in the “debug” node, and you’ll see your LED blinking which is Awesome! You might go further and replace led with relay+real lamp, but it’s a different story.

Here’s an EPIC demo video, just for fun and self-motivation.

Social Share Toolbar