Skip to content

Latest commit

 

History

History
267 lines (204 loc) · 19 KB

File metadata and controls

267 lines (204 loc) · 19 KB

Create solar panel IoT circuit & send data to IBM Maximo Monitor

[From Drone to Fix - Solar Farm Inspection - Energy Loss Story (Circuit)]

Last Updated: 19 November 2024 Authors: James Petrie & Christophe Lucas
Disclaimer: This code is delivered as-is and is NOT formal IBM documentation in any way.

Table of Contents

Introduction

The objective of this recipe is to enable you to fully reproduce the Energy Loss story of the From Drone to Fix – Solar Farm Inspection using IBM Maximo & Watsonx demo system - from buying the IoT circuit to sending live data to Monitor, to creating a service request for a drone inspection based on a power drop or anomaly. Note: If you wish to reproduce the Energy Loss story without having to purchase the hardware, follow this alternative Send csv data to IBM Maximo Monitor with IoT Platform SDK & Cloud Pak For Data recipe.

In this recipe, you will:

  1. get the list of hardware elements to buy to reproduce the IoT solar panel system.
  2. set up the IoT solar panel (hardware & code parts), create a device in Monitor and send data to it.
  3. create an anomaly function on the power reading, create alerts and a dashboard in Monitor to visualize the solar panel readings. Re-play the whole Energy Loss story by submitting a service request based on an alert.

Products Used: IBM Maximo Monitor version 8.11.11, part of the IBM Maximo Application Suite 8.11.15.

image

Prereqs & hardware ingredients

Prerequisites & system used

In order to run this recipe, you need a Maximo Application Suite (MAS) ID with, at the minimun, Application Entitlement - Base & Administration entitlement - Base entitlements, as well as Administrator access to Monitor and IoT applications.

System Used: All below code was implemented using a Windows 11 Enterprise x64 laptop.

Hardware Buy List

This table lists the components that were bought to build this system. Please note that the sample buy links are just provided as examples and to show the item images, but you can purchase those at your preferred vendor site.

# Item Item Description Sample Buy Link
1 Atem Solar Panel 12v 10W Solar Panel. Note that any similar panel with red and black 'crocodile clips' to connect to should do. 12V 10W Mono Solar Panel
2 Arduino R3 Arduino microcontroller Arduino Uno REV3
3 INA219 5 x DC current sensor for reading solar panel power output 5 x INA219 DC Current Power
4 Jumper wires For connecting up circuit Jump Cable 40pcs
5 LED Light Emitting Diodes for excess load consumption 5mm Light Emitting Diodes
6 Display case 20x30x20cm box for circuit Acrylic Display Case
7 USB-A to USB-B Cable For connecting Arduino to laptop USB-A to USB-B Cable
8 [Optional] Desk Lamp To have consistent light source over the panel Swing Arm Desk Lamp
9 [Optional] Light Bulb To have consistent light source 9.8w Light Buld

Create device

Create device type in Monitor

  1. Open MAS > Monitor > Create a device type
  2. Choose basic template and select Next
  3. Name the device type in the format- <Initials>_<Device> e.g. JP_SolarPanel – then select Create
  4. In the Metrics tab, select Add metric + and add the following metrics:
    Metric Display name Event Type Unit
    sp_p SolarPanel_Power event NUMBER mW
    sp_bv SolarPanel_BusVoltage event NUMBER v
    sp_sv SolarPanel_ShuntVoltage event NUMBER mV
    sp_c SolarPanel_current event NUMBER mA

Create device in Monitor IoT Tool

  1. Move back to MAS suite navigator > Tools > IoT
  2. Select Add Device in top right
  3. Enter previously created device_type into device type field
  4. Name the device in the format - <Device type>_<Identifier> e.g. JP_SolarPanel_001 – then select Next
  5. Enter any relevant device information (Optional)
  6. Select Next through Device information, gateway and security tabs, and finally Finish on summary tab
  7. Record Authentication token on next screen as this will be used later

This picture highlights the steps you just completed: image

Set up hardware

Create circuit

  1. Establish the following connections on the board:
    • Solar Panel Positive -> Sensor Power In
    • Sensor Power out -> LED (3 were used in sequence to consume enough power)
    • LED output -> Solar Panel Negative
    • Sensor 5V Power -> Microcontroller 5V Power source
    • Sensor GND -> Microcontroller GND
    • Sensor SDA -> Microcontroller pin A5
    • Sensor SDL -> Microcontroller pin A4
  2. At this stage, observe how the LED lights react to you covering and uncovering the panel by getting less or more bright - that brightness relates to that power production which we will later see in Monitor
  3. Connect Arduino to laptop using USB cable

image

Create config - Get your MAS Monitor IoT Tool details & certificate

To send data to Monitor's IoT Tool, you will use the Publishing Device Events command of Monitor's IBM Watson IoT Platform Python SDK. To connect, you will need a myConfig Configuration cell, including your IoT Tool's "orgId" & "domain" values, as well as its "caFile" certifcate.

Here is how to get "orgId" & "domain":

  1. "orgId": from Monitor's home menu, click Open the IoT tool. On the top-right of the screen just below your user name, copy the ID - that is the value of "orgId".
  2. "domain": observe the URL of your IoT Tool home screen. As per the image example, if your IoT Tool URL = https://yourgeo.iot.yourgeomas.xyz.com/, then your "domain" = iot.yourgeomas.xyz.com.

To get the "caFile" certificate, use Firefox (not Chrome) and:

  1. In the Watson IoT Platform browser bar, click the Security icon just next to the URL. Click the Connection Secure line. Then click the More information line. That will open a pop-up window.
  2. On the popped-up window, click View Certificate. That will open a new tab on your browser. On the opened Certificate browser tab, click the ISRG Root X1 tab. In the Miscellaneous section, click the PEM (chain) link. That will download a certificate.pem file which name should look like: iot-yourgeomas-xyz-com.pem. Save it locally.

Implement code

  1. Download and install Arduino IDE: https://www.arduino.cc/en/software

  2. With the Arduino plugged into your device, select the COM port that shows Arduino Uno as per below image

  3. Copy the below code into a new file and upload to arduino, noting the baud rate of 115200. This will output 1 line to serial every second with the format: <sp_sv>,<sp_bv>,<sp_v>,<sp_c>,<sp_p>\n

    Note: Full file is saved here: arduino_reading.ino


    #include <Adafruit_INA219.h>
    
    Adafruit_INA219 ina219;
    
    void setup(void) 
    {
    Serial.begin(115200); // This is the baud rate and will be used in python code
    while (!Serial) {
        delay(1);
    }
    
    auto connected = false;
    while (!connected) {   
        if (ina219.begin()) {
            connected = true;
        }
        Serial.println("Connecting...");
        delay(1000);
    }
    
    ina219.setCalibration_16V_400mA();
    
    Serial.println("Measuring voltage and current with INA219 ...");
    }
    
    void loop(void) 
    {
        float shuntVoltage = ina219.getShuntVoltage_mV();
        float busVoltage = ina219.getBusVoltage_V(); 
        float current = ina219.getCurrent_mA();
        float power_mW = ina219.getPower_mW();
        float voltage = busVoltage + (shuntVoltage / 1000);
    
        Serial.print(shuntVoltage); Serial.print(',');
        Serial.print(busVoltage);Serial.print(',');
        Serial.print(voltage);Serial.print(',');
        Serial.print(current);Serial.print(',');
        Serial.print(power_mW);Serial.print(',');
        Serial.println("");
    
        delay(1000);
    }
  4. On VSCode or any other IDE that supports python, copy the below python code to pick up the line output from arduino and send to IoT:

    Note: Full file is saved here: relay.py

    import datetime
    import argparse
    import serial
    
    import wiotp.sdk.device as wiotpgw
    
    def commandProcessor(cmd):
        print(f"Command received: {cmd.data}")
    
    
    def onPublishCallback():
        print(f"Confirmed event received by WIoTP\n")
    
        
    deviceOptions = wiotpgw.parseConfigFile("config.cfg")
    deviceCli = wiotpgw.DeviceClient(config=deviceOptions, logHandlers=None)
    deviceCli.commandCallback = commandProcessor
    csuccess = deviceCli.connect()
    
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-E", "--event", required=False, default="event", help="type of event to send")
    parser.add_argument("-N", "--nummsgs", required=False, type=int, default=1, help="send this many messages before disconnecting")
    parser.add_argument("-D", "--delay", required=False, type=float, default=5, help="number of seconds between msgs")
    args, unknown = parser.parse_known_args()
    
    while (True):
        stream = serial.Serial(port, baudrate=115200)
        data = [int(float(item)) for item in stream.readline().decode('utf-8').split(',')[:-1]]
    
        if (len(data) > 0):
            output = {
                'sp_sv': data[0],
                'sp_bv': data[1],
                'sp_lv': data[2],
                'sp_c': data[3],
                'sp_p': data[4],
                'time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 
            }
    
        success = deviceCli.publishEvent(args.event, "json", data, qos=0, onPublish=onPublishCallback)
        if not success:
            print("Not connected to WIoTP")
    
        time.sleep(10)

Play the 'Energy Loss' story end-to-end

Now that the data is flowing, let's visualize it in Monitor and play the Energy Loss story end-to-end.

Create Anomaly Function & Dashboard

Create the power_anomaly data item:

  1. From the Monitor left menu, Devices tab, select your Device Type e.g. JP_SolarPanel and click Setup device type.
  2. In the Data Items menu, click Create metric under the Batch data metric (calculated) section. Select KMeansAnomalyScore function. Click Next. In the input_item field, select sp_p (the power reading) and set windowsize to 12. Click Next. On final screen, untick Auto schedule and set Executing every to 5 Minutes and Calculating the last to 30 Days. Name you data item power_anomaly and click Create. Wait 5 minutes for the power_anomaly to be calculated.

Create a Dashboard:

  1. From the Monitor Setup menu, Devices tab, select your Device (NOT the Device Type) e.g. JP_SolarPanel_001 and click the + buttom next to the Metrics Dashboard tab. Name it Overview.
  2. Reproduce a Dashboard similar to the one in below picture i.e. (a) create a Image card and add a nice picture to it, (b) create a Value/KPI card and select the sp_c, sp_bv, sp_p data items, call it Last Readings, (c) create a Value/KPI with , (d) importantly create a Time Series and display all readings on it, including the power_anomaly data item you just created.

Create Alert & Service Request

On the Time Series plot of the dashboard, select sp_p and power_anomaly only and notice the spikes of the power_anomaly whenever there's a power drop. Observe the value of those spikes and take note e.g. you will likely notice that the power_anomaly score spikes to values above 16 each time there is a drop.

Create the alert_power_anomaly data item and add it to the dashboard :

  1. From the Data Items menu, click Create metric under the Batch data metric (calculated) section. Select AlertHighValue and click Select.
  2. Click Next. Select power_anomaly in input_item, in upper_threshold enter the 'spike' value just mentionned e.g. 16. Select High in Severity and New in Status. Click next and on last screen. Click Create.
  3. Back to the dashboard, click Edit dashboard (top right) and add an Alert table as per image below.

Finally, you can now create a Service Request for a visual drone inspection from the Alert table.

image Well done - you made it !