| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
suppressMessages(library(pbdZMQ, quietly = TRUE)) |
| 7 |
|
| 8 |
|
| 9 |
cat("Collecting updates from weather server ...\n"); |
| 10 |
context <- zmq.ctx.new() |
| 11 |
subscriber <- zmq.socket(context, ZMQ.ST()$SUB) |
| 12 |
zmq.connect(subscriber, "tcp://localhost:5556") |
| 13 |
|
| 14 |
|
| 15 |
filters <- c("50011", "37831", "37996", "20993") |
| 16 |
for(i in 1:length(filters)){ |
| 17 |
cat("Subscribe zipcode", filters[i], "\n") |
| 18 |
zmq.setsockopt(subscriber, ZMQ.SO()$SUBSCRIBE, filters[i]) |
| 19 |
} |
| 20 |
|
| 21 |
|
| 22 |
N.updates <- 30 |
| 23 |
temperature <- vector(mode = "list", length = 4) |
| 24 |
while(any(sapply(temperature, length) < N.updates)){ |
| 25 |
string <- zmq.recv(subscriber) |
| 26 |
msg <- strsplit(string$buf, " ")[[1]] |
| 27 |
|
| 28 |
id <- which(msg[1] == filters) |
| 29 |
temperature[[id]] <- c(temperature[[id]], as.integer(msg[2])) |
| 30 |
|
| 31 |
if(length(temperature[[id]]) == N.updates){ |
| 32 |
|
| 33 |
cat("Unsubscribe zipcode", filters[id], "\n", sep = " "); |
| 34 |
zmq.setsockopt(subscriber, ZMQ.SO()$UNSUBSCRIBE, filters[id]) |
| 35 |
} |
| 36 |
} |
| 37 |
avg.temperature <- sapply(temperature, mean) |
| 38 |
|
| 39 |
|
| 40 |
for(i in 1:length(filters)){ |
| 41 |
cat("Average temperature for zipcode", filters[i], |
| 42 |
"was", avg.temperature[i], "\n") |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
zmq.close(subscriber) |
| 47 |
zmq.ctx.destroy(context) |