Mobile Black Box Part 3 : iOS App coded in Swift 3


drfrank-color The last part of our IoT invention is the iOS App. The user interface looks like this:
app-screenshot

This App was created utilizing the IoT client library for iOS located here. This library encapsulates the REST services that IoT exposes.

The App is a Single View Application. In ViewController.swift we use the following code:

Device data:

        let URN: String = "urn:drfranz:blackbox"

        let PROVFILE: String = "alex004"

        let PASSPHRASE: String = "********" //get it from text field

For setting the sensor data capture we do the following:

        motionManager = CMMotionManager()

        motionManager.accelerometerUpdateInterval = 1

        motionManager.startAccelerometerUpdates()

        motionManager.startMagnetometerUpdates()

        motionManager.startDeviceMotionUpdates()

        motionManager.startGyroUpdates()

        myTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)

For  activating the device:

var dcd: DirectlyConnectedDevice

        do {

            dcd = try DirectlyConnectedDevice(path: Bundle.main.bundlePath + "/" + PROVFILE, password: PASSPHRASE)

        } catch let exc as NSError {

            print("Caught exception from DirectlyConnectedDevice constructor: " + exc.localizedDescription)

            return

        }

        // This closure will be called if the device is activated

        // It sends a single message to the server.

        let sendMessage: (_ endpointId: String?, _ error: ClientError?) -> () = {

            endpointId, error in

            // If there was an error handle the error

            if (error != nil) {

                print (error as Any )

                return

            }

            do {

                // Set up a virtual device based on your device model

                try dcd.getDeviceModel(deviceModelUrn: URN, callback: { (deviceModelIn, error) in

                    if (error != nil) {

                        print(error as Any)

                        return

                    }

                    let deviceModel = deviceModelIn!

                    do {

                        self.m_virtualDevice = try dcd.createVirtualDevice(deviceId: dcd.getEndpointId(), deviceModel: deviceModel)

                        

                        if (self.m_virtualDevice != nil){

                            print("Virtual device created.")

                        }

                        else{

                            let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)

                            alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))

                            self.present(alert, animated: true, completion: nil)

                        }

                    } catch let exc as NSError {

                        print("Cannot create virtual device: " + exc.localizedDescription)

                    }

                })

            } catch let exc as NSError {

                print("Recieved exception setting attribute: " + exc.localizedDescription)

            }

        }

        do {

            if !(dcd.isActivated()) {

                try dcd.activate(callback: sendMessage, deviceModels: URN)

            } else {

                sendMessage(dcd.getEndpointId(), nil)

            }

        } catch let exc as NSError {

            print("Caught exception from DirectlyConnectedDevice: " + exc.localizedDescription)

        }

 

For sending messages we use the following:

    /*********************************

    *

    * send sensor data to IoT CS via virtual device object

    *

    **********************************/

    func sendMsg(acc: CMAccelerometerData, mag: CMMagnetometerData, mot: CMDeviceMotion, gyr: CMGyroData){
        backgroundQueue.async {

            print("Dispatched to queue")

            do{

            _ = try self.m_virtualDevice.set(attributeName: "ACCx", attributeValue: acc.acceleration.x as AnyObject)

            _ = try self.m_virtualDevice.set(attributeName: "ACCy", attributeValue: acc.acceleration.y as AnyObject)

            _ = try self.m_virtualDevice.set(attributeName: "ACCz", attributeValue: acc.acceleration.z as AnyObject)

                _ = try self.m_virtualDevice.set(attributeName: "MAGx", attributeValue: mag.magneticField.x as AnyObject)

                _ = try self.m_virtualDevice.set(attributeName: "MAGy", attributeValue: mag.magneticField.y as AnyObject)

                _ = try self.m_virtualDevice.set(attributeName: "MAGz", attributeValue: mag.magneticField.z as AnyObject)

            /*if let devicemotionData = motionManager.deviceMotion {

                _ = try m_virtualDevice.set(attributeName: "GRA", attributeValue: devicemotionData.gravity as AnyObject)

                _ = try m_virtualDevice.set(attributeName: "ACC", attributeValue: devicemotionData.userAcceleration as AnyObject)

                _ = try m_virtualDevice.set(attributeName: "ATT", attributeValue: devicemotionData.attitude as AnyObject)

                _ = try m_virtualDevice.set(attributeName: "ROT", attributeValue: devicemotionData.rotationRate as AnyObject)

            }*/

                _ = try self.m_virtualDevice.set(attributeName: "ROTx", attributeValue: gyr.rotationRate.x as AnyObject)

                _ = try self.m_virtualDevice.set(attributeName: "ROTy", attributeValue: gyr.rotationRate.y as AnyObject)

                _ = try self.m_virtualDevice.set(attributeName: "ROTz", attributeValue: gyr.rotationRate.z as AnyObject)

        }catch let e as NSError {

            self.textLog.text = self.textLog.text + "Error: " + e.localizedDescription

        }

    }

}

When the App is running and we move around, the IoT CS receives sensor data like this:

Captura de pantalla 2017-03-23 a las 0.06.51

Next challenge is upload the App to Apple Store and get it approved… Will let you my kind audience guys know…

Enjoy 😉

2 thoughts on “Mobile Black Box Part 3 : iOS App coded in Swift 3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.