logger.py.configmap.yaml 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. apiVersion: v1
  2. data:
  3. logger.py: "#!/usr/bin/env python3\n\nimport time\nfrom datetime import datetime\n\
  4. import requests\nimport traceback\nfrom influxdb import InfluxDBClient\n\nOUT\
  5. \ = \"/data/log.csv\"\nURL = \"http://62.220.135.196:8080/sensor/{}?version=1.0&interval=minute&unit=watt\"\
  6. \nSENSORS = (\n \"34cde81adabfb1ce819eca8fea6949b6\",\n \"b7755b5f3ec05fcdc67f449241a9912a\"\
  7. ,\n \"e67e0685f747b30d855108ab781abdfc\"\n)\n\nprint(\"Starting logger\")\ndb\
  8. \ = InfluxDBClient('influxdb', database='power')\nprint(\"Connected to %s\" %\
  9. \ db)\n\nwhile True:\n points = []\n last_timestamps = {}\n\n for sensor in\
  10. \ SENSORS:\n try:\n last_timestamp = last_timestamps.get(sensor, 0)\n\
  11. \ flukso = requests.get(URL.format(sensor)).json()\n print(\"Before\
  12. \ filtering: \" + str(len(flukso)))\n\n # Remove NaN values\n flukso\
  13. \ = filter(lambda x: x[1] != 'nan', flukso)\n\n # Remove values that were\
  14. \ already seen before\n flukso = list(filter(lambda x: x[0] >= last_timestamp,\
  15. \ flukso))\n\n if len(flukso) > 0:\n last_timestamp = flukso[-1][0]\n\
  16. \n print(\"After filtering: \" + str(len(flukso)))\n\n for timestamp,\
  17. \ value in flukso:\n points.append((timestamp, sensor, value))\n except\
  18. \ Exception as e:\n traceback.print_exc()\n\n try:\n db.write_points([{\n\
  19. \ \"measurement\": \"flukso\",\n \"time\": datetime.fromtimestamp(timestamp).isoformat(),\n\
  20. \ \"tags\": {\n \"sensor\": sensor,\n },\n\
  21. \ \"fields\": { \"watts\": float(value) }\n } for timestamp,\
  22. \ sensor, value in points])\n print(\"Wrote %d samples to influxdb\" % len(points))\n\
  23. \ except Exception as e:\n print(\"Write to influxdb failed\")\n traceback.print_exc()\n\
  24. \n try:\n with open(OUT, 'a') as f:\n for timestamp, sensor, value in\
  25. \ points:\n f.write(\",\".join((str(timestamp), sensor, str(value))) +\
  26. \ \"\\n\")\n print(\"Wrote %d samples to csv\" % len(points))\n except Exception\
  27. \ as e:\n print(\"Write to csv file failed\")\n traceback.print_exc()\n\n\
  28. \ sleeptime = 45 * 1000000 - datetime.utcnow().microsecond\n print(\"Sleeping\
  29. \ %d us\" % sleeptime)\n time.sleep(sleeptime/1000000.0)\n"
  30. kind: ConfigMap
  31. metadata:
  32. annotations: {}
  33. labels:
  34. app: power-monitor
  35. name: logger.py
  36. namespace: power-monitoring