Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mskyttner/4e72baef580ab1d58fb59440925e077a to your computer and use it in GitHub Desktop.
Save mskyttner/4e72baef580ab1d58fb59440925e077a to your computer and use it in GitHub Desktop.
aisdecode.R
library(vikingr)
library(dplyr)
library(purrr)
library(stringr)
log <- read_ais_log(vikingr_example("vikingr-visby-2019-ais-2"))
log_tail <-
log$message %>%
str_replace("(.*?,){5}(.*?)", "\\2")
log_head <-
log$message %>%
str_extract("((.*?,){5})") %>%
str_remove(",$") %>%
readr::read_csv(col_names = letters[1:5])
log_clean <- bind_cols(
timestamp = log$timestamp,
log_head,
message = log_tail
)
to_payload <- function(message) {
message %>% utf8ToInt() - 48 %>%
map_dbl(function(x) if_else(x > 40, x - 8, x))
}
to_bits <- function(x, n_bits = 8) {
x %>% map(~ intToBits(.)[n_bits:1] %>% as.logical) %>% unlist
}
to_decimal <- function(bits) {
# using as.integer means bits should be <= 32
stopifnot(bits <= 32)
bits %*% 2^((length(bits) - 1):0) %>% as.integer
}
decode_bits <- function(bits) {
list(
msg_type = bits[1:6],
repeat_indicator = bits[7:8],
mmsi = bits[9:38],
nav_stat = bits[39:42],
rot = bits[43:50],
sog = bits[51:60],
pos_acc = bits[61],
lon = bits[62:89],
lat = bits[90:116],
cog = bits[117:128],
hdg = bits[118:137]
) %>%
map_df(to_decimal) %>%
mutate_at(vars(lon, lat), ~ . / 600000)
}
decode_ais <- function(message) {
decode_message <- function(x)
x %>% to_payload() %>% to_bits() %>% decode_bits()
message %>% map_df(decode_message)
}
# this is the resulting df after decoding the messages
df <- bind_cols(
log_clean,
decode_ais(log_clean$message)
)
decode_sixbits <- function(payload) {
six_bit <- c('@', LETTERS, '[', '\\', ']',
'^', '_', ' ', '!', '"', '#', '$', '%',
'&', '\'', '(', ')', '*', '+', ',', '-',
'.', '/', 0:9, ':', ';', '<', '=', '>', '?')
six_bit %>% set_names(c(0:(2^6 - 1)))
six_bit[payload]
}
# we seem not to have any type 5 messages so cannot test this
df %>% filter(msg_type == 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment