From 385b1ef42130678574a575f2a66d6f8030de3962 Mon Sep 17 00:00:00 2001 From: Trey Blancher Date: Sat, 3 Aug 2019 12:55:52 -0400 Subject: [PATCH] Initial commit. --- acfst.py | 164 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 acfst.py diff --git a/acfst.py b/acfst.py new file mode 100644 index 0000000..f8a8b54 --- /dev/null +++ b/acfst.py @@ -0,0 +1,164 @@ +from datetime import datetime, timedelta +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from email.mime.base import MIMEBase +from email import encoders +import time +import requests +import json +import csv +import math +import smtplib, ssl +import sys + +def sendreport(message): + context = ssl.create_default_context() + with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server: + server.login(sender_email, password) + server.sendmail(sender_email,receiver_email,message) + time_msg=datetime.today() + time_msg = time_msg.strftime("%m/%d/%Y, %H:%M:%S") + print('Message sent at time {}'.format(time_msg)) + +def getships(): + """ + Retrieves MarineTraffic.com Extended Data from the API, using the ACF.ShipTracker@gmail.com API key. + Collates the data, records the request time. + If a vessel has a speed over 10 kts, the estimated wave height at distance 1m, 1000m, 2000m, and 3000m, are recorded. + This is to be used in concert with the rest of ACF_ShipTracker python script to save as a CSV and email once a day. + """ + response = requests.get( + 'https://services.marinetraffic.com/api/exportvessels/v:8/ea1f4a05afbd000ba30772a9979bf7aa743092cb/timespan:60/msgtype:extended/protocol:json') + json_data=response.content + redata=json.loads(json_data) + req_time0=datetime.today() + req_time=req_time0.strftime("%m/%d/%Y, %H:%M:%S") + for XX in range(len(redata)) : + speed_0=float(redata[XX][5]) + ship_speed_kts=speed_0/10 #in kts + if ship_speed_kts>max_speed: + shipdata = redata[XX] + lat = shipdata[3] + lon = shipdata[4] + parameters = {'latitude': lat, 'longitude': lon} + depth_request = requests.get('https://www.gmrt.org/services/PointServer?', params=parameters) + depth = float(str(depth_request.content, 'utf-8'))*-1 # depth in m + shipdata.extend([req_time]) + shipdata.extend([depth]) + ship_speed_ms=ship_speed_kts/1.944 + froude=ship_speed_ms/math.sqrt(9.8*depth) + if shipdata[23]=='Tug': + alpha_1=1 + else: + alpha_1=0.35 + alpha_1=float(alpha_1) + distance_interest=[1, 1000, 2000, 3000] + for II in distance_interest: + wave_height=depth*alpha_1*((II/depth)**-0.33)*froude**4 + shipdata.extend([round(wave_height,2)]) + matrix.append(shipdata) + time_ships=datetime.today() + time_ships = time_ships.strftime("%m/%d/%Y, %H:%M:%S") + print('Ship data collected at {}'.format(time_ships)) + + +exe_question=1 +max_speed=10 + +port = 465 # For SSL +sender_email='acf.shiptracker@gmail.com' +password = 'ACFships123' + +#receiver_email=input('Where should the email be sent? ') +#send_hour=input('When should the email be sent? (0-23) ') +receiver_email=sys.argv[1] + + +print('At 0:00, an email will be sent to {}'.format(receiver_email)) + +message_start = MIMEMultipart() +message_start["From"] = sender_email +message_start["To"] = receiver_email +message_start["Subject"] = "Starting ACF ShipTracker" + +body_start = """ +This is an automated ACF ShipTracker Email, which has begun tracking ships.\n + +An email containing information about these vessels will be sent to this email ({}).\n + +This email will contain a CSV file listing all of the information about these vessels for the previous day.\n + +Please do not respond to this email. For assistance, please contact Justin Blancher (jeblancher@gmail.com) for any +troubleshooting. +""".format(receiver_email) + +message_start.attach(MIMEText(body_start, 'plain')) +text_start = message_start.as_string() +sendreport(text_start) + +x=datetime.today() +start_time=x.strftime("%m/%d/%Y, %H:%M:%S") +y = x.replace(day=x.day, hour=x.hour, second=0, minute=0, microsecond=0) + timedelta(hours=1) +delta_t=y-x +secs=delta_t.total_seconds() +#print(secs) + + +rowheadings=[ + 'MMSI', 'IMO', 'SHIP_ID', 'LAT', 'LON', 'SPEED', + 'HEADING', 'COURSE', 'STATUS', 'TIMESTAMP', 'DSRC', 'UTC_SECONDS', + 'SHIPNAME', 'SHIPTYPE', 'CALLSIGN', 'FLAG', 'LENGTH', 'WIDTH', 'GRT', 'DWT', + 'DRAUGHT', 'YEAR_BUILT', 'ROT', 'TYPE_NAME', 'AIS_TYPE_SUMMARY', + 'DESTINATION', 'ETA', 'Request Time', 'DEPTH','Est Wave Height 1m', 'Est Wave Height 1000m', + 'Est Wave Height 2000m', 'Est Wave Height 3000m' +] + +time.sleep(secs) +matrix = [] +counter=0 + +while exe_question>0: + x2=datetime.today() + y2 = x2.replace(day=x2.day, hour=x2.hour, minute=0, second=0, microsecond=0) + timedelta(hours=1) + delta_t2 = y2 - x2 + secs2 = delta_t2.total_seconds() + #print(secs2) + time.sleep(secs2) + getships() + if x2.hour == 23: + csv_name = "ACFshipdata_{}_{}_{}.csv".format(x2.month, x2.day,x2.year) + with open(csv_name, 'w') as outfile: + writer = csv.writer(outfile) + writer.writerow(rowheadings) + writer.writerows(matrix) + outfile.close() + attachment = open(csv_name, "rb") + p = MIMEBase('application', 'octet-stream') + p.set_payload((attachment).read()) + encoders.encode_base64(p) + p.add_header('Content-Disposition', "attachment; filename= %s" % csv_name) + attachment.close() + message = MIMEMultipart() + message.attach(p) + message["From"] = sender_email + message["To"] = receiver_email + message["Subject"] = "Mobile Bay Ship information from ".format(x2.minute) + + body = """ + This is an automated ACF ShipTracker Email, which has been running since {}.\n + \n + In the past {} hours, a total of {} ships were detected as going faster than {} kts.\n + \n + Attached is the information for these ships. \n + \n + Please do not respond to this email. For assistance, please contact Justin Blancher (jeblancher@gmail.com) for any +troubleshooting. + """.format(start_time,counter,len(matrix),max_speed) + + message.attach(MIMEText(body, 'plain')) + text = message.as_string() + sendreport(text) + matrix = [] + counter+=1 + +