ctucx.git: fritzbox-exporter

[nimlang] prometheus exporter for lte fritzboxes

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 
import strutils, json

proc CtrlCHook* () {.noconv.} =
  echo "Ctrl+C fired! \nStopping Server now!"
  quit()

proc isInt* (s: string): bool =
  try:
    discard s.parseInt()
    result = true
  except:
    discard

proc isFloat* (s: string): bool =
  try:
    discard s.parseFloat()
    result = true
  except:
    discard

proc parseCtlMgr* (n: string): JsonNode =
  var input = n.split("\n")

  input.del(0)

  var last_group = ""

  var data = newJObject()

  for i in items(input):
    let line = strip(i)
    if line == "": continue

    if endsWith(line, "/"):
      last_group = replace(line, "/", "")
      continue

    let entry = line.split("=")

    var value = ""

    if entry.len > 1:
        value = entry[1]

    if last_group == "":
      if isInt(value):
        data.add(entry[0], newJInt(parseInt(value)))
      elif isFloat(value):
        data.add(entry[0], newJFloat(parseFloat(value)))
      else:
        data.add(entry[0], %(value))
    else:
      if not data.hasKey(last_group):
        data.add(last_group, newJObject())

      if isInt(value):
        data[last_group].add(entry[0], newJInt(parseInt(value)))
      elif isFloat(value):
        data[last_group].add(entry[0], newJFloat(parseFloat(value)))
      else:
        data[last_group].add(entry[0], %(value))
  return data

proc getTxTraffic* (data: JsonNode, mode: string): int =
  if data[mode].hasKey("BytesSentHigh") and data[mode].hasKey("BytesSentLow"):
    return data[mode]["BytesSentHigh"].getInt shl 32 + data[mode]["BytesSentLow"].getInt

proc getRxTraffic* (data: JsonNode, mode: string): int =
  if data[mode].hasKey("BytesReceivedHigh") and data[mode].hasKey("BytesReceivedLow"):
    return data[mode]["BytesReceivedHigh"].getInt shl 32 + data[mode]["BytesReceivedLow"].getInt