Skip to content

[WIRE-422] Custom templates support #157

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .licenses/go/github.com/arduino/iot-client-go/v2.dep.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: github.com/arduino/iot-client-go/v2
version: v2.0.2
version: v2.0.3
type: go
summary:
homepage: https://pkg.go.dev/github.com/arduino/iot-client-go/v2
Expand Down
Binary file not shown.
70 changes: 70 additions & 0 deletions TT/resources/sketches/ToSiteWise 3/ToSiteWise_3_may08a.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#include <ArduinoIoTCloud.h>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you intentionally put the sitewise template in the repo as example?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it was my error... this is a test template used in manual test. Removed, thanks.


#include "thingProperties.h"

void setup() {
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without blocking if none is found
delay(1500);

// Defined in thingProperties.h
initProperties();

// Connect to Arduino IoT Cloud
ArduinoCloud.begin(ArduinoIoTPreferredConnection, false, "mqtts-sa.iot.oniudra.cc");

setDebugMessageLevel(4);
ArduinoCloud.printDebugInfo();
}

unsigned long previousMillis = 0;
const long interval = 5000; //ms
bool increase = true;

// the loop function runs over and over again forever
void loop() {
ArduinoCloud.update();

unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
increase = !increase;

if(pressure < 2){
pressure = 8;
}
if(temperature < 2){
temperature = 25;
}

int randNumber = random(10.0, 70.0);
if(!increase){
randNumber = -randNumber;
}
float diff = (float)randNumber / 100.0;

pressure = pressure + diff;
temperature = temperature + diff;

Serial.println(AIOT_CONFIG_LIB_VERSION);
Serial.println("2.1");
}

}

/*
Since Temperature is READ_WRITE variable, onTemperatureChange() is
executed every time a new value is received from IoT Cloud.
*/
void onTemperatureChange() {
// Add your code here to act upon Temperature change
}

/*
Since Pressure is READ_WRITE variable, onPressureChange() is
executed every time a new value is received from IoT Cloud.
*/
void onPressureChange() {
// Add your code here to act upon Pressure change
}
18 changes: 18 additions & 0 deletions TT/resources/sketches/ToSiteWise 3/sketch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"cpu": {
"fqbn": "arduino:mbed_nano:nanorp2040connect",
"name": "",
"type": "serial"
},
"secrets": [
{
"name": "SECRET_SSID",
"value": ""
},
{
"name": "SECRET_OPTIONAL_PASS",
"value": ""
}
],
"included_libs": []
}
23 changes: 23 additions & 0 deletions TT/resources/sketches/ToSiteWise 3/thingProperties.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Code generated by Arduino IoT Cloud, DO NOT EDIT.

#include <ArduinoIoTCloud.h>
#include <Arduino_ConnectionHandler.h>

const char SSID[] = SECRET_SSID; // Network SSID (name)
const char PASS[] = SECRET_OPTIONAL_PASS; // Network password (use for WPA, or use as key for WEP)

void onPressureChange();
void onTemperatureChange();

float pressure;
CloudTemperature temperature;

void initProperties(){

ArduinoCloud.addProperty(pressure, READWRITE, 30 * SECONDS, onPressureChange);
ArduinoCloud.addProperty(temperature, READWRITE, 30 * SECONDS, onTemperatureChange);

}

WiFiConnectionHandler ArduinoIoTPreferredConnection(SSID, PASS);

23 changes: 23 additions & 0 deletions TT/resources/thing_1.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
id: tositewise-3-2547e
name: ToSiteWise 3
sketch_template: ToSiteWise 3
sketch_name: ToSiteWise_3_may08a
timezone: ""
tags:
- key: integration
value: sitewise
variables:
- id: pressure
name: pressure
type: FLOAT
permission: READ_WRITE
update_parameter: 30
update_strategy: TIMED
variable_name: pressure
- id: temperature
name: temperature
type: TEMPERATURE
permission: READ_WRITE
update_parameter: 30
update_strategy: TIMED
variable_name: temperature
1 change: 1 addition & 0 deletions TT/template.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"title":"OK - RP with binaries","name":"OK - RP with binaries","description":"\u003cp\u003eBIN CONTENT INCLUDED\u003c/p\u003e","template":{"things":["thing_1.yaml"],"dashboards":null,"triggers":null},"resources":{"things":1,"dashboards":0,"triggers":0,"max_variables":2},"compatible_boards":[{"fqbn":"arduino:mbed_nano:nanorp2040connect"}],"images":[],"assets":{"thing_template_names":["ToSiteWise 3"],"dashboard_template_names":[],"trigger_template_names":[]},"source_template_id":"af076825-c0d2-4a27-a1cd-042df3604bae"}
Binary file added TT/template_ok-rp-with-binaries.tino
Binary file not shown.
2 changes: 2 additions & 0 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
"github.com/arduino/arduino-cloud-cli/cli/dashboard"
"github.com/arduino/arduino-cloud-cli/cli/device"
"github.com/arduino/arduino-cloud-cli/cli/ota"
"github.com/arduino/arduino-cloud-cli/cli/template"
"github.com/arduino/arduino-cloud-cli/cli/thing"
"github.com/arduino/arduino-cloud-cli/cli/version"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -65,6 +66,7 @@ func Execute() {
cli.AddCommand(thing.NewCommand())
cli.AddCommand(dashboard.NewCommand())
cli.AddCommand(ota.NewCommand())
cli.AddCommand(template.NewCommand())

if err := cli.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
Expand Down
1 change: 1 addition & 0 deletions cli/device/device.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func NewCommand() *cobra.Command {

deviceCommand.AddCommand(initCreateCommand())
deviceCommand.AddCommand(initListCommand())
deviceCommand.AddCommand(initShowCommand())
deviceCommand.AddCommand(initDeleteCommand())
deviceCommand.AddCommand(tag.InitCreateTagsCommand())
deviceCommand.AddCommand(tag.InitDeleteTagsCommand())
Expand Down
102 changes: 102 additions & 0 deletions cli/device/show.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// This file is part of arduino-cloud-cli.
//
// Copyright (C) 2024 ARDUINO SA (http://www.arduino.cc/)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

package device

import (
"context"
"fmt"
"os"
"strings"

"github.com/arduino/arduino-cli/cli/errorcodes"
"github.com/arduino/arduino-cli/cli/feedback"
"github.com/arduino/arduino-cli/table"
"github.com/arduino/arduino-cloud-cli/command/device"
"github.com/arduino/arduino-cloud-cli/config"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

type showFlags struct {
deviceId string
}

func initShowCommand() *cobra.Command {
flags := &showFlags{}
showCommand := &cobra.Command{
Use: "show",
Short: "Show device properties",
Long: "Show device properties on Arduino IoT Cloud",
Run: func(cmd *cobra.Command, args []string) {
if err := runShowCommand(flags); err != nil {
feedback.Errorf("Error during device show: %v", err)
os.Exit(errorcodes.ErrGeneric)
}
},
}
showCommand.Flags().StringVarP(&flags.deviceId, "device-id", "d", "", "device ID")

showCommand.MarkFlagRequired("device-id")

return showCommand
}

func runShowCommand(flags *showFlags) error {
logrus.Info("Show device")

cred, err := config.RetrieveCredentials()
if err != nil {
return fmt.Errorf("retrieving credentials: %w", err)
}

dev, _, err := device.Show(context.TODO(), flags.deviceId, cred)
if err != nil {
return err
}

feedback.PrintResult(showResult{dev})
return nil
}

type showResult struct {
device *device.DeviceInfo
}

func (r showResult) Data() interface{} {
return r.device
}

func (r showResult) String() string {
if r.device == nil {
return "No device found."
}
t := table.New()
t.SetHeader("Name", "ID", "Board", "FQBN", "SerialNumber", "Status", "Connection type", "Thing", "Tags")
t.AddRow(
r.device.Name,
r.device.ID,
r.device.Board,
r.device.FQBN,
r.device.Serial,
dereferenceString(r.device.Status),
dereferenceString(r.device.ConnectionType),
dereferenceString(r.device.ThingID),
strings.Join(r.device.Tags, ","),
)
return t.Render()
}
96 changes: 96 additions & 0 deletions cli/template/apply.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// This file is part of arduino-cloud-cli.
//
// Copyright (C) 2024 ARDUINO SA (http://www.arduino.cc/)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

package template

import (
"fmt"
"os"
"strings"

"github.com/arduino/arduino-cli/cli/errorcodes"
"github.com/arduino/arduino-cli/cli/feedback"
"github.com/arduino/arduino-cloud-cli/command/template"
"github.com/arduino/arduino-cloud-cli/config"
"github.com/spf13/cobra"
)

type applyFlags struct {
templateId string
templatePrefix string
deviceId string
netCredentials string
applyOta bool
}

func initTemplateApplyCommand() *cobra.Command {
flags := &applyFlags{}
applyCommand := &cobra.Command{
Use: "apply",
Short: "Apply custom template",
Long: "Given a template, apply it and create all the resources defined in it",
Run: func(cmd *cobra.Command, args []string) {
if err := runTemplateApplyCommand(flags); err != nil {
feedback.Errorf("Error during template apply: %v", err)
os.Exit(errorcodes.ErrGeneric)
}
},
}

applyCommand.Flags().StringVarP(&flags.templateId, "template-id", "t", "", "Template ID")
applyCommand.Flags().StringVarP(&flags.templatePrefix, "prefix", "p", "", "Prefix to apply to the name of created resources")
applyCommand.Flags().StringVarP(&flags.deviceId, "device-id", "d", "", "Device ID")
applyCommand.Flags().StringVarP(&flags.netCredentials, "network-credentials", "n", "", "Comma separated network credentials used to configure device with format <key>=<value>. Supported values: SECRET_SSID | SECRET_OPTIONAL_PASS | SECRET_DEVICE_KEY")

applyCommand.MarkFlagRequired("template-id")
applyCommand.MarkFlagRequired("prefix")
applyCommand.MarkFlagRequired("device-id")

flags.applyOta = false

return applyCommand
}

func runTemplateApplyCommand(flags *applyFlags) error {
cred, err := config.RetrieveCredentials()
if err != nil {
return fmt.Errorf("retrieving credentials: %w", err)
}

deviceNetCredentials, err := parseCredentials(flags.netCredentials)
if err != nil {
return fmt.Errorf("parsing network credentials: %w", err)
}

return template.ApplyCustomTemplates(cred, flags.templateId, flags.deviceId, flags.templatePrefix, deviceNetCredentials, flags.applyOta)
}

func parseCredentials(credentials string) (map[string]string, error) {
credentialsMap := make(map[string]string)
if credentials == "" {
return credentialsMap, nil
}
credentialsArray := strings.Split(credentials, ",")
for _, credential := range credentialsArray {
credentialArray := strings.Split(credential, "=")
if len(credentialArray) != 2 {
return nil, fmt.Errorf("invalid network credential: %s", credential)
}
credentialsMap[credentialArray[0]] = credentialArray[1]
}
return credentialsMap, nil
}
Loading
Loading