Skip to content

Commit

Permalink
first
Browse files Browse the repository at this point in the history
  • Loading branch information
torresashjian committed Nov 4, 2021
0 parents commit 2220379
Show file tree
Hide file tree
Showing 78 changed files with 7,395 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.target
.DS_Store
dist

515 changes: 515 additions & 0 deletions LICENSE

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
SHELL := /bin/bash
SCRIPTS_PATH := scripts

.PHONY: build-installer
build-installer:
@$(SCRIPTS_PATH)/build_installer.sh

.PHONY: build-push-delete-air-edgex-component
build-push-delete-air-edgex-component: build-air-edgex-component push-image delete-local-image

.PHONY: build-air-edgex-component
build-air-edgex-component:
@$(SCRIPTS_PATH)/build_air_edgex_component.sh ${IMAGE_NAME} ${IMAGE_TAG} ${IMAGE_URL} ${EDGEX_COMPONENT_NAME} ${TARGET_NAME}

.PHONY: push-image
push-image:
@$(SCRIPTS_PATH)/push_image.sh ${IMAGE_NAME} ${IMAGE_TAG} ${IMAGE_URL}

.PHONY: delete-local-image
delete-local-image:
@$(SCRIPTS_PATH)/delete_local_image.sh ${IMAGE_NAME} ${IMAGE_TAG} ${IMAGE_URL}
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Project Air

Project Air is an IoT platform for the registration of devices, process of IoT produced data and definition, deployment and configuration of Application pipelines.

For more information please visit [Project Air](https://tibcosoftware.github.io/labs-air/) docs page.

## Introduction

These components are device, services and other [edgex](https://www.edgexfoundry.org/) specific add-ons for project Air.
35 changes: 35 additions & 0 deletions app-service-metadata/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

.vscode
**/debug
**/debug.test
*.txt
*.html

# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
cmd/app-service-metadata

# Test binary, build with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

*.log

.idea/
vendor/
go.sum

# snap files
*.snap
*.assert
prime/
stage/
parts/
squashfs-root/
coverage.out
27 changes: 27 additions & 0 deletions app-service-metadata/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
FROM golang:1.15-alpine AS builder

# add git for go modules
RUN apk update;\
apk add --no-cache make git gcc libc-dev libsodium-dev zeromq-dev;

WORKDIR /app-service-metadata

COPY go.mod .

RUN go mod download

COPY . .

RUN apk info -a zeromq-dev

RUN make build

# Next image - Copy built Go binary into new workspace
FROM alpine


RUN apk --no-cache add zeromq
COPY --from=builder /app-service-metadata/cmd/res /res
COPY --from=builder /app-service-metadata/cmd/app-service-metadata /app-service-metadata

CMD [ "/app-service-metadata" ,"--registry","--confdir=/res"]
44 changes: 44 additions & 0 deletions app-service-metadata/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
.PHONY: build test clean docker

GO=CGO_ENABLED=1 GO111MODULE=on go

MICROSERVICES=cmd/app-service-metadata
.PHONY: $(MICROSERVICES)

VERSION=$(shell cat ./VERSION)
GOFLAGS=-ldflags "-X github.com/TIBCOSoftware/labs-air-infra/edgexfoundry/app-service-metadata.Version=$(VERSION)"
GIT_SHA=$(shell git rev-parse HEAD)

build: $(MICROSERVICES)
$(GO) install -tags=safe

$(MICROSERVICES):
$(GO) build $(GOFLAGS) -o $@ ./cmd

docker:
docker build --no-cache \
--label "git_sha=$(GIT_SHA)" \
-t tibcosoftware/labs-air-edgex-app-service-metadata:$(VERSION) \
.

dockerarm64:
docker build --no-cache \
--label "git_sha=$(GIT_SHA)" \
-t tibcosoftware/labs-air-edgex-app-service-metadata-arm64:$(VERSION) \
.


dockerbuildxarm64:
docker buildx build \
--platform linux/arm64 \
--label "git_sha=$(GIT_SHA)" \
-t tibcosoftware/docker-app-service-metadata-arm64:$(VERSION) --push \
.

test:
$(GO) vet ./...
gofmt -l .
$(GO) test -coverprofile=coverage.out ./...

clean:
rm -f $(MICROSERVICES)
1 change: 1 addition & 0 deletions app-service-metadata/VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1.3.0
224 changes: 224 additions & 0 deletions app-service-metadata/cmd/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
package main

import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"strconv"
"time"

inttransforms "github.com/TIBCOSoftware/labs-air/edgexfoundry/app-service-metadata/internal/transforms"
"github.com/edgexfoundry/app-functions-sdk-go/appcontext"
"github.com/edgexfoundry/app-functions-sdk-go/appsdk"
"github.com/edgexfoundry/go-mod-core-contracts/clients"
"github.com/edgexfoundry/go-mod-core-contracts/clients/logger"
"github.com/edgexfoundry/go-mod-core-contracts/clients/metadata"
"github.com/edgexfoundry/go-mod-core-contracts/clients/urlclient/local"
"github.com/edgexfoundry/go-mod-core-contracts/models"
"github.com/google/uuid"
)

const (
serviceKey = "app-service-metadata"
)

type msgStruct struct {
ID string `json:"id"`
Device string `json:"device"`
Origin int64 `json:"source"`
Gateway string `json:"gateway"`
Readings []models.Reading `json:"readings"`
}

type gatewayStruct struct {
UUUID string `json:"uuid"`
Description string `json:"description"`
Address string `json:"address"`
Router string `json:"router"`
RouterPort string `json:"routerPort"`
DeployNetwork string `json:"deployNetwork"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
AccessToken string `json:"accessToken"`
Username string `json:"username"`
Platform string `json:"platform"`
Createdts int64 `json:"createdts"`
Updatedts int64 `json:"updatedts"`
}

type metadataStruct struct {
Gateway gatewayStruct `json:"gateway"`
Devices []models.Device `json:"devices"`
}

var mdc metadata.DeviceClient
var mqttSender *inttransforms.MQTTSender
var gatewayInfo gatewayStruct

func main() {

// Create an instance of the EdgeX SDK and initialize it.
edgexSdk := &appsdk.AppFunctionsSDK{ServiceKey: serviceKey}
if err := edgexSdk.Initialize(); err != nil {
message := fmt.Sprintf("SDK initialization failed: %v\n", err)
if edgexSdk.LoggingClient != nil {
edgexSdk.LoggingClient.Error(message)
} else {
fmt.Println(message)
}
os.Exit(-1)
}

// Set the logging client for the transforms
inttransforms.SetLoggingClient(edgexSdk.LoggingClient)

// Get the application's specific configuration settings.
metadataPublishInterval := 30
metadataClient := ""
appSettings := edgexSdk.ApplicationSettings()
if appSettings != nil {

gatewayID := inttransforms.GetAppSetting(appSettings, "GatewayId")
gatewayDescription := inttransforms.GetAppSetting(appSettings, "GatewayDescription")
gatewayHostname := inttransforms.GetAppSetting(appSettings, "GatewayHostname")
gatewayRouter := inttransforms.GetAppSetting(appSettings, "GatewayRouter")
gatewayRouterPort := inttransforms.GetAppSetting(appSettings, "GatewayRouterPort")
gatewayDeployNetwork := inttransforms.GetAppSetting(appSettings, "GatewayDeployNetwork")
gatewayLatitude := inttransforms.GetAppSetting(appSettings, "GatewayLatitude")
gatewayLongitude := inttransforms.GetAppSetting(appSettings, "GatewayLongitude")
gatewayAccessToken := inttransforms.GetAppSetting(appSettings, "GatewayAccessToken")
gatewayUsername := inttransforms.GetAppSetting(appSettings, "GatewayUsername")
gatewayPlatform := inttransforms.GetAppSetting(appSettings, "GatewayPlatform")
metadataClient = inttransforms.GetAppSetting(appSettings, "MetadataClient")
metadataPublishIntervalStr := inttransforms.GetAppSetting(appSettings, "MetadataPublishIntervalSecs")

startupTime := time.Now().UnixNano() / int64(time.Millisecond)
gatewayInfo.UUUID = gatewayID
gatewayInfo.AccessToken = gatewayAccessToken
gatewayInfo.Address = gatewayHostname
gatewayInfo.Router = gatewayRouter
gatewayInfo.RouterPort = gatewayRouterPort
gatewayInfo.DeployNetwork = gatewayDeployNetwork
gatewayInfo.Createdts = startupTime
gatewayInfo.Updatedts = startupTime
gatewayInfo.Description = gatewayDescription
gatewayInfo.Username = gatewayUsername
gatewayInfo.Platform = gatewayPlatform
gatewayInfo.Latitude, _ = strconv.ParseFloat(gatewayLatitude, 32)
gatewayInfo.Longitude, _ = strconv.ParseFloat(gatewayLongitude, 32)
metadataPublishInterval64, _ := strconv.ParseInt(metadataPublishIntervalStr, 10, 32)
metadataPublishInterval = int(metadataPublishInterval64)

} else {
fmt.Println("Application settings nil")
}

deviceClientURL := metadataClient + clients.ApiDeviceRoute

mdc = metadata.NewDeviceClient(
local.New(deviceClientURL))
// local.New(config.Clients[common.CoreDataClientName].Url() + clients.ApiValueDescriptorRoute))

// Create the MQTT Sender
mqttConfig, _ := inttransforms.LoadMQTTConfig(appSettings)
mqttSender = inttransforms.NewMQTTSender(edgexSdk.LoggingClient, nil, mqttConfig)

// Set pipeline configuration, the collection of functions to
// execute every time an event is triggered.
edgexSdk.SetFunctionsPipeline(
// transforms.NewFilter(deviceNames).FilterByDeviceName,
processEvent,
)

// Set ticker to trigger metadata publishing
ticker := time.NewTicker(time.Duration(metadataPublishInterval) * time.Second)
go func() {
for ; true; <-ticker.C {
publishMetadata(edgexSdk.LoggingClient)
}
}()

// Lastly, we'll go ahead and tell the SDK to "start" and begin listening for events
// to trigger the pipeline.
err := edgexSdk.MakeItRun()
if err != nil {
edgexSdk.LoggingClient.Error("MakeItRun returned error: ", err.Error())
os.Exit(-1)
}

// Do any required cleanup here

ticker.Stop()
os.Exit(0)
}

func processEvent(edgexcontext *appcontext.Context, params ...interface{}) (bool, interface{}) {

if len(params) < 1 {
// We didn't receive a result
return false, nil
}

if event, ok := params[0].(models.Event); ok {

edgexcontext.LoggingClient.Debug(fmt.Sprintf("Processing event for device: %s", event.Device))

// Check to see if reading is of type binary and if so, update reading
if event.Readings[0].ValueType == "Binary" {
edgexcontext.LoggingClient.Debug(fmt.Sprintf("Processing Binary Data"))
event.Readings[0].Id = uuid.New().String()
// event.Readings[0].Value = string(event.Readings[0].BinaryValue)
event.Readings[0].Value = base64.StdEncoding.EncodeToString(event.Readings[0].BinaryValue)
// event.Readings[0].Value = "image"
event.Readings[0].BinaryValue = nil
event.Readings[0].ValueType = "String"
}

jsondat := &msgStruct{
ID: event.ID,
Device: event.Device,
Origin: event.Origin,
Gateway: gatewayInfo.UUUID,
Readings: event.Readings,
}

encjson, _ := json.Marshal(jsondat)

edgexcontext.Complete(encjson)

// return false, nil

return true, nil
}

return false, errors.New("Unexpected type received")

}

func publishMetadata(loggingClient logger.LoggingClient) (bool, interface{}) {

loggingClient.Debug("Publishing metadata")

// Update gatewayInfo with publish time
publishTime := time.Now().UnixNano() / int64(time.Millisecond)
gatewayInfo.Updatedts = publishTime

devices, err := mdc.Devices(context.Background())

if devices != nil && err == nil {
jsonmd := &metadataStruct{
Gateway: gatewayInfo,
Devices: devices,
}

encjson, _ := json.Marshal(jsonmd)

// Export metadata
return mqttSender.MQTTSendMetadata(string(encjson))
}

return false, errors.New("Unexpected devices result received")
}
Loading

0 comments on commit 2220379

Please sign in to comment.