forked from johnbeil/BuoyBot
/
buoybot.go
338 lines (295 loc) · 9.84 KB
/
buoybot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Copyright (c) 2016 John Beil.
// Use of this source code is governed by the MIT License.
// The MIT license can be found in the LICENSE file.
// BuoyBot 1.5
// Obtains latest observation for NBDC Station 46026
// Saves observation to database
// Obtains next tide from database
// Tweets observation and tide prediction from @SFBuoy
// See README.md for setup information
package main
import (
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/ChimeraCoder/anaconda"
_ "github.com/lib/pq"
)
// First two rows of text file, fixed width delimited, used for debugging
const header = "#YY MM DD hh mm WDIR WSPD GST WVHT DPD APD MWD PRES ATMP WTMP DEWP VIS PTDY TIDE\n#yr mo dy hr mn degT m/s m/s m sec sec degT hPa degC degC degC nmi hPa ft"
// URL for SF Buoy Observations
const noaaURL = "http://www.ndbc.noaa.gov/data/realtime2/46026.txt"
// Observation struct stores buoy observation data
type Observation struct {
Date time.Time
WindDirection string
WindSpeed float64
SignificantWaveHeight float64
DominantWavePeriod int
AveragePeriod float64
MeanWaveDirection string
AirTemperature float64
WaterTemperature float64
}
// Config struct stores Twitter and Database credentials
type Config struct {
UserName string `json:"UserName"`
ConsumerKey string `json:"ConsumerKey"`
ConsumerSecret string `json:"ConsumerSecret"`
Token string `json:"Token"`
TokenSecret string `json:"TokenSecret"`
DatabaseUrl string `json:"DatabaseUrl"`
DatabaseUser string `json:"DatabaseUser"`
DatabasePassword string `json:"DatabasePassword"`
DatabaseName string `json:"DatabaseName"`
}
// Tide stores a tide prediction from the database
type Tide struct {
Date string
Day string
Time string
PredictionFt float64
PredictionCm int64
HighLow string
}
// Variable for database
var db *sql.DB
func main() {
fmt.Println("Starting BuoyBot...")
// Load configuration
config := Config{}
loadConfig(&config)
// Load database
dbinfo := fmt.Sprintf("user=%s password=%s host=%s dbname=%s sslmode=disable",
config.DatabaseUser, config.DatabasePassword, config.DatabaseUrl, config.DatabaseName)
var err error
db, err = sql.Open("postgres", dbinfo)
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Check database connection
err = db.Ping()
if err != nil {
log.Fatal("Error: Could not establish connection with the database.", err)
}
// Get latest observation and store in struct
var observation Observation
observation = getObservation()
// Save latest observation in database
saveObservation(observation)
// Obtain next tide from database
tide := getTide()
// Format tide
tideOutput := processTide(tide)
// Format observation given Observation and tideOutput
observationOutput := formatObservation(observation, tideOutput)
// Tweet observation at 0000, 0600, 0900, 1200, 1500, 1800 PST
t := time.Now()
if t.Hour() == 0 || t.Hour() == 6 || t.Hour() == 9 || t.Hour() == 12 || t.Hour() == 15 || t.Hour() == 18 {
tweetCurrent(config, observationOutput)
} else {
fmt.Println("Not at update interval - not tweeting.")
fmt.Println(observationOutput)
}
// Shutdown BuoyBot
fmt.Println("Exiting BuoyBot...")
}
// Fetches and parses latest NBDC observation and returns data in Observation struct
func getObservation() Observation {
observationRaw := getDataFromURL(noaaURL)
observationData := parseData(observationRaw)
return observationData
}
// Given Observation struct, saves most recent observation in database
func saveObservation(o Observation) {
_, err := db.Exec("INSERT INTO observations(observationtime, windspeed, winddirection, significantwaveheight, dominantwaveperiod, averageperiod, meanwavedirection, airtemperature, watertemperature) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9)", o.Date, o.WindSpeed, o.WindDirection, o.SignificantWaveHeight, o.DominantWavePeriod, o.AveragePeriod, o.MeanWaveDirection, o.AirTemperature, o.WaterTemperature)
if err != nil {
log.Fatal("Error saving observation:", err)
}
}
// Given config and observation, tweets latest update
func tweetCurrent(config Config, o string) {
fmt.Println("Preparing to tweet observation...")
var api *anaconda.TwitterApi
api = anaconda.NewTwitterApi(config.Token, config.TokenSecret)
anaconda.SetConsumerKey(config.ConsumerKey)
anaconda.SetConsumerSecret(config.ConsumerSecret)
tweet, err := api.PostTweet(o, nil)
if err != nil {
fmt.Println("update error:", err)
} else {
fmt.Println("Tweet posted:")
fmt.Println(tweet.Text)
}
}
// Given URL, returns raw data with recent observations from NBDC
func getDataFromURL(url string) (body []byte) {
resp, err := http.Get(url)
if err != nil {
log.Fatal("Error fetching data:", err)
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("ioutil error reading resp.Body:", err)
}
// fmt.Println("Status:", resp.Status)
return
}
// Given path to config.js file, loads credentials
func loadConfig(config *Config) {
// load path to config from CONFIGPATH environment variable
configpath := os.Getenv("CONFIGPATH")
file, _ := os.Open(configpath)
decoder := json.NewDecoder(file)
err := decoder.Decode(&config)
if err != nil {
log.Fatal("Error loading config.json:", err)
}
}
// Given raw data, parses latest observation and returns Observation struct
func parseData(d []byte) Observation {
// Each line contains 19 data points
// Headers are in the first two lines
// Latest observation data is in the third line
// Other lines are not needed
// Extracts relevant data into variable for processing
var data = string(d[188:281])
// convert most recent observation into array of strings
datafield := strings.Fields(data)
// convert wave height from meters to feet
waveheightmeters, _ := strconv.ParseFloat(datafield[8], 64)
waveheightfeet := waveheightmeters * 3.28084
// convert wave direction from degrees to cardinal
wavedegrees, _ := strconv.ParseInt(datafield[11], 0, 64)
wavecardinal := direction(wavedegrees)
// convert wind speed from m/s to mph
windspeedms, _ := strconv.ParseFloat((datafield[6]), 64)
windspeedmph := windspeedms / 0.44704
// convert wind direction from degrees to cardinal
winddegrees, _ := strconv.ParseInt(datafield[5], 0, 64)
windcardinal := direction(winddegrees)
// convert air temp from C to F
airtempC, _ := strconv.ParseFloat(datafield[13], 64)
airtempF := airtempC*9/5 + 32
airtempF = RoundPlus(airtempF, 1)
// convert water temp from C to F
watertempC, _ := strconv.ParseFloat(datafield[14], 64)
watertempF := watertempC*9/5 + 32
watertempF = RoundPlus(watertempF, 1)
// process date/time and convert to PST
rawtime := strings.Join(datafield[0:5], " ")
t, err := time.Parse("2006 01 02 15 04", rawtime)
if err != nil {
log.Fatal("error processing rawtime:", err)
}
loc, err := time.LoadLocation("America/Los_Angeles")
if err != nil {
log.Fatal("error processing location", err)
}
t = t.In(loc)
// Create Observation struct and populate with parsed data
var o Observation
o.Date = t
o.WindDirection = windcardinal
o.WindSpeed = windspeedmph
o.SignificantWaveHeight = waveheightfeet
o.DominantWavePeriod, err = strconv.Atoi(datafield[9])
if err != nil {
log.Fatal("o.AveragePeriod:", err)
}
o.AveragePeriod, err = strconv.ParseFloat(datafield[10], 64)
if err != nil {
log.Fatal("o.AveragePeriod:", err)
}
o.MeanWaveDirection = wavecardinal
o.AirTemperature = airtempF
o.WaterTemperature = watertempF
return o
}
// Given Observation returns formatted text for tweet
func formatObservation(o Observation, tide string) string {
output := fmt.Sprint(o.Date.Format(time.RFC822), "\nSwell: ", strconv.FormatFloat(float64(o.SignificantWaveHeight), 'f', 1, 64), "ft at ", o.DominantWavePeriod, " sec from ", o.MeanWaveDirection, "\nWind: ", strconv.FormatFloat(float64(o.WindSpeed), 'f', 0, 64), "mph from ", o.WindDirection, "\n", tide, "\nTemp: Air ", o.AirTemperature, "F / Water: ", o.WaterTemperature, "F")
return output
}
// given degrees returns cardinal direction
func direction(deg int64) string {
switch {
case deg < 0:
return "ERROR - DEGREE LESS THAN ZERO"
case deg <= 11:
return "N"
case deg <= 34:
return "NNE"
case deg <= 56:
return "NE"
case deg <= 79:
return "ENE"
case deg <= 101:
return "E"
case deg <= 124:
return "ESE"
case deg <= 146:
return "SE"
case deg <= 169:
return "SSE"
case deg <= 191:
return "S"
case deg <= 214:
return "SSW"
case deg <= 236:
return "SW"
case deg <= 259:
return "WSW"
case deg <= 281:
return "W"
case deg <= 304:
return "WNW"
case deg <= 326:
return "NW"
case deg <= 349:
return "NNW"
case deg <= 360:
return "N"
default:
return "ERROR - DEGREE GREATER THAN 360"
}
}
// Round input to nearest integer given Float64 and returns Float64
func Round(f float64) float64 {
return math.Floor(f + .5)
}
// RoundPlus truncates a Float64 to a defined number of decimals given an Int and Float64, and returns a Float64
func RoundPlus(f float64, places int) float64 {
shift := math.Pow(10, float64(places))
return Round(f*shift) / shift
}
// getTide selects the next tide prediction from the database and return a Tide struct
func getTide() Tide {
var tide Tide
err := db.QueryRow("select date, day, time, predictionft, highlow from tidedata where datetime >= current_timestamp order by datetime limit 1").Scan(&tide.Date, &tide.Day, &tide.Time, &tide.PredictionFt, &tide.HighLow)
if err != nil {
log.Fatal("getTide function error:", err)
}
return tide
}
// processTide returns a formatted string give a Tide struct
func processTide(t Tide) string {
if t.HighLow == "H" {
t.HighLow = "High"
} else {
t.HighLow = "Low"
}
s := "Tide: " + t.HighLow + " " + strconv.FormatFloat(float64(t.PredictionFt), 'f', 1, 64) + "ft at " + t.Time
// fmt.Println(s)
return s
}