alfred.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import print_function
  4. import io
  5. import json
  6. import subprocess
  7. import time
  8. class AlfredParser:
  9. alfred_json = 'alfred-json'
  10. alfred_datatypes = [('static', 158), ('dynamic', 159)]
  11. def __str__(self):
  12. types = ['{1}=>{0}'.format(x[0], x[1]) for x in self.alfred_datatypes]
  13. return 'AlfredParser \'{0}\' {1}'.format(
  14. self.alfred_json,
  15. str.join(' ', types),
  16. )
  17. def sanitycheck(self):
  18. testdata = None
  19. try:
  20. cmd = [self.alfred_json, '-z', '-r', str(int(self.alfred_datatypes[0][1]))]
  21. testdata = subprocess.check_output(cmd)
  22. except Exception as err:
  23. raise Exception("alfred-json not found or incompatible: " + str(err))
  24. try:
  25. json.loads(testdata)
  26. except Exception as err:
  27. raise Exception("alfred-json does not return valid JSON data: " + str(err))
  28. return True
  29. def fetch(self, alfred_dump=None, include_rawdata=False):
  30. data = { }
  31. ts = int(time.time())
  32. alfreddata = {}
  33. for datatype in self.alfred_datatypes:
  34. rawdata = subprocess.check_output([self.alfred_json, '-z', '-r', str(int(datatype[1]))])
  35. newdata = json.loads(rawdata)
  36. for item in newdata:
  37. if not item in alfreddata:
  38. alfreddata[item] = {}
  39. alfreddata[item][datatype[0]] = newdata[item]
  40. if not alfred_dump is None:
  41. jsondata = json.dumps(alfreddata, ensure_ascii=False)
  42. dumpfile = io.open(alfred_dump, 'w')
  43. dumpfile.write(jsondata)
  44. dumpfile.close()
  45. for alfredid in alfreddata:
  46. alfredinfo = alfreddata[alfredid]
  47. if 'node_id' in alfredinfo['static']:
  48. myid = alfredinfo['static']['node_id']
  49. else:
  50. alfredid.lower().replace(':', '')
  51. nodeinfo = {
  52. 'hostname': None,
  53. 'mac': None,
  54. 'software': {},
  55. 'statistics': {},
  56. '__UPDATED__': {'alfred': ts,},
  57. '__RAW__': {'alfred': alfredinfo,},
  58. }
  59. data[myid] = nodeinfo
  60. nodestatic = alfredinfo['static']
  61. if 'hostname' in nodestatic:
  62. nodeinfo['hostname'] = nodestatic['hostname']
  63. if 'network' in nodestatic:
  64. if 'mac' in nodestatic['network']:
  65. nodeinfo['mac'] = nodestatic['network']['mac']
  66. if 'mesh_interfaces' in nodestatic['network']:
  67. nodeinfo['macs'] = [x for x in nodestatic['network']['mesh_interfaces']]
  68. else:
  69. nodeinfo['macs'] = []
  70. if 'software' in nodestatic:
  71. sw = nodestatic['software']
  72. nodeinfo['software']['firmware'] = sw['firmware']['release'] if 'firmware' in sw and 'release' in sw['firmware'] else None
  73. nodeinfo['software']['autoupdater'] = sw['autoupdater']['branch'] if sw['autoupdater']['enabled'] else 'off'
  74. nodedyn = alfredinfo['dynamic'] if 'dynamic' in alfredinfo else nodestatic['statistics']
  75. if 'uptime' in nodedyn:
  76. nodeinfo['uptime'] = int(float(nodedyn['uptime']))
  77. if 'gateway' in nodedyn:
  78. nodeinfo['gateway'] = nodedyn['gateway']
  79. traffic = nodedyn["traffic"] if "traffic" in nodedyn else None
  80. if not traffic is None:
  81. if not 'traffic' in nodeinfo['statistics']:
  82. nodeinfo['statistics']['traffic'] = { }
  83. t = nodeinfo['statistics']['traffic']
  84. t['rxbytes'] = int(traffic["rx"]["bytes"])
  85. t['txbytes'] = int(traffic["tx"]["bytes"])
  86. return data
  87. if __name__ == "__main__":
  88. a = AlfredParser()
  89. try:
  90. a.sanitycheck()
  91. except Exception as err:
  92. print('SANITY-CHECK failed:', str(err))
  93. import sys
  94. sys.exit(1)
  95. adata = a.fetch()
  96. print(json.dumps(adata))