summaryrefslogtreecommitdiff
path: root/vdv-server/VDV451.hs
blob: 8e8a841b736f000168a1a5a3fe828c9f3ac88c71 (plain)
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
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleInstances #-}


module VDV451 where

import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString as SB
import Data.ByteString (ByteString)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Vector (Vector)
import qualified Data.Vector as V
import qualified Data.ByteString.Char8 as C8
import GHC.Base (ord)
import Fmt ((+|),(|+))
import Data.Time (Day, toGregorian, UTCTime (..), DiffTime, formatTime, defaultTimeLocale, isLeapYear)
import Data.String (IsString)
import GHC.Exts (IsString(..))
import Data.Time.Format.ISO8601 (formatShow)
import Data.Data (Proxy (..))
import Data.Time.Calendar.MonthDay (monthAndDayToDayOfYear)
import Codec.Archive.Zip (toEntry, emptyArchive, addEntryToArchive, Archive)

class ÖPNVEncode a where
  encode :: a -> ByteString
  default encode :: Show a => a -> ByteString
  encode = C8.pack . show


instance ÖPNVEncode Text where
  -- hopefully not too naive iso8859-1 encoding
  encode text = if T.null unsafe
    then C8.pack bytes
    else error ("invalid unicode in iso8859-1 string: "+|unsafe|+".")
    where (safe, unsafe) = T.span (\c -> ord c <= 0xFF) text
          bytes = "\"" <> concatMap escape (T.unpack safe) <> "\""
          escape c = case c of
            '"' -> "\"\""
            a -> [a]

instance ÖPNVEncode Day where
  encode day = "\""+|crop 2 d|+"."+|crop 2 m|+"."+|crop 4 y|+"\""
    where (y,m,d) = toGregorian day

-- | for things which can be encoded as either string or number,
-- this module defaults to strings. Add this newtype to the schema
-- to make things encode as numbers instead.
newtype AsNumber a = AsNumber a

instance ÖPNVEncode (AsNumber Day) where
  encode (AsNumber day) =
    encode (d*1000000 + m*10000 + (fromInteger y `mod` 10000))
    where (y,m,d) = toGregorian day

instance ÖPNVEncode DiffTime where
  encode = C8.pack . formatTime defaultTimeLocale "\"%2H:%2M:%2S\""

instance ÖPNVEncode Int
instance ÖPNVEncode Integer


-- | these are encoded in a horrible format
newtype Longitude = Longitude Double
newtype Latitude = Latitude Double

encodeGeoLength :: Double -> ByteString
encodeGeoLength d' = ""+|sign|+""+|crop 3 deg|+""+|crop 2 min|+""+|crop 5 sec|+""
  where deg = truncate d
        min = truncate (d * 60) `mod` 60
        sec = truncate (d * 3600 * 1000) `mod` (60 * 1000)
        d = abs d'
        sign :: Text
        sign = if d' < 0 then "-" else ""

instance ÖPNVEncode Latitude where
  encode (Latitude d) = encodeGeoLength d
instance ÖPNVEncode Longitude where
  encode (Longitude d) = encodeGeoLength d

-- | this isn't specified anywhere, but seems to be what VDV 452 implies
instance ÖPNVEncode a => ÖPNVEncode (Maybe a) where
  encode (Just a) = encode a
  encode Nothing = "0"

instance ÖPNVEncode Bool where
  encode False = "0"
  encode True = "1"

data ÖPNVBefehl =
  MOD | SRC | CHS | VER | IFV
  | DVE | FFT | TBL | ATR | FRM
  | REC | END | EOF | COM
  deriving Show

instance ÖPNVEncode ÖPNVBefehl where
  encode MOD = "mod"
  encode SRC = "src"
  encode CHS = "chs"
  encode VER = "ver"
  encode IFV = "ifv"
  encode DVE = "dve"
  encode FFT = "fft"
  encode TBL = "tbl"
  encode ATR = "atr"
  encode FRM = "frm"
  encode REC = "rec"
  encode END = "end"
  encode EOF = "eof"
  encode COM = "com"

data ÖPNVType =
  ÖChar Int | ÖNum Int
  deriving Show

instance ÖPNVEncode ÖPNVType where
  encode (ÖChar n) = "char["+|n|+"]"
  encode (ÖNum n) = "num["+|n|+".0]"

class ÖPNVDatum a where
  tableName :: Proxy a -> ByteString
  tableNumber :: Proxy a -> Int
  tableSchema :: Proxy a -> [(ByteString, ÖPNVType, a -> Feld)]

encodeRow :: forall a. ÖPNVDatum a => a -> [Feld]
encodeRow a = fmap (\f -> f a) accessors
  where accessors = fmap (\(_,_,a) -> a) (tableSchema (Proxy @a))

tableInfo :: ÖPNVDatum a => Proxy a -> [(ByteString, ÖPNVType)]
tableInfo proxy = fmap (\(n, ty, _) -> (n, ty)) (tableSchema proxy)

data Feld = forall a. ÖPNVEncode a => F a | Raw ByteString

data ÖPNVOptions = ÖPNVOptions
  { öpnvSource :: Text
  , öpnvProgramVersion :: Text
  , öpnvDataVersion :: Text
  } deriving Show


öpnvSchnittstellenDaten :: forall a. ÖPNVDatum a => ÖPNVOptions -> UTCTime -> Vector a -> LB.ByteString
öpnvSchnittstellenDaten ÖPNVOptions{..} time rows = LB.intercalate "\n" $ fmap mkRow
  [ [F MOD, Raw "DD.MM.YYYY", Raw "HH:MM:SS", Raw "free"]
  , [F SRC, F öpnvSource, F (utctDay time), F (utctDayTime time) ]
  , [F CHS, F ("ISO8859-1" :: Text)]
  , [F VER, F öpnvProgramVersion]
  , [F IFV, F ("1.0" :: Text)]
  , [F DVE, F öpnvDataVersion]
  , [F FFT, F ("" :: Text)] -- this one is probably not needed?
  , [F TBL, Raw (tableName (Proxy @a))]
  , F ATR : fmap Raw colNames
  , F FRM : fmap F colTypes]
  <> fmap (mkRow . (:) (F REC) . encodeRow) (V.toList rows)
  <> fmap mkRow
  [ [F END, F (length rows)]
  , [F EOF, Raw "1"]]
  where
    mkRow :: [Feld] -> LB.ByteString
    mkRow = LB.fromStrict
      . C8.intercalate "; "
      . fmap (\case { (F a) -> encode a; Raw a -> a })
    (colNames, colTypes) = unzip (tableInfo (Proxy @a))

öpnvSchnittstellenDatei :: forall a. ÖPNVDatum a => ÖPNVOptions -> UTCTime -> Vector a -> (FilePath, LB.ByteString)
öpnvSchnittstellenDatei options time rows = (filename, content)
  where content = öpnvSchnittstellenDaten options time rows
        filename = "i"+|tableNumber (Proxy @a)|+""+|dayOfYearPadded|+"0.x10"
        dayOfYearPadded =
          replicate (3 - length (show dayOfYear)) '0' <> show dayOfYear
        (year, month, day) = toGregorian (utctDay time)
        dayOfYear = monthAndDayToDayOfYear
                     (isLeapYear year) month day

data ÖPNVTable = forall a. ÖPNVDatum a => ÖPNVTable (Vector a)

öpnvSchnittstellenZip :: ÖPNVOptions -> UTCTime -> [ÖPNVTable] -> Archive
öpnvSchnittstellenZip options time tables =
  foldl addTableEntry emptyArchive tables
  where unixt = 0 -- nominalDiffTimeToSeconds (utcTimeToPOSIXSeconds time)
        addTableEntry archive (ÖPNVTable t) =
          addEntryToArchive (toEntry filename unixt content) archive
          where (filename,content) = öpnvSchnittstellenDatei options time t

crop n thing = if T.length shown < n
  then T.replicate (n - T.length shown) "0" <> shown
  else T.takeEnd n shown
  where shown = T.pack $ show thing