Make alerts async

This commit is contained in:
April 2022-11-12 13:22:25 -07:00
parent 900cad0b9b
commit c20b48b6d9
No known key found for this signature in database
GPG Key ID: 17A9A017FAA4DE5E

View File

@ -9,6 +9,7 @@ import xml.dom.minidom
import shutil
import gzip
import logging,coloredlogs
import aiofiles, aiohttp
import sys
@ -26,15 +27,18 @@ headlineApiKey = '21d8a80b3d6b444998a80b3d6b1449d3'
detailsApiKey = '21d8a80b3d6b444998a80b3d6b1449d3'
k = 0
def getAlerts(location):
async def getAlerts(location):
global k
fetchUrl = 'https://api.weather.com/v3/alerts/headlines?areaId=' + location + ':US&format=json&language=en-US&apiKey=' + headlineApiKey
response = requests.get(fetchUrl)
# response = requests.get(fetchUrl)
theCode = response.status_code
# theCode = response.status_code
#Our global variables
theCode = 0
async with aiohttp.ClientSession() as s:
async with s.get(fetchUrl) as r:
theCode = await r.status
#Set the actions based on response code
if theCode == 204:
@ -67,9 +71,9 @@ def getAlerts(location):
elif theCode == 200:
pass
#Alright lets map our headline variables.
# Map headline variables
l.debug('Found Alert for ' + location + '\n')
dataH = response.json()
dataH = await r.json()
alertsRoot = dataH['alerts']
for x in alertsRoot:
@ -95,14 +99,15 @@ def getAlerts(location):
#theIdent = str(Identifier)
try:
thecheck = open('./.temp/alertmanifest.txt', "r")
check = thecheck.read()
async with aiofiles.open('./.temp/alertmanifest.txt', 'r' ) as checkFile:
c = await checkFile.read()
if check.find(Identifier) != -1:
l.debug("Alert already sent...")
if c.find(Identifier) != -1:
l.debug(f"{Identifier} was sent already, skipping..")
return
except FileNotFoundError:
l.warning("alert manifest does not exist (yet)")
k += 1 #We have an alert to send!
#Lets Map Our Vocal Codes!
@ -307,40 +312,40 @@ def getAlerts(location):
alertMsg = '<BERecord id="0000" locationKey="' + location + '_' + x['phenomena'] + '_' + x['significance'] + '_' + x['eventTrackingNumber'] + '_' + x['officeCode'] + '" isWxscan="0"><action>NOT_USED</action><BEHdr><bPIL>' + x['productIdentifier'] + '</bPIL><bWMOHdr>NOT_USED</bWMOHdr><bEvent><eActionCd eActionPriority="' + str(x['messageTypeCode']) + '">' + Action + '</eActionCd><eOfficeId eOfficeNm="' + x['officeName'] + '">' + x['officeCode'] + '</eOfficeId><ePhenom>' + x['phenomena'] + '</ePhenom><eSgnfcnc>' + x['significance'] + '</eSgnfcnc><eETN>' + x['eventTrackingNumber'] + '</eETN><eDesc>' + x['eventDescription'] + '</eDesc><eStTmUTC>NOT_USED</eStTmUTC><eEndTmUTC>' + EndTimeUTC + '</eEndTmUTC><eSvrty>' + str(x['severityCode']) + '</eSvrty><eTWCIId>NOT_USED</eTWCIId><eExpTmUTC>' + expireTimeUTC + '</eExpTmUTC></bEvent><bLocations><bLocCd bLoc="' + x['areaName'] + '" bLocTyp="' + locationType + '">' + location + '</bLocCd><bStCd bSt="' + x['adminDistrict'] + '">' + x['adminDistrictCode'] + '</bStCd><bUTCDiff>NOT_USED</bUTCDiff><bTzAbbrv>NOT_USED</bTzAbbrv><bCntryCd>NOT_USED</bCntryCd></bLocations><bSgmtChksum>' + x['identifier'] + '</bSgmtChksum><procTm>' + processTime + '</procTm></BEHdr><BEData><bIssueTmUTC>' + issueTimeUtc + '</bIssueTmUTC><bHdln><bHdlnTxt>' + x['headlineText'] + '</bHdlnTxt>' + vocalCode + '</bHdln><bParameter>NOT_USED</bParameter><bNarrTxt bNarrTxtLang="en-US"><bLn>' + description + '</bLn></bNarrTxt><bSrchRslt>NOT_USED</bSrchRslt></BEData><clientKey>' + location + '_' + x['phenomena'] + '_' + x['significance'] + '_' + x['eventTrackingNumber'] + '_' + x['officeCode'] + '</clientKey></BERecord>'
#Append BERecord
with open('./.temp/BERecord.xml', "a") as b:
b.write(alertMsg)
b.close()
async with aiofiles.open('./.temp/BERecord.xml', "a") as b:
await b.write(alertMsg)
await b.close()
#Add our alert to the manifest so we don't keep sending in the same alert every 60 seconds unless an update is issued.
with open('./.temp/alertmanifest.txt', "a") as c:
c.write('\n' + location + '_' + x['phenomena'] + '_' + x['significance'] + '_' + str(x['processTimeUTC']))
c.close()
async with aiofiles.open('./.temp/alertmanifest.txt', "a") as c:
await c.write('\n' + location + '_' + x['phenomena'] + '_' + x['significance'] + '_' + str(x['processTimeUTC']))
await c.close()
# TODO: This should be converted into a function so it works better with async, that way we're not getting hung up on that time.sleep() call.
def makeRecord():
async def makeRecord():
global k
with open("./.temp/BERecord.xml", 'a') as BERecord:
BERecord.write('<Data type="BERecord">')
BERecord.close()
# The BERecord XML doesn't need to be written if there's no alerts.
if k > 0:
async with aiofiles.open("./.temp/BERecord.xml", 'a') as BERecord:
await BERecord.write('<Data type="BERecord">')
await BERecord.close()
for z in alertLocations:
getAlerts(z)
await getAlerts(z)
with open('./.temp/BERecord.xml', 'a') as BERecord:
BERecord.write("</Data>")
BERecord.close()
async with aiofiles.open('./.temp/BERecord.xml', 'a') as BERecord:
await BERecord.write("</Data>")
await BERecord.close()
dom = xml.dom.minidom.parse("./.temp/BERecord.xml")
pretty_xml_as_string = dom.toprettyxml(indent = " ")
with open("./.temp/BERecord.i2m", 'w') as h:
h.write(pretty_xml_as_string[23:])
h.close()
async with aiofiles.open("./.temp/BERecord.i2m", 'w') as h:
await h.write(pretty_xml_as_string[23:])
await h.close()
# If we don't need to send the i2 an alert, we don't need to gzip it.
if k > 0:
l.info("Sending alert(s) to the IntelliStar 2!")
with open("./.temp/BERecord.i2m", 'rb') as f_in:
with gzip.open("./.temp/BERecord.gz", 'wb') as f_out: