Advertisement

Quick Links

NXP Semiconductors
Weather station - Developer
Guide
NXP IoT - Weather Station Developer Guide
Contents
1.
Introduction ..................................................................... 1
2.
Mobile applications.......................................................... 3
Development setup ............................................... 4
Applications architecture ...................................... 4
3.
Cloud application ........................................................... 27
Development setup ............................................. 27
Application architecture ...................................... 28
Plotting measurements in graphs ........................ 42
4.
Broker application.......................................................... 43
JSON structure .................................................... 46
Revision history ..................................................................... 51
© 2019 NXP B.V.
PRELIMINARY
1.

Introduction

NXP's Rapid IoT prototyping kit is a comprehensive,
secure and optimized IoT end node solution with a
user-friendly development environment that enables
anyone to quickly take their idea to a proof-of-concept.
Its architecture is built upon two controllers:
• Kinetis K64F for the main application, powered by
an ARM® Cortex®-M4 core
• Kinetis KW41Z for wireless connectivity, powered
by an ARM® Cortex®-M0+ core
It includes:
• 10-axis motion sensing, thanks to a combo
accelerometer / magneto-meter
• Gyroscope
• Pressure sensor for altitude measurement
• Environmental sensing via temperature/humidity,
ambient light and air quality sensors
• Display capabilities with low-power color screen
• Authentication, identification
• User interfaces with LEDs, buzzer and touch plus
push buttons
• Additional memory for data storage
• Rechargeable battery
The factory application includes USB and
Bluetooth/Thread bootloaders to program your own
firmware without external tool, and several IoT
Rev. 0 1, 1/2019

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the IoT and is the answer not in the manual?

Questions and answers

Summary of Contents for NXP Semiconductors IoT

  • Page 1: Table Of Contents

    Development setup ..........4 NXP’s Rapid IoT prototyping kit is a comprehensive, Applications architecture ........4 secure and optimized IoT end node solution with a Implementation of the main functional blocks ..5 user-friendly development environment that enables Cloud application ............27 Development setup ..........
  • Page 2 In order to allow any user to evaluate this product, NXP has created the “NXP IoT – Weather station” applications. This is a set of applications consisting of a mobile application (available in Android and iOS), a cloud application and a demo FW for the Rapid IoT device.
  • Page 3: Mobile Applications

    Table 1. K64F USB Programming LED Figure 3. USB Programming LED Sequence More information about the Rapid IoT kit can be found in NXP’s website: https://www.nxp.com/support/developer-resources/rapid-prototyping/nxp-rapid-iot-prototyping-kit:IOT- PROTOTYPING 2. Mobile applications The Weather Station platform relies on a mobile application that can be used to connect to the RapidIoT kit, extract the data and post it to the Cloud.
  • Page 4: Development Setup

    2.2.1. Android and iOS application The mobile applications are built in a layered structure, following the “Model-Business-Presentation” design pattern. A simple diagram of the relationship between layers can be found in Figure 4. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 5: Implementation Of The Main Functional Blocks

    Each sensor in the device has its own BLE characteristic where the microcontroller posts the information, so the user can filter the information he will be notified about. NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 6 Figure 5. ‘WSDBleManager’ class header in Android app The ‘BleManagerCallbacks’ includes methods that are called depending on the state that the connection goes through. We can highlight the following methods: NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 7 .setServiceUuid(ParcelUuid.fromString(WSDemoUUID.toString())) .build(); Figure 8. Set scan settings in Android app Once the settings and filter are configured, it starts scanning: bluetoothLeScanner.startScan(filterList, scanSettings, scanCallback); Figure 9. Start scan in Android app NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 8 Below we can see the ‘onBondingRequired’, ‘onBonded’ and ‘onDeviceReady’ methods from the application: @Override public void onBondingRequired(BluetoothDevice device) { super.onBondingRequired(device); bondingRequired = true; Toast.makeText(getApplicationContext(), "Please follow pairing instructions in Notification Bar", Toast.LENGTH_LONG).show(); NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 9 ‘BleManagerGattCallback’. This method should be overwritten with all requests needed to initialize the profile. In our case, we will use it to request the ‘subscription’ to all notifications from the sensors characteristics: NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 10 Once we know the type of measurement we need to convert the data to float and create with it a ‘MeasurementModel’ type object: byte[] rawpressure = characteristic.getValue(); MeasurementModel measurement = MeasurementModel( MeasurementUtils.getPressureMeasurement(rawpressure)); NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 11 Implementation in iOS Similar to the Android application, there is a singleton object for the BLE communication. This object is called ‘sharedBLEInstance’ and is created as follows in the ‘BLEManager’ class: NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 12 CBPeripheral?, advertisementLocalName: String?) Figure 22. BLEManager delegate methods The Rapid IoT device in the iOS application is another Singleton object, so it can be accessed anywhere through the application. This object is updated each time a new Rapid IoT device is connected/disconnected.
  • Page 13 Before starting the scanning, we check that the BLE adapter state is powered on and there is no active scanning already ongoing. In order to scan only for Rapid IoT devices, we need to perform a configuration in the ‘startScan’ method. This is shown in Figure 25. We include only the service UUID we are interested in, in this case the Rapid IoT service UUID.
  • Page 14 Data display screen and nothing in the Bluetooth connection changes. 3- There is no device connected in the application and the user taps in a device. In this case we just start the connection with the new device. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 15 The characteristics we are looking for appear in section 2.3.1, we need to subscribe to those characteristics in order to get notifications each time they are written with a new value. This can be found in Figure 28. NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 16 ‘didUpdateValueFor’ callback method is called. We check what measurement the characteristic that has been written corresponds to and call a delegate method to notify the controller. This is shown in Figure 29. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 17 Refresh Rate in the Settings menu. When it is time to store a measurement, this variable is set to true and the measurement is processed from the HEX string received in the BLE characteristic and stored as float in the ‘Device’ object together with the timestamp. See Figure 30. NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 18 The Android application uses the ‘Paho’ library from the Eclipse group to establish the communication with the broker and publish the messages. This library is included in the build.gradle file from the app: dependencies { [..] implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.1' implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1' [..] NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 19 {..} public void clearDataFromCloud() {..} Figure 32. Broker communication methods in Android app The ‘connect’ method sets up all parameters and executes the connection to the MQ broker: NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 20 The ‘isConnected’ method returns a Boolean to indicate if there is an active connection with the broker. The method ‘publishLastMeasurement’ is used to publish the latest set of measurements to the cloud. NXP IoT – Weather Station Developer Guide PRELIMINARY...
  • Page 21 ‘PostDataMessageModel’ that helps us generating the JSON message that will later be sent to the broker using the ‘publish’ method from the ‘MQTTClient’ class. The last method we are going to review from the ‘MQManager’ class is the ‘clearDataFromCloud’. NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 22 The periodicity of this operation depends on how the user sets it up in the settings menu and the availability of new data. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 23 On the other hand, the ‘ClearDataService’ is used to send a message to the Cloud app, to delete all the data from the current session. It follows a similar structure to the ‘PostDataService’, but in this case the task calls the ‘clearDataFromCloud’ message from the ‘MQManager’. NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 24 When the ‘DataDisplayViewController’ class is loaded in the screen, a new ‘Network’ object is created and initialized. The process of setting up this object is shown in Figure 38. In the ‘Network’ object, the CocoaMQTT library as MQTT client. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 25 DispatchQueue.main.async { if(BLEManager.sharedBLEInstance.isConnected()){ if Persistent.readCloudPostSettings() ?? false{ if(DataValidation.isValidData(device: Device.deviceInstance)){ let getJSON = JSONGeneration.encodeMeasurementJSON(deviceObject: Device.deviceInstance) self.networkSample?.sendDataToServer(data: getJSON, isDatabaseClean: false) else{ print("Cloud post data is not active") Figure 39. Form measurement JSON NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 26 = ClearCloud(SessionID: sessionID) let jsonEncoder = JSONEncoder() let jsonData = try! jsonEncoder.encode(createStructure) print(String(data: jsonData, encoding: String.Encoding.utf8)) return String(data: jsonData, encoding: String.Encoding.utf8) ?? "Unknown JSON" Figure 41. JSONGeneration class NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 27: Cloud Application

    For first time users of ASP.NET MVC technology, it is recommended to check the tutorials from the Microsoft official website to start getting familiar with some concepts that will be explained later on in this document: https://docs.microsoft.com/es-es/aspnet/mvc/overview/getting- started/introduction/getting-started NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 28: Application Architecture

    MAC address, JSON interpretation, Data validation, etc. Model: The Model block contains the data model definition, for example the Rapid IoT device class, etc. Regarding the project organization in Visual Studio, there is one solution called “WeatherStationDemo_CloudApp”.
  • Page 29 Cloud application MAC address of the Rapid IoT device shall be the last 4 digits of the full address (which can be found at the back of the device or in the mobile apps). Figure 44. Web UI: Login view The HTML code for the login form view is shown in Figure 45.
  • Page 30 See Figure 48. At the bottom of the screen, it is possible to configure the time scale in seconds or minutes and set the temperature scale in Celsius or Fahrenheit degrees. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 31 In the ‘Main.cshtml’ file there are two JavaScript functions called ‘initChartsOptions’ and ‘initCharts’. The initialization of the graphs can be found in these functions. More information about how to plot graphically can be found in Section 3.4. NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 32 (i.e., if there has been any session created with those values). If there is an existing session with those parameters, this method will redirect the user to the Data Display View, which is explained in the next section. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 33 RedirectToAction("Main", "DataDisplay", { sessionID = modelLogin.SessionID, MACAddress = modelLogin.bleMACAddress else TempData["ErrorMessage"] = "Error in login, please check that the login data is correct."; return View(); Figure 49. Login controller source code NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 34 //Pass the View a ViewBag variable containing the .csv and .txt formats to display the dropdownlist. ViewBag.Formats = FileFormatDefinition.listFormats.ToList(); ViewBag.SessionID = sessionID; ViewBag.MACAddress = MACAddress; return View(); Figure 50. Data display controller source code – Main method NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 35 This procedure is repeated until the temporary LinkedLists are filled with 30 elements (if the database contains less than 30 elements, the loop will stop beforehand). NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 36 OrderByDescending(x => x.Id).FirstOrDefault(); nextTimestamp = nextDbRow.Measurement.Timestamp; TimeSpan difference = TimeConverter.UnixTimeStampToDateTime(nextTimestamp) - TimeConverter.UnixTimeStampToDateTime(lastTimestamp); switch (timescale) case "Minutes": (difference.TotalMinutes <= -1) //If the time difference is 1 minute or more we can store it NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 37 Once we have all the records of the database stored in the ‘StringWriter’ object, it is just a matter of exporting the text to an external file using ‘StreamWriter’ and UTF8 encoding format. NXP IoT – Weather Station Developer Guide NXP Semiconductors...
  • Page 38 = filename + ".csv"; //Set the text format and add the current datetime to the title Response.ContentType = "text/plain"; Response.AddHeader("content-disposition", "attachment;filename=" string.Format(filename, string.Format("{0:ddMMyyyy}", DateTime.Today))); Response.Clear(); using (StreamWriter writer = StreamWriter(Response.OutputStream, Encoding.UTF8)) writer.Write(sw.ToString()); Response.End(); NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 39 Unique identifier of the entry Automated Int bleMACAddress Last 4 bytes of the MAC address of String the device that took the measurement. Name Name of the device as shown in BLE String advertising NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 40: How To Add A New Measurement To The Database

    ‘Migrations’ folder. The commands sequence to generate a new database migration is the following: 1. enable-migrations 2. add-migration ‘addYourMigrationNameHere 3. update-Database -ConnectionString "Data Source= aanon59uu774jt.cq4m2m0a8jif.us-west- 2.rds.amazonaws.com,1433;Initial Catalog= aanon59uu774jt;User Id=WeatherStationDemoUser;password=wsdadmin12345!" -ConnectionProviderName "System.Data.SqlClient" NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 41 ‘DataModels’ folder, go to the ‘Measurement’ class and add the new value as we did in Figure 14. On the other hand, open the ‘DatabaseOperations’ class in the ‘Utils’ folder, and modify the ‘checkUserLimitAndAddMeasurementToDatabase’ method to include this new parameter. This modification is shown in Figure 59. NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 42: Plotting Measurements In Graphs

    Once we have the JSON with all the information from the measurements, they need to be parsed and plotted in the graphs. Let’s see an example of how it is done with the humidity measurement in Figure NXP IoT – Weather Station Developer Guide PRELIMINARY...
  • Page 43: Broker Application

    On the other side, the broker application is subscribed to these topics. Every time a topic is written, the broker application parses the JSON object received and stores the information in the database. NXP IoT – Weather Station Developer Guide NXP Semiconductors...
  • Page 44 = true; Figure 62. Broker app – Main loop The endpoint information can be found in the source code in the ‘BrokerAccountInfo’ class. These parameters are shown in Figure 63. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 45 = ConnectionFactory(BrokerAccountInfo.AWS_WSD_ENDPOINT); _connection = connectionFactory.CreateConnection(BrokerAccountInfo.ACTIVEMQ_USERNAME, BrokerAccountInfo.ACTIVEMQ_PASSWORD); _connection.Start(); catch (Exception ex) Console.WriteLine(ex); Console.WriteLine("Could not start listener. Press <ENTER> to exit."); Console.Read(); […] Figure 64. Broker app – Listener class constructor NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 46: Json Structure

    First it is necessary to subscribe for the iOS topic in the broker application. Once subscribed, the method will be continually looping while waiting for new incoming messages in the topic. This can be seen in Figure 65. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 47 RapidIoTDevice object. The method to parse the JSON object is shown in Figure 66. Finally, if the RapidIoTDevice object is not null, we can ensure there is a new message to store in the database and proceed to store it. NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 48 The procedure to subscribe and process the measurements coming from the Android application is very similar. We just need to change the iOS topic name for the Android topic name. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 49 "Values (@Name, @SessionID,@Meas_Temp,@Meas_Humid,@Meas_Pres,@Meas_Light,@Meas_Time,@bleMACAddress)" , con); insertCommand.Parameters.AddWithValue("@Name", rapidIoTDevice.Name); insertCommand.Parameters.AddWithValue("@SessionID", rapidIoTDevice.SessionID); insertCommand.Parameters.AddWithValue("@Meas_Temp", rapidIoTDevice.Measurement.Temperature); insertCommand.Parameters.AddWithValue("@Meas_Humid", rapidIoTDevice.Measurement.Humidity); insertCommand.Parameters.AddWithValue("@Meas_Pres", rapidIoTDevice.Measurement.Pressure); insertCommand.Parameters.AddWithValue("@Meas_Light", rapidIoTDevice.Measurement.Light); insertCommand.Parameters.AddWithValue("@Meas_Time", rapidIoTDevice.Measurement.Timestamp); insertCommand.Parameters.AddWithValue("@bleMACAddress", rapidIoTDevice.bleMACAddress); insertCommand.ExecuteNonQuery(); con.Close(); Figure 67. Add a measurement to the database NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 50 Figure 68. Subscribe to Clear database topic Then we proceed to parse the message into a ‘ClearCloud’ object which contains the session ID. This can be seen in Figure 69. NXP IoT – Weather Station Developer Guide PRELIMINARY NXP Semiconductors...
  • Page 51: Revision History

    WHERE SessionID = '" + mSessionID + "'", con)) deleteCommand.ExecuteNonQuery(); con.Close(); Figure 70. Delete all measurements from database Revision history Table 2. Sample revision history Revision number Date Substantive changes 01/2019 Initial release NXP IoT – Weather Station Developer Guide NXP Semiconductors PRELIMINARY...
  • Page 52 Information in this document is provided solely to enable system and software How to Reach Us: implementers to use NXP products. There are no express or implied copyright licenses Home Page: granted hereunder to design or fabricate any integrated circuits based on the nxp.com information in this document.

Table of Contents