#!/usr/bin/env python
#test
import os
from socket import *
from datetime import datetime, time
import math

import psycopg2
import psycopg2.extensions
from psycopg2.extras import Json
conn = psycopg2.connect(host='localhost', database='nws', user='nws', password='nws')
cursor = conn.cursor()

cursor.execute("SELECT stationid,lat,lon,tempf,dewpt, humidity,winddir,windspd,windgust,cwop,cwoptime,preciptotal, pressure from wusites WHERE (Active = True and CWOP IS NOT NULL) and (((EXTRACT(EPOCH FROM (current_timestamp - cwoptime ))/60)  > 9 ) or (cwoptime ISNULL)) and ((EXTRACT(EPOCH FROM (current_timestamp - lastob ))/60)  < 15 )")
allcwasites = cursor.fetchall()
print(allcwasites)


def decdeg2dms(dd,pad):
   is_positive = dd >= 0
   dd = abs(dd)
   minutes,seconds = divmod(dd*3600,60)
   degrees,minutes = divmod(minutes,60)
   degrees = degrees
   if pad == 'lat':
       coord = str(int(degrees)).zfill(2) + str(int(minutes)).zfill(2) + '.' + str(int(seconds)).zfill(2)
       if is_positive:
           coord = coord + 'N'
       if not(is_positive):
           coord = coord + 'S'
   if pad == 'lon':
       coord = str(int(degrees)).zfill(3) + str(int(minutes)).zfill(2) + '.' + str(int(seconds)).zfill(2)
       if is_positive:
           coord = coord + 'E'
       if not(is_positive):
           coord = coord + 'W'  

   return (coord)

devicename = 'WURELAY' #This identifies your equipment/software. You can put anything you want. I use 'WS2902A', which is the model of weather station I have


for i in allcwasites:
    stationid = i[0]
    latitude = i[1]
    longitude = i[2]
    tempf = i[3]
    dewpt = i[4]
    humidity = i[5]
    winddir = i[6]
    windspd = i[7]
    windgust = i[8]
    callsign = i[9]
    cwoptime = i[10]
    preciptotal = i[11]
    pressure = i[12]
    latitude = decdeg2dms(latitude,'lat')
    longitude = decdeg2dms(longitude,'lon') 
    print(i)
    
    if tempf != None:
     if tempf < 0:
      temp = str(int(round(tempf))).zfill(3)
     else:
      temp = str(int(round(tempf))).zfill(3)
    else:
     temp = '...'
    if (winddir != None and winddir > -1):
        winddir = str(int(winddir)).zfill(3)
    else:
        winddir = '...'
    if windspd != None:
       if windspd > 99:
        windspeed = '...'
       else:
        windspeed = str(int(math.ceil(windspd))).zfill(3)
    else:
        windspeed = '...'        
    if windgust != None:
      if windgust > 99:
        windgust = '...'
      else:
        windgust = str(int(math.ceil(windgust))).zfill(3)
    else:
        windgust = '...'        
    if humidity != None:
        if humidity > 8:
          humidity = str(int(humidity%100)).zfill(2)
        else:
           humidity = '...'
    else:
        humidity = '...'
    if pressure != None:
     if pressure > 29.00 and pressure < 31.00:
        pressure = str(int(pressure * 338.63886666667)).zfill(5)
     else:
        pressure = '...'
    else:
        pressure = '...' 
    
    if preciptotal != None:
        preciptotal = str(int(preciptotal*100)).zfill(3)
    else:
        preciptotal = '...'
    packet = callsign + '>APRS,TCPIP*:@' + datetime.utcnow().strftime("%d%H%M") + 'z' + latitude + '/' + longitude + '_' + winddir + '/' + windspeed + 'g' + windgust + 't' + temp + 'r...P' + preciptotal + 'h' + humidity + 'b' + pressure + devicename
    
    s = socket(AF_INET, SOCK_STREAM)
    s.connect(('cwop.aprs.net', 14580))
    print(packet)
    s.send(('user ' + callsign + ' pass -1 vers Python\n').encode())
    s.send((packet+'\n').encode())
    s.shutdown(0)
    s.close()
    sql = 'UPDATE wusites set cwoptime = current_timestamp where cwop = %s'
    val = (callsign,)
    cursor.execute(sql,val)
    conn.commit()









