Added report generator for thingsboard

This commit is contained in:
Nico Melone
2024-07-31 14:02:59 -05:00
parent c45c5a926d
commit 6db3e90fc1
82 changed files with 17951 additions and 27 deletions

View File

@@ -0,0 +1,469 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from tb_rest_client.rest_client_pe import *\n",
"from tb_rest_client.rest import ApiException\n",
"\n",
"import json, sys, os\n",
"from datetime import datetime as dt"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"url = \"https://hp.henrypump.cloud\"\n",
"username = \"nmelone@henry-pump.com\"\n",
"password = \"gzU6$26v42mU%3jDzTJf\""
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"#Creating Rest Client for ThingsBoard\n",
"with RestClientPE(base_url=url) as rest_client:\n",
" try:\n",
" rest_client.login(username=username, password=password)\n",
" #Loading Config from file\n",
" with open(\"./config.json\") as f:\n",
" config = json.load(f)\n",
"\n",
" reportData = {}\n",
" reportToList = {}\n",
" #Loop through each item in config, each item represents a report\n",
" for report in config:\n",
" reportToList[report[\"name\"]] = report[\"emails\"]\n",
" #Each customer becomes it's own xlsx file later\n",
" for customer in report[\"customers\"].keys():\n",
" #Get all the devices for a given customer\n",
" devices = rest_client.get_customer_devices(customer_id=customer, page=0, page_size=100)\n",
" #Filter devices to the desired devices\n",
" if report[\"filterDevicesIn\"]:\n",
" devices.data = [device for device in devices.data if device.id.id in report[\"filterDevicesIn\"]]\n",
" if report[\"filterDevicesOut\"]:\n",
" devices.data = [device for device in devices.data if device.id.id not in report[\"filterDevicesOut\"]]\n",
" #Create the report in reportData if needed\n",
" if not reportData.get(report[\"name\"], None):\n",
" reportData[report[\"name\"]] = {}\n",
" #Go through all the devices and add them and their desired data to reportData \n",
" for device in devices.data:\n",
" name = device.name\n",
" keys = rest_client.get_timeseries_keys_v1(device.id)\n",
" #Filter keys to desired keys\n",
" for deviceType in report[\"customers\"][customer][\"deviceTypes\"]:\n",
" if device.type == deviceType[\"deviceType\"]:\n",
" keys = list(filter(lambda x: x in deviceType[\"dataPoints\"], keys))\n",
" #Create customer if needed\n",
" if not reportData[report[\"name\"]].get(report[\"customers\"][customer][\"name\"], None):\n",
" reportData[report[\"name\"]][report[\"customers\"][customer][\"name\"]] = {}\n",
" #Check to make sure the deviceType is desired in the report for the given device\n",
" if device.type in list(map(lambda x: x[\"deviceType\"], report[\"customers\"][customer][\"deviceTypes\"])):\n",
" #Create deviceType if needed\n",
" if not reportData[report[\"name\"]][report[\"customers\"][customer][\"name\"]].get(device.type, None):\n",
" reportData[report[\"name\"]][report[\"customers\"][customer][\"name\"]][device.type] = {}\n",
" reportData[report[\"name\"]][report[\"customers\"][customer][\"name\"]][device.type][device.name] = rest_client.get_latest_timeseries(entity_id=device.id , keys=\",\".join(keys))\n",
" except ApiException as e:\n",
" print(e)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"CrownQuest-Daily-Report\": {\n",
" \"CrownQuest\": {\n",
" \"rigpump\": {\n",
" \"#07\": {\n",
" \"vfd_frequency\": [\n",
" {\n",
" \"ts\": 1721761800000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ],\n",
" \"vfd_current\": [\n",
" {\n",
" \"ts\": 1721761800000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ]\n",
" },\n",
" \"#03\": {\n",
" \"vfd_frequency\": [\n",
" {\n",
" \"ts\": 1721712600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ],\n",
" \"vfd_current\": [\n",
" {\n",
" \"ts\": 1721712600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ]\n",
" },\n",
" \"#04\": {\n",
" \"vfd_frequency\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ],\n",
" \"vfd_current\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ]\n",
" },\n",
" \"#08\": {\n",
" \"vfd_frequency\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ],\n",
" \"vfd_current\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ]\n",
" },\n",
" \"#12\": {\n",
" \"vfd_frequency\": [\n",
" {\n",
" \"ts\": 1721772000000,\n",
" \"value\": \"40.98\"\n",
" }\n",
" ],\n",
" \"vfd_current\": [\n",
" {\n",
" \"ts\": 1721772000000,\n",
" \"value\": \"43.03\"\n",
" }\n",
" ]\n",
" },\n",
" \"#11\": {\n",
" \"vfd_frequency\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ],\n",
" \"vfd_current\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ]\n",
" },\n",
" \"#06\": {\n",
" \"vfd_frequency\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"50.0\"\n",
" }\n",
" ],\n",
" \"vfd_current\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"34.51\"\n",
" }\n",
" ]\n",
" },\n",
" \"#10\": {\n",
" \"vfd_frequency\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ],\n",
" \"vfd_current\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ]\n",
" },\n",
" \"#13\": {\n",
" \"vfd_frequency\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ],\n",
" \"vfd_current\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"0.0\"\n",
" }\n",
" ]\n",
" }\n",
" },\n",
" \"cqwatertanks\": {\n",
" \"Office Water Management\": {\n",
" \"fm_1_flow_rate\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"165.81\"\n",
" }\n",
" ]\n",
" }\n",
" }\n",
" },\n",
" \"Henry-Petroleum\": {\n",
" \"abbflow\": {\n",
" \"Davis Check Meter\": {\n",
" \"accumulated_volume\": [\n",
" {\n",
" \"ts\": 1721772000000,\n",
" \"value\": \"366655.72\"\n",
" }\n",
" ]\n",
" },\n",
" \"Great Western Check Meter\": {\n",
" \"accumulated_volume\": [\n",
" {\n",
" \"ts\": 1721716800000,\n",
" \"value\": \"45504.62\"\n",
" }\n",
" ]\n",
" },\n",
" \"Francis Hill Check Meter\": {\n",
" \"accumulated_volume\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"340350.0\"\n",
" }\n",
" ]\n",
" },\n",
" \"Foundation Check Meter\": {\n",
" \"accumulated_volume\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"434597.88\"\n",
" }\n",
" ]\n",
" },\n",
" \"Wess Hill Check Meter\": {\n",
" \"accumulated_volume\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"226273.38\"\n",
" }\n",
" ]\n",
" },\n",
" \"Lively Check Meter\": {\n",
" \"accumulated_volume\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"233637.39\"\n",
" }\n",
" ]\n",
" },\n",
" \"Glasscock Check Meter\": {\n",
" \"accumulated_volume\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"128745.13\"\n",
" }\n",
" ]\n",
" },\n",
" \"Mann Check Meter\": {\n",
" \"accumulated_volume\": [\n",
" {\n",
" \"ts\": 1721772600000,\n",
" \"value\": \"29861.7\"\n",
" }\n",
" ]\n",
" }\n",
" }\n",
" }\n",
" },\n",
" \"Henry-Petroleum-Daily-Report\": {\n",
" \"Henry-Petroleum\": {\n",
" \"abbflow\": {\n",
" \"Davis Check Meter\": {\n",
" \"accumulated_volume\": [\n",
" {\n",
" \"ts\": 1721772000000,\n",
" \"value\": \"366655.72\"\n",
" }\n",
" ]\n",
" }\n",
" }\n",
" }\n",
" }\n",
"}\n"
]
}
],
"source": [
"print(json.dumps(reportData, indent=4))"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"CrownQuest-Daily-Report\": [\n",
" \"nmelone@henry-pump.com\",\n",
" \"n_melone@hotmail.com\"\n",
" ],\n",
" \"Henry-Petroleum-Daily-Report\": [\n",
" \"nmelone@henry-pump.com\",\n",
" \"nmelone08@gmail.com\"\n",
" ]\n",
"}\n"
]
}
],
"source": [
"print(json.dumps(reportToList, indent=4))"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"import xlsxwriter\n",
"import boto3\n",
"from email.mime.multipart import MIMEMultipart\n",
"from email.mime.application import MIMEApplication\n",
"from email.mime.text import MIMEText\n",
"import tempfile\n",
"from email import encoders\n",
"from email.mime.base import MIMEBase"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"# Create an AWS SES client\n",
"ses_client = boto3.client('ses', region_name='us-east-1')"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'MessageId': '01000190e1a66884-79debb77-9a2f-400a-927e-ed2fe315a32c-000000', 'ResponseMetadata': {'RequestId': '212bf456-644c-492d-acf3-d23255222e4d', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Tue, 23 Jul 2024 22:11:37 GMT', 'content-type': 'text/xml', 'content-length': '338', 'connection': 'keep-alive', 'x-amzn-requestid': '212bf456-644c-492d-acf3-d23255222e4d'}, 'RetryAttempts': 0}}\n",
"[<xlsxwriter.workbook.Workbook object at 0x1100dae40>, <xlsxwriter.workbook.Workbook object at 0x105820980>]\n",
"{'MessageId': '01000190e1a66958-70b625d5-dec6-45f1-a1d8-155264b5c6f0-000000', 'ResponseMetadata': {'RequestId': '9de5509b-9745-4379-93d1-535e055bf55e', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Tue, 23 Jul 2024 22:11:38 GMT', 'content-type': 'text/xml', 'content-length': '338', 'connection': 'keep-alive', 'x-amzn-requestid': '9de5509b-9745-4379-93d1-535e055bf55e'}, 'RetryAttempts': 0}}\n",
"[<xlsxwriter.workbook.Workbook object at 0x105f2afc0>]\n"
]
}
],
"source": [
"# Create a workbook for each report\n",
"for report_name, report_data in reportData.items():\n",
" #will generate an email lower down\n",
" spreadsheets = []\n",
" # Create a worksheet for each company\n",
" for company_name, company_data in report_data.items():\n",
" workbook = xlsxwriter.Workbook(f\"{report_name}-{company_name}-{dt.today().strftime('%Y-%m-%d')}.xlsx\")\n",
" bold = workbook.add_format({'bold': True})\n",
" # Create a sheet for each device type\n",
" for device_type, device_data in company_data.items():\n",
" worksheet = workbook.add_worksheet(device_type)\n",
" \n",
" # Set the header row with device types\n",
" device_types = list(device_data.keys())\n",
" worksheet.write_column(1, 0, device_types,bold)\n",
" \n",
" # Write the data to the sheet\n",
" for i, (telemetry_name, telemetry_data) in enumerate(device_data.items()):\n",
" # Set the header row with telemetry names\n",
" telemetry_names = list(telemetry_data.keys())\n",
" worksheet.write_row(0, 1, telemetry_names, bold)\n",
" for j, (data_name, data) in enumerate(telemetry_data.items()):\n",
" values = [d[\"value\"] for d in data]\n",
" worksheet.write_row(i + 1, j+ 1, values)\n",
" worksheet.autofit()\n",
" workbook.close()\n",
" spreadsheets.append(workbook)\n",
" # Create an email message\n",
" msg = MIMEMultipart()\n",
" msg['Subject'] = report_name\n",
" msg['From'] = 'alerts@henry-pump.com'\n",
" msg['To'] = \", \".join(reportToList[report_name])\n",
"\n",
" # Add a text body to the message (optional)\n",
" body_text = 'Please find the attached spreadsheets.'\n",
" msg.attach(MIMEText(body_text, 'plain'))\n",
"\n",
" # Attach each workbook in the spreadsheets array\n",
" for spreadsheet in spreadsheets:\n",
" # Attach the file to the email message\n",
" attachment = MIMEBase('application', 'octet-stream')\n",
" attachment.set_payload(open(spreadsheet.filename, \"rb\").read())\n",
" encoders.encode_base64(attachment)\n",
" attachment.add_header('Content-Disposition', 'attachment', filename=spreadsheet.filename)\n",
"\n",
" msg.attach(attachment)\n",
"\n",
" # Send the email using AWS SES\n",
" response = ses_client.send_raw_email(\n",
" \n",
" RawMessage={'Data': msg.as_string()}\n",
" )\n",
"\n",
" print(response)\n",
" print(spreadsheets)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "thingsboard",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,244 @@
# Created by https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### OSX ###
*.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### PyCharm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Ruby plugin and RubyMine
/.rakeTasks
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### PyCharm Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
.pytest_cache/
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Translations
*.mo
*.pot
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule.*
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history
### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# Build folder
*/build/*
# End of https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode

View File

@@ -0,0 +1,36 @@
# Developing AWS SAM Applications with the AWS Toolkit For Visual Studio Code
This project contains source code and supporting files for a serverless application that you can locally run, debug, and deploy to AWS with the AWS Toolkit For Visual Studio Code.
A "SAM" (serverless application model) project is a project that contains a template.yaml file which is understood by AWS tooling (such as SAM CLI, and the AWS Toolkit For Visual Studio Code).
## Writing and Debugging Serverless Applications
The code for this application will differ based on the runtime, but the path to a handler can be found in the [`template.yaml`](./template.yaml) file through a resource's `CodeUri` and `Handler` fields.
AWS Toolkit For Visual Studio Code supports local debugging for serverless applications through VS Code's debugger. Since this application was created by the AWS Toolkit, launch configurations for all included handlers have been generated and can be found in the menu next to the Run button:
You can debug the Lambda handlers locally by adding a breakpoint to the source file, then running the launch configuration. This works by using Docker on your local machine.
Invocation parameters, including payloads and request parameters, can be edited either by the `Edit SAM Debug Configuration` command (through the Command Palette or CodeLens) or by editing the `launch.json` file.
AWS Lambda functions not defined in the [`template.yaml`](./template.yaml) file can be invoked and debugged by creating a launch configuration through the CodeLens over the function declaration, or with the `Add SAM Debug Configuration` command.
## Deploying Serverless Applications
You can deploy a serverless application by invoking the `AWS: Deploy SAM application` command through the Command Palette or by right-clicking the Lambda node in the AWS Explorer and entering the deployment region, a valid S3 bucket from the region, and the name of a CloudFormation stack to deploy to. You can monitor your deployment's progress through the `AWS Toolkit` Output Channel.
## Interacting With Deployed Serverless Applications
A successfully-deployed serverless application can be found in the AWS Explorer under region and CloudFormation node that the serverless application was deployed to.
In the AWS Explorer, you can invoke _remote_ AWS Lambda Functions by right-clicking the Lambda node and selecting "Invoke on AWS".
Similarly, if the Function declaration contained an API Gateway event, the API Gateway API can be found in the API Gateway node under the region node the serverless application was deployed to, and can be invoked via right-clicking the API node and selecting "Invoke on AWS".
## Resources
General information about this SAM project can be found in the [`README.md`](./README.md) file in this folder.
More information about using the AWS Toolkit For Visual Studio Code with serverless applications can be found [in the AWS documentation](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/serverless-apps.html) .

View File

@@ -0,0 +1,130 @@
# lambda-python3.12
This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders.
- hello_world - Code for the application's Lambda function.
- events - Invocation events that you can use to invoke the function.
- tests - Unit tests for the application code.
- template.yaml - A template that defines the application's AWS resources.
The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code.
If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit.
The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started.
* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html)
* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html)
## Deploy the sample application
The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.
To use the SAM CLI, you need the following tools.
* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
* [Python 3 installed](https://www.python.org/downloads/)
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)
To build and deploy your application for the first time, run the following in your shell:
```bash
sam build --use-container
sam deploy --guided
```
The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts:
* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.
* **AWS Region**: The AWS region you want to deploy your app to.
* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.
* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.
You can find your API Gateway Endpoint URL in the output values displayed after deployment.
## Use the SAM CLI to build and test locally
Build your application with the `sam build --use-container` command.
```bash
lambda-python3.12$ sam build --use-container
```
The SAM CLI installs dependencies defined in `hello_world/requirements.txt`, creates a deployment package, and saves it in the `.aws-sam/build` folder.
Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project.
Run functions locally and invoke them with the `sam local invoke` command.
```bash
lambda-python3.12$ sam local invoke HelloWorldFunction --event events/event.json
```
The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000.
```bash
lambda-python3.12$ sam local start-api
lambda-python3.12$ curl http://localhost:3000/
```
The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path.
```yaml
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
```
## Add a resource to your application
The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types.
## Fetch, tail, and filter Lambda function logs
To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.
`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.
```bash
lambda-python3.12$ sam logs -n HelloWorldFunction --stack-name "lambda-python3.12" --tail
```
You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html).
## Tests
Tests are defined in the `tests` folder in this project. Use PIP to install the test dependencies and run tests.
```bash
lambda-python3.12$ pip install -r tests/requirements.txt --user
# unit test
lambda-python3.12$ python -m pytest tests/unit -v
# integration test, requiring deploying the stack first.
# Create the env variable AWS_SAM_STACK_NAME with the name of the stack we are testing
lambda-python3.12$ AWS_SAM_STACK_NAME="lambda-python3.12" python -m pytest tests/integration -v
```
## Cleanup
To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following:
```bash
sam delete --stack-name "lambda-python3.12"
```
## Resources
See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts.
Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/)

View File

@@ -0,0 +1,2 @@
DOCKER_HOST=unix:///Users/nico/.docker/run/docker.sock sam build --use-container
DOCKER_HOST=unix:///Users/nico/.docker/run/docker.sock sam deploy

View File

@@ -0,0 +1,62 @@
{
"body": "{\"message\": \"hello world\"}",
"resource": "/hello",
"path": "/hello",
"httpMethod": "GET",
"isBase64Encoded": false,
"queryStringParameters": {
"foo": "bar"
},
"pathParameters": {
"proxy": "/path/to/resource"
},
"stageVariables": {
"baz": "qux"
},
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch",
"Accept-Language": "en-US,en;q=0.8",
"Cache-Control": "max-age=0",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Custom User Agent String",
"Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
"X-Forwarded-For": "127.0.0.1, 127.0.0.2",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"requestContext": {
"accountId": "123456789012",
"resourceId": "123456",
"stage": "prod",
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"requestTime": "09/Apr/2015:12:34:56 +0000",
"requestTimeEpoch": 1428582896000,
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"accessKey": null,
"sourceIp": "127.0.0.1",
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": "Custom User Agent String",
"user": null
},
"path": "/prod/hello",
"resourcePath": "/hello",
"httpMethod": "POST",
"apiId": "1234567890",
"protocol": "HTTP/1.1"
}
}

View File

@@ -0,0 +1,36 @@
# More information about the configuration file can be found here:
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html
version = 0.1
[default]
[default.global.parameters]
stack_name = "lambda-python3.12"
[default.build.parameters]
cached = true
parallel = true
[default.validate.parameters]
lint = true
[default.deploy.parameters]
capabilities = "CAPABILITY_IAM"
confirm_changeset = true
resolve_s3 = true
stack_name = "tbreport"
s3_prefix = "tbreport"
region = "us-east-1"
image_repositories = []
disable_rollback = true
[default.package.parameters]
resolve_s3 = true
[default.sync.parameters]
watch = true
[default.local_start_api.parameters]
warm_containers = "EAGER"
[default.local_start_lambda.parameters]
warm_containers = "EAGER"

View File

@@ -0,0 +1,42 @@
import json
# import requests
def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
API Gateway Lambda Proxy Input Format
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
context: object, required
Lambda Context runtime methods and attributes
Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
Returns
------
API Gateway Lambda Proxy Output Format: dict
Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
"""
# try:
# ip = requests.get("http://checkip.amazonaws.com/")
# except requests.RequestException as e:
# # Send some context about this error to Lambda Logs
# print(e)
# raise e
return {
"statusCode": 200,
"body": json.dumps({
"message": "hello world",
# "location": ip.text.replace("\n", "")
}),
}

View File

@@ -0,0 +1,64 @@
[
{
"emails": [
"nmelone@henry-pump.com"
],
"customers": {
"ec691940-52e2-11ec-a919-556e8dbef35c": {
"name": "CrownQuest",
"deviceTypes": [
{
"deviceType": "rigpump",
"dataPoints": [
"vfd_current",
"vfd_frequency"
]
},
{
"deviceType": "cqwatertanks",
"dataPoints": [
"fm_1_flow_rate"
]
}
]
},
"81083430-6988-11ec-a919-556e8dbef35c": {
"name": "Henry-Petroleum",
"deviceTypes": [
{
"deviceType": "abbflow",
"dataPoints": [
"accumulated_volume"
]
}
]
}
},
"filterDevicesIn": [],
"filterDevicesOut": [],
"name": "CrownQuest-Daily-Report"
},
{
"emails": [
"nmelone@henry-pump.com"
],
"customers": {
"81083430-6988-11ec-a919-556e8dbef35c": {
"name": "Henry-Petroleum",
"deviceTypes": [
{
"deviceType": "abbflow",
"dataPoints": [
"accumulated_volume"
]
}
]
}
},
"filterDevicesIn": [
"0090dbd0-abb0-11ec-90c2-ad8278896f52"
],
"filterDevicesOut": [],
"name": "Henry-Petroleum-Daily-Report"
}
]

View File

@@ -0,0 +1,6 @@
import json
def handler(event, context):
# Log the event argument for debugging and for use in local development.
print(json.dumps(event))
return {}

View File

@@ -0,0 +1,114 @@
from tb_rest_client.rest_client_pe import *
from tb_rest_client.rest import ApiException
import json, xlsxwriter, boto3, os
from datetime import datetime as dt
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from email.mime.base import MIMEBase
def lambda_handler(event, context):
#Creating Rest Client for ThingsBoard
with RestClientPE(base_url="https://hp.henrypump.cloud") as rest_client:
try:
rest_client.login(username=os.environ["username"], password=os.environ["password"])
#Loading Config from file
with open("./config.json") as f:
config = json.load(f)
reportData = {}
reportToList = {}
#Loop through each item in config, each item represents a report
for report in config:
reportToList[report["name"]] = report["emails"]
#Each customer becomes it's own xlsx file later
for customer in report["customers"].keys():
#Get all the devices for a given customer
devices = rest_client.get_customer_devices(customer_id=customer, page=0, page_size=100)
#Filter devices to the desired devices
if report["filterDevicesIn"]:
devices.data = [device for device in devices.data if device.id.id in report["filterDevicesIn"]]
if report["filterDevicesOut"]:
devices.data = [device for device in devices.data if device.id.id not in report["filterDevicesOut"]]
#Create the report in reportData if needed
if not reportData.get(report["name"], None):
reportData[report["name"]] = {}
#Go through all the devices and add them and their desired data to reportData
for device in devices.data:
name = device.name
keys = rest_client.get_timeseries_keys_v1(device.id)
#Filter keys to desired keys
for deviceType in report["customers"][customer]["deviceTypes"]:
if device.type == deviceType["deviceType"]:
keys = list(filter(lambda x: x in deviceType["dataPoints"], keys))
#Create customer if needed
if not reportData[report["name"]].get(report["customers"][customer]["name"], None):
reportData[report["name"]][report["customers"][customer]["name"]] = {}
#Check to make sure the deviceType is desired in the report for the given device
if device.type in list(map(lambda x: x["deviceType"], report["customers"][customer]["deviceTypes"])):
#Create deviceType if needed
if not reportData[report["name"]][report["customers"][customer]["name"]].get(device.type, None):
reportData[report["name"]][report["customers"][customer]["name"]][device.type] = {}
reportData[report["name"]][report["customers"][customer]["name"]][device.type][device.name] = rest_client.get_latest_timeseries(entity_id=device.id , keys=",".join(keys))
except ApiException as e:
print(e)
# Create an AWS SES client
ses_client = boto3.client('ses', region_name='us-east-1')
# Create a workbook for each report
for report_name, report_data in reportData.items():
#will generate an email lower down
spreadsheets = []
# Create a worksheet for each company
for company_name, company_data in report_data.items():
workbook = xlsxwriter.Workbook(f"/tmp/{report_name}-{company_name}-{dt.today().strftime('%Y-%m-%d')}.xlsx")
bold = workbook.add_format({'bold': True})
# Create a sheet for each device type
for device_type, device_data in company_data.items():
worksheet = workbook.add_worksheet(device_type)
# Set the header row with device types
device_types = list(device_data.keys())
worksheet.write_column(1, 0, device_types,bold)
# Write the data to the sheet
for i, (telemetry_name, telemetry_data) in enumerate(device_data.items()):
# Set the header row with telemetry names
telemetry_names = list(telemetry_data.keys())
worksheet.write_row(0, 1, telemetry_names, bold)
for j, (data_name, data) in enumerate(telemetry_data.items()):
values = [d["value"] for d in data]
worksheet.write_row(i + 1, j+ 1, values)
worksheet.autofit()
workbook.close()
spreadsheets.append(workbook)
# Create an email message
msg = MIMEMultipart()
msg['Subject'] = report_name
msg['From'] = 'alerts@henry-pump.com'
msg['To'] = ", ".join(reportToList[report_name])
# Add a text body to the message (optional)
body_text = 'Please find the attached spreadsheets.'
msg.attach(MIMEText(body_text, 'plain'))
# Attach each workbook in the spreadsheets array
for spreadsheet in spreadsheets:
# Attach the file to the email message
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(spreadsheet.filename, "rb").read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment', filename=spreadsheet.filename[5:])
msg.attach(attachment)
# Send the email using AWS SES
response = ses_client.send_raw_email(
RawMessage={'Data': msg.as_string()}
)

View File

@@ -0,0 +1,2 @@
xlsxwriter
tb-rest-client

View File

@@ -0,0 +1,68 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: |
lambda-python3.12
Sample SAM Template for lambda-python3.12
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Resources:
TBReport:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
MemorySize: 128
Timeout: 300
Environment:
Variables:
username: henry.pump.automation@gmail.com
password: Henry Pump @ 2022
Architectures:
- arm64
CodeUri: tbreport
Runtime: python3.12
Handler: tbreport.lambda_handler
Policies: AmazonSESFullAccess
Layers:
- !Ref TBReportLayer
TBReportLayer:
Type: AWS::Serverless::LayerVersion
Properties:
ContentUri: tbreportlayer/
CompatibleRuntimes:
- python3.9
- python3.10
- python3.11
- python3.12
Metadata:
BuildMethod: python3.9
Schedule:
Type: AWS::Scheduler::Schedule
Properties:
ScheduleExpression: cron(0 5 * * ? *)
FlexibleTimeWindow:
Mode: 'OFF'
ScheduleExpressionTimezone: America/Chicago
Target:
Arn: !GetAtt TBReport.Arn
RoleArn: !GetAtt ScheduleToTBReportRole.Arn
ScheduleToTBReportRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
Effect: Allow
Principal:
Service: !Sub scheduler.${AWS::URLSuffix}
Action: sts:AssumeRole
Policies:
- PolicyName: StartExecutionPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: lambda:InvokeFunction
Resource: !GetAtt TBReport.Arn

View File

@@ -0,0 +1,45 @@
import os
import boto3
import pytest
import requests
"""
Make sure env variable AWS_SAM_STACK_NAME exists with the name of the stack we are going to test.
"""
class TestApiGateway:
@pytest.fixture()
def api_gateway_url(self):
""" Get the API Gateway URL from Cloudformation Stack outputs """
stack_name = os.environ.get("AWS_SAM_STACK_NAME")
if stack_name is None:
raise ValueError('Please set the AWS_SAM_STACK_NAME environment variable to the name of your stack')
client = boto3.client("cloudformation")
try:
response = client.describe_stacks(StackName=stack_name)
except Exception as e:
raise Exception(
f"Cannot find stack {stack_name} \n" f'Please make sure a stack with the name "{stack_name}" exists'
) from e
stacks = response["Stacks"]
stack_outputs = stacks[0]["Outputs"]
api_outputs = [output for output in stack_outputs if output["OutputKey"] == "HelloWorldApi"]
if not api_outputs:
raise KeyError(f"HelloWorldAPI not found in stack {stack_name}")
return api_outputs[0]["OutputValue"] # Extract url from stack outputs
def test_api_gateway(self, api_gateway_url):
""" Call the API Gateway endpoint and check the response """
response = requests.get(api_gateway_url)
assert response.status_code == 200
assert response.json() == {"message": "hello world"}

View File

@@ -0,0 +1,3 @@
pytest
boto3
requests

View File

@@ -0,0 +1,72 @@
import json
import pytest
from hello_world import app
@pytest.fixture()
def apigw_event():
""" Generates API GW Event"""
return {
"body": '{ "test": "body"}',
"resource": "/{proxy+}",
"requestContext": {
"resourceId": "123456",
"apiId": "1234567890",
"resourcePath": "/{proxy+}",
"httpMethod": "POST",
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"accountId": "123456789012",
"identity": {
"apiKey": "",
"userArn": "",
"cognitoAuthenticationType": "",
"caller": "",
"userAgent": "Custom User Agent String",
"user": "",
"cognitoIdentityPoolId": "",
"cognitoIdentityId": "",
"cognitoAuthenticationProvider": "",
"sourceIp": "127.0.0.1",
"accountId": "",
},
"stage": "prod",
},
"queryStringParameters": {"foo": "bar"},
"headers": {
"Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
"Accept-Language": "en-US,en;q=0.8",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Mobile-Viewer": "false",
"X-Forwarded-For": "127.0.0.1, 127.0.0.2",
"CloudFront-Viewer-Country": "US",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Upgrade-Insecure-Requests": "1",
"X-Forwarded-Port": "443",
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
"X-Forwarded-Proto": "https",
"X-Amz-Cf-Id": "aaaaaaaaaae3VYQb9jd-nvCd-de396Uhbp027Y2JvkCPNLmGJHqlaA==",
"CloudFront-Is-Tablet-Viewer": "false",
"Cache-Control": "max-age=0",
"User-Agent": "Custom User Agent String",
"CloudFront-Forwarded-Proto": "https",
"Accept-Encoding": "gzip, deflate, sdch",
},
"pathParameters": {"proxy": "/examplepath"},
"httpMethod": "POST",
"stageVariables": {"baz": "qux"},
"path": "/examplepath",
}
def test_lambda_handler(apigw_event):
ret = app.lambda_handler(apigw_event, "")
data = json.loads(ret["body"])
assert ret["statusCode"] == 200
assert "message" in ret["body"]
assert data["message"] == "hello world"