Compare commits

6 Commits

Author SHA1 Message Date
Patrick McDonagh
74019e4889 Completes #1.
Updates README-local.md to include instructions and configuration for running locally
2018-04-05 18:07:13 -05:00
Patrick McDonagh
a462070cf9 use packaged Meshify 2018-03-26 09:34:53 -05:00
Patrick McDonagh
fd68d4067f use meshify package, fix build function, add more device channel files 2018-03-23 18:51:10 -05:00
Patrick McDonagh
c388fa1f61 Local packages were missing 2018-03-14 17:16:00 -05:00
Patrick McDonagh
acf614f6c2 Adds LICENSE and reformats README.md 2018-03-14 17:07:31 -05:00
Patrick McDonagh
bf202dae5c Updates README.md and creates README-local.md 2018-03-14 17:02:14 -05:00
10 changed files with 492 additions and 350 deletions

201
LICENSE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Patrick McDonagh
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

99
README-local.md Normal file
View File

@@ -0,0 +1,99 @@
# POCloud Local Report Generators
Developed by Patrick McDonagh @patrickjmcd, Henry pump
## Setup
System variables must be set up for the script to run. Add the following lines to /etc/environment
```Shell
MESHIFY_USERNAME="<yourMeshifyUsername>"
MESHIFY_PASSWORD="<yourMeshifyPassword>"
```
### Setup a Virtual Environment and Install Python Modules
```Shell
python3 -m venv env # Creates the virtual environment in a folder ./env
source env/bin/activate # activates the virtual environment
pip install xlsxwriter requests tzlocal meshify # installs the python modules
```
### Preparing an S3 Bucket
This section will show you how to configure the S3 Bucket within AWS. It assumes a strong knowledge of AWS platforms.
1. Sign in to your AWS Console and open the S3 dashboard.
2. Create a bucket named "pocloud-email-reports". You may choose to name your bucket differently, but you must update the variable BUCKET_NAME within reports_s3_xlsx.py
3. Open the newly-created bucket and create 3 folders. These names cannot be changed without doing some serious hacking of the reports_s3_xlsx.py file.
- channel_config
- created_reports
- to_files
### Populating Channel Configs
Populating channel config files tells the Lambda function which devices to prepare reports for and which channels to include data from. **Devices will not be recognized unless they have both a Channel Config file and a To file.**
1. Prepare a file named devicetype_channels.json where "devicetype" is the Meshify name for the devicetype.
```touch <devicetype>_channels.json```
2. In the text editor of your choice, develop a JSON **list of objects** that contains properties "meshify_name" and "vanity_name".
```JSON
[
{
"meshify_name": "<channel name in meshify>",
"vanity_name": "<vanity name for report header>"
},
{
"meshify_name": "<another channel name in meshify>",
"vanity_name": "<another vanity name for report header>"
},
]
```
3. Upload this file to the "channel_config" folder in the S3 Bucket.
### Populating To Files
Populating To files tells the Lambda function which devices to prepare reports for and whom to send the reports for each company. **Devices will not be recognized unless they have both a Channel Config file and a To file.**
1. Prepare a file named devicetype_to.json where "devicetype" is the Meshify name for the devicetype.
```touch <devicetype>_to.json```
2. In the text editor of your choice, develop a JSON **object** that contains properties of the format below. CompanyA and CompanyB should be replaced by the full name of the company as recorded in Meshify.
```JSON
{
"CompanyA": [
"person@email.com",
"place@email.com"
],
"CompanyB": [
"person@email.com",
"thing@email.com"
]
}
```
3. Upload this file to the "to_files" folder in the S3 Bucket.
## Running the Script
As long as everything has been setup correctly, all it takes is running:
```Shell
python local_test.py
```
This performs a "dry-run" where it will generate the reports and print to the console the list of recipients, but it will not actually send the reports. The script can trigger the sending of reports by running:
```Shell
python local_test.py --send
```

206
README.md
View File

@@ -1,128 +1,150 @@
# POCloud Report Generators
# POCloud Email Report Generator
Developed by Patrick McDonagh @patrickjmcd, Henry pump
Send daily reports of Meshify Data via AWS functions.
## Setup
## Using the Generator
System variables must be set up for the script to run. Add the following lines to /etc/environment
```
SMTP_EMAIL="<yourSMTPemailAddress>"
SMTP_PASSWORD="<yourSMTPpassword>"
MESHIFY_USERNAME="<yourMeshifyUsername>"
MESHIFY_PASSWORD="<yourMeshifyPassword>"
```
Reports will be generated on a schedule by AWS Lambda, a serverless, event-driven computing platform. Each report will contain all devices of a specified type that the user has been granted access to in Meshify. If a user has access to multiple device types and is configured to receive reports for multiple device types, the user will receive one report for each device type. The Lambda function will mark in red any data that is more than 24 hours old in order to denote devices that have not updated. Values reported are the latest values at the time of report generation (12:00 GMT / 07:00 CST by default).
Create a "files" in the script's directory.
If you would like to run the reports locally without the AWS Lambda Function, refer to [README-local.md](README-local.md)
### Install Python Modules
## Setting it up yourself
```
pip install xlsxwriter
```
### Prerequisites
## Configuration Files
- Amazon Web Services account
- Sufficient knowledge of S3, Lambda, and SES within Amazon Web Services
- Python 3
The script relies heavily on configuration files based on the Meshify devicetype. To configure a device, create a file
named <devicetype>_channels.json file. The file should hold a JSON list.
### Preparing an S3 Bucket
### Example Configuration File
This section will show you how to configure the S3 Bucket within AWS. It assumes a strong knowledge of AWS platforms.
```
# testdevice_channels.json
1. Sign in to your AWS Console and open the S3 dashboard.
2. Create a bucket named "pocloud-email-reports". You may choose to name your bucket differently, but you must update the variable BUCKET_NAME within reports_s3_xlsx.py
3. Open the newly-created bucket and create 3 folders. These names cannot be changed without doing some serious hacking of the reports_s3_xlsx.py file.
- channel_config
- created_reports
- to_files
[
### Populating Channel Configs
Populating channel config files tells the Lambda function which devices to prepare reports for and which channels to include data from. **Devices will not be recognized unless they have both a Channel Config file and a To file.**
1. Prepare a file named devicetype_channels.json where "devicetype" is the Meshify name for the devicetype.
```touch <devicetype>_channels.json```
2. In the text editor of your choice, develop a JSON **list of objects** that contains properties "meshify_name" and "vanity_name".
```JSON
[
{
"meshify_name": "yesterday_volume",
"vanity_name": "Yesteday Volume"
"meshify_name": "<channel name in meshify>",
"vanity_name": "<vanity name for report header>"
},
{
"meshify_name": "volume_flow",
"vanity_name": "Flow Rate"
"meshify_name": "<another channel name in meshify>",
"vanity_name": "<another vanity name for report header>"
},
...
]
```
## Recipients File
]
```
In order to send emails containing the reports, configure a recipients json file named <devicetype>_to.json. The
file should hold a JSON object.
3. Upload this file to the "channel_config" folder in the S3 Bucket.
### Example Recipients File
### Populating To Files
```
# testdevice_to.json
Populating To files tells the Lambda function which devices to prepare reports for and whom to send the reports for each company. **Devices will not be recognized unless they have both a Channel Config file and a To file.**
{
"Company 1 Name": [
"email1@company.com",
"email2@company.com"
1. Prepare a file named devicetype_to.json where "devicetype" is the Meshify name for the devicetype.
```touch <devicetype>_to.json```
2. In the text editor of your choice, develop a JSON **object** that contains properties of the format below. CompanyA and CompanyB should be replaced by the full name of the company as recorded in Meshify.
```JSON
{
"CompanyA": [
"person@email.com",
"place@email.com"
],
"Company 2 Name": [
"email3@company2.com",
"email4@company2.com"
],
...
}
```
"CompanyB": [
"person@email.com",
"thing@email.com"
]
}
```
## Running the script
3. Upload this file to the "to_files" folder in the S3 Bucket.
```
usage: reports_xlsx.py [-h] [-s] [-p CONFIG_PATH] [-o OUTPUT_PATH] deviceType
### Preparing the Lambda function
positional arguments:
deviceType Meshify device type
1. Clone this repository and open it
optional arguments:
-h, --help show this help message and exit
-s, --send Send emails to everyone in the _to.json file
-c CONFIG_PATH, --config-path CONFIG_PATH
The folder path that holds the configuration files
-o OUTPUT_PATH, --output-path OUTPUT_PATH
The folder path that holds the output files
```
```Shell
git clone https://github.com/Henry-Pump/POCloud-Email-Reports.git
cd POCloud-Email-Reports
```
## Configuring the script to be run via crontab
2. Setup a Python Virtual environment and activate the environment
Open the crontab file with `crontab -e`.
```Shell
python3 -m venv env
source env/bin/activate
```
Add the following contents:
```
00 07 * * * /usr/bin/python3 /home/ubuntu/POCloud-Scraper/reports_xlsx.py advvfdipp --send --config-path /home/ubuntu/POCloud-Scraper --output-path /home/ubuntu/POCloud-Scraper/files
01 07 * * * /usr/bin/python3 /home/ubuntu/POCloud-Scraper/reports_xlsx.py ipp --send --config-path /home/ubuntu/POCloud-Scraper --output-path /home/ubuntu/POCloud-Scraper/files
02 07 * * * /usr/bin/python3 /home/ubuntu/POCloud-Scraper/reports_xlsx.py abbflow --send --config-path /home/ubuntu/POCloud-Scraper --output-path /home/ubuntu/POCloud-Scraper/files
```
3. Install necessary python packages in the virtual environment.
```Shell
pip install requests tzlocal xlsxwriter
```
# POCloud-Scraper
Scrape production data from POCloud to push to accounting servers
4. Create a folder for deploying the lambda function
## Setup
System variables must be set up for the script to run. Add the following lines to /etc/environment
```
HP_SQL_USER="<yourSQLusername>"
HP_SQL_PASSWORD="<yourSQLpassword>"
HP_SQL_SERVER="<yourSQLserverAddress>"
MESHIFY_USERNAME="<yourMeshifyUsername>"
MESHIFY_PASSWORD="<yourMeshifyPassword>"
```
```Shell
mkdir -p deploy```
## Usage
It is useful to run the script and store the output in a log file.
5. To build the lambda file automatically, allow execution permissions on the build script and execute it. To build manually, examine the [build_lambda.sh](https://github.com/Henry-Pump/POCloud-Email-Reports/blob/master/build_lambda.sh) file and execute commands at your own peril.
## Test Mode
The script has a test mode which will only retrieve the data. Test mode will not write date to the database.
```Shell
chmod +x build_lambda.sh
./build_lambda.sh
```
To run the script in test mode:
```
python3 henryPetroleumMeshifyAPI.pt True >> output.log
```
You should now have a file named lambda.zip in the main directory of the repo. This is the file to upload into your Lambda function.
## Normal Mode
In normal mode, the data will be grabbed from the Meshify API and inserted into the Production database.
### Creating the Lambda Function in AWS
To run the script:
```
python3 henryPetroleumMeshifyAPI.pt >> output.log
```
This section will show you how to configure the Lambda function within AWS. It assumes a strong knowledge of AWS platforms.
1. Sign in to your AWS Console and open the Lambda dashboard.
2. Click "Create function".
3. Select "Author from scratch" and fill in the info
- Name: give your function a name
- Runtime: select Python 3.6
- Role: either choose an existing role with S3, SES, and Lambda permissions or create one.
- Existing role: select the existing or created role name.
4. Click "Create Function".
5. In the function code section, set the following:
- Code entry type: "Upload a .ZIP file"
- Runtime: Python 3.6
- Handler: reports_s3_xlsx.lambda_handler
- Function package: upload the created lambda.zip
6. In Environment Variables, two variables are needed:
- MESHIFY_PASSWORD: your meshify password
- MESHIFY_USERNAME: your meshify username
7. Drag a CloudWatch Events trigger in the Designer to the trigger section of your function.
8. Configure a new CloudWatch event with the schedule expression:
```cron(0 12 * * ? *)```
This will schedule the event to be triggered at 12:00 PM GMT (7:00 AM CST) every day of the week.
9. Save and test your function.
## Contributors
- [Patrick McDonagh](@patrickjmcd) - Owner

View File

@@ -1,11 +1,11 @@
!#/bin/bash
env/bin/pip install boto3 tzlocal meshify requests
rm -f lambda.zip
mkdir -p deploy
cp env/lib/python3.6/site-packages/* deploy
cp meshify.py deploy
cp -R env/lib/python3.6/site-packages/* deploy
cp reports_s3_xlsx.py deploy
cd deploy
zip -r ../lambda.zip ./*
cd ..
echo "Lambda zip file built to ./lambda.zip"

View File

@@ -0,0 +1,18 @@
[
{
"meshify_name": "run_status",
"vanity_name": "Run Status"
},
{
"meshify_name": "bbl_total_yesterday",
"vanity_name": "BBL Total Yesterday"
},
{
"meshify_name": "bpd_flow",
"vanity_name": "BPD Flow Rate"
},
{
"meshify_name": "bbl_total_thismonth",
"vanity_name": "BBL Total This Month"
}
]

View File

@@ -0,0 +1,10 @@
[
{
"meshify_name": "pond_level",
"vanity_name": "Pond Level"
},
{
"meshify_name": "pond_volume",
"vanity_name": "Pond Volume"
}
]

View File

@@ -0,0 +1,18 @@
[
{
"meshify_name": "totalizer_1_yesterday",
"vanity_name": "Total Yesterday"
},
{
"meshify_name": "totalizer_1_units",
"vanity_name": "Totalizer Units"
},
{
"meshify_name": "volume_flow",
"vanity_name": "Flow Rate"
},
{
"meshify_name": "volume_flow_units",
"vanity_name": "Flow Rate Units"
}
]

25
local_test.py Normal file
View File

@@ -0,0 +1,25 @@
"""Run a test of the lambda function locally."""
import argparse
from reports_s3_xlsx import get_s3_device_types, read_s3_tofiles, read_s3_device_config, prep_emails, send_ses_email
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--send', action='store_true', help="Actually send the emails.")
args = parser.parse_args()
SEND_EMAIL = args.send
device_type_list = get_s3_device_types()
to_lists = list(map(lambda x: read_s3_tofiles(x), device_type_list))
channel_configs = list(map(lambda x: read_s3_device_config(x), device_type_list))
for i in range(0, len(device_type_list)):
emails = prep_emails(device_type_list[i], channel_configs[i], to_lists[i])
for email in emails:
if SEND_EMAIL:
send_ses_email(email)
print("Sent email for {} to {}".format(device_type_list[i], email['To']))
else:
print("Would have sent email for {} to {}".format(device_type_list[i], email['To']))

View File

@@ -1,38 +0,0 @@
"""Query Meshify for data."""
import requests
import json
from os import getenv
from sys import exit
MESHIFY_BASE_URL = "https://henrypump.meshify.com/api/v3/"
MESHIFY_USERNAME = getenv("MESHIFY_USERNAME")
MESHIFY_PASSWORD = getenv("MESHIFY_PASSWORD")
MESHIFY_AUTH = requests.auth.HTTPBasicAuth(MESHIFY_USERNAME, MESHIFY_PASSWORD)
if not MESHIFY_USERNAME or not MESHIFY_PASSWORD:
print("Be sure to set the meshify username and password as environment variables MESHIFY_USERNAME and MESHIFY_PASSWORD")
exit()
def find_by_name(name, list_of_stuff):
"""Find an object in a list of stuff by its name parameter."""
for x in list_of_stuff:
if x['name'] == name:
return x
return False
def query_meshify_api(endpoint):
"""Make a query to the meshify API."""
q_url = MESHIFY_BASE_URL + endpoint
q_req = requests.get(q_url, auth=MESHIFY_AUTH)
return json.loads(q_req.text) if q_req.status_code == 200 else []
def post_meshify_api(endpoint, data):
"""Post data to the meshify API."""
q_url = MESHIFY_BASE_URL + endpoint
q_req = requests.post(q_url, data=json.dumps(data), auth=MESHIFY_AUTH)
if q_req.status_code != 200:
print(q_req.status_code)
return json.loads(q_req.text) if q_req.status_code == 200 else []

View File

@@ -1,213 +0,0 @@
"""Prepare and send daily reports for Advanced VFD IPP devices in Meshify."""
import meshify
import json
from os import getenv
from sys import exit, stdout
from smtplib import SMTP
from datetime import datetime, timedelta
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.mime.base import MIMEBase
from time import sleep, time
from tzlocal import get_localzone
import xlsxwriter
import argparse
import logging
from logging.handlers import RotatingFileHandler
logger = ""
DEVICE_TYPE_NAME = ""
datestring = datetime.now().strftime("%Y%m%d")
VALUES_TO_INCLUDE = []
MESHIFY_NAMES = []
CONFIG_PATH = ""
OUTPUT_PATH = ""
SMTP_EMAIL = getenv("SMTP_EMAIL")
SMTP_PASSWORD = getenv("SMTP_PASSWORD")
def join_company_info(obj_with_companyId, company_lookup_obj):
"""Add company information to an object with companyId property."""
obj_with_companyId['company'] = company_lookup_obj[obj_with_companyId['companyId']]
return obj_with_companyId
def filter_object_parameters(ob, list_of_parameters):
"""Return an object of just the list of paramters."""
new_ob = {}
for par in list_of_parameters:
try:
new_ob[par] = ob[par]
except KeyError:
new_ob[par] = None
return new_ob
def group_by_company(devices):
"""Group a list of devices by company."""
grouped = {}
for dev in devices:
try:
grouped[dev['company']['name']].append(dev)
except KeyError:
grouped[dev['company']['name']] = [dev]
return grouped
def main(sendEmail=False):
"""Get the data and optionally send an email."""
if sendEmail:
if not SMTP_EMAIL or not SMTP_PASSWORD:
logger.error("Be sure to set the SMTP email and password as environment variables SMTP_EMAIL and SMTP_PASSWORD")
exit()
devicetypes = meshify.query_meshify_api("devicetypes")
this_devicetype = meshify.find_by_name(DEVICE_TYPE_NAME, devicetypes)
companies = meshify.query_meshify_api("companies")
company_lookup = {}
for x in companies:
company_lookup[x['id']] = x
devices = meshify.query_meshify_api("devices")
this_devices = filter(lambda x: x['deviceTypeId'] == this_devicetype['id'], devices)
this_devices = [join_company_info(x, company_lookup) for x in this_devices]
for i in range(0, len(this_devices)):
this_devices[i]['values'] = filter_object_parameters(
meshify.query_meshify_api("devices/{}/values".format(this_devices[i]['id'])), MESHIFY_NAMES)
this_devices = group_by_company(this_devices)
for comp in this_devices:
local_tz = get_localzone()
now_t = time()
now_dt = datetime.utcfromtimestamp(now_t)
now = local_tz.localize(now_dt)
workbook = xlsxwriter.Workbook("{}/{}_{}_{}.xlsx".format(OUTPUT_PATH, DEVICE_TYPE_NAME, comp, datestring))
worksheet = workbook.add_worksheet()
worksheet.set_column('A:A', 20)
bold = workbook.add_format({'bold': True})
red = workbook.add_format({'font_color': 'red'})
worksheet.write(0, 0, "Well Name", bold)
for i in range(0, len(VALUES_TO_INCLUDE)):
worksheet.write(0, i+1, VALUES_TO_INCLUDE[i]['vanity_name'], bold)
sorted_company_devices = sorted(this_devices[comp], key=lambda x: x['vanityName'])
for j in range(0, len(sorted_company_devices)):
dev = sorted_company_devices[j]
worksheet.write(j+1, 0, dev['vanityName'])
for k in range(0, len(MESHIFY_NAMES)):
v = MESHIFY_NAMES[k]
dt_ts = datetime.utcfromtimestamp(dev['values'][v]['timestamp'])
dt_loc = local_tz.localize(dt_ts)
stale = (now - dt_loc) > timedelta(hours=24)
try:
v = round(float(dev['values'][v]['value']), 3)
if stale:
worksheet.write_number(j+1, 1+k, v, red)
else:
worksheet.write_number(j+1, 1+k, v)
except ValueError:
v = str(dev['values'][v]['value'])
if stale:
worksheet.write(j+1, 1+k, v, red)
else:
worksheet.write(j+1, 1+k, v)
workbook.close()
if sendEmail:
with open("{}/{}_to.json".format(CONFIG_PATH, DEVICE_TYPE_NAME), 'r') as to_file:
to_lookup = json.load(to_file)
try:
email_to = to_lookup[comp]
except KeyError:
logger.error("No recipients for that company({})!".format(comp))
continue
# part1 = MIMEText(header + values, "plain")
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open("{}/{}_{}_{}.xlsx".format(OUTPUT_PATH, DEVICE_TYPE_NAME, comp, datestring), "rb").read())
encoders.encode_base64(attachment)
now = datetime.now()
datestr = now.strftime("%a %b %d, %Y")
msg = MIMEMultipart('alternative')
msg['Subject'] = "{} Daily {} Report for {}".format(comp, DEVICE_TYPE_NAME.upper(), datestr)
msg['From'] = "alerts@henry-pump.com"
msg['To'] = ", ".join(email_to)
filename = "{} {}.xlsx".format(comp, datestr)
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
# msg.attach(part1)
# msg.attach(part2)
msg.attach(attachment)
# s = SMTP(host="secure.emailsrvr.com", port=25)
s = SMTP(host="email-smtp.us-east-1.amazonaws.com", port=587)
s.starttls()
s.login(SMTP_EMAIL, SMTP_PASSWORD)
s.sendmail(from_addr="alerts@henry-pump.com", to_addrs=email_to, msg=msg.as_string())
logger.info("Email sent to {} for {}".format(email_to, comp))
sleep(2)
def setup_logger():
"""Setup and return the logger module."""
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
logFile = '{}/emailreports.log'.format(CONFIG_PATH)
my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=500*1024, backupCount=2, encoding=None, delay=0)
my_handler.setFormatter(log_formatter)
my_handler.setLevel(logging.INFO)
logger = logging.getLogger("emailreports")
logger.setLevel(logging.INFO)
logger.addHandler(my_handler)
console_out = logging.StreamHandler(stdout)
console_out.setFormatter(log_formatter)
logger.addHandler(console_out)
return logger
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('deviceType', help="Meshify device type")
parser.add_argument('-s', '--send', action='store_true', help="Send emails to everyone in the _to.json file")
parser.add_argument('-c', '--config-path', default="channel_config", help="The folder path that holds the configuration files")
parser.add_argument('-o', '--output-path', default="files", help="The folder path that holds the output files")
args = parser.parse_args()
DEVICE_TYPE_NAME = args.deviceType
SEND_EMAIL = args.send
CONFIG_PATH = args.config_path
if CONFIG_PATH[-1] == '/':
CONFIG_PATH = CONFIG_PATH[:-1]
OUTPUT_PATH = args.output_path
if OUTPUT_PATH[-1] == '/':
OUTPUT_PATH = OUTPUT_PATH[:-1]
logger = setup_logger()
try:
with open("{}/{}_channels.json".format(CONFIG_PATH, DEVICE_TYPE_NAME), 'r') as channel_file:
VALUES_TO_INCLUDE = json.load(channel_file)
MESHIFY_NAMES = [m['meshify_name'] for m in VALUES_TO_INCLUDE]
except IOError:
logger.error("No channel file named {}_channels.json".format(DEVICE_TYPE_NAME))
exit()
except ValueError as e:
logger.error("Channel file {}_channels.json is misformed: {}".format(DEVICE_TYPE_NAME, e))
exit()
main(sendEmail=SEND_EMAIL)