SHARE
TWEET

new2.py

a guest Mar 20th, 2017 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Version: 1
  2. # Author: Joachim Olsson
  3. # Email: joachim.olsson@gcf-consulting.com
  4. # Date: 2016-10-05
  5. #
  6. # This file detects hardware pulses from energy meter and logs them
  7. # The default input pin is GPIO24 on raspberry pi
  8. # Each tick on this pin is worth 10 Wh
  9. # This is stored in memory, and written to file by default once every minute
  10.  
  11. import RPi.GPIO as GPIO
  12. import datetime
  13. import time
  14. import os
  15. import sys
  16. import linecache
  17. import requests
  18. import json
  19. import threading
  20. from random import randint
  21.  
  22. def RunScript(script):
  23.     os.system('sudo python ' + script)
  24.  
  25. def LogException(Info):
  26.     print 'Enter LogException()'
  27.     f = None
  28.     try:
  29.         LoggingLock.acquire()
  30.         f = open(os.getcwd() + LogFile, "a+")
  31.         dateTime = datetime.datetime.utcnow()
  32.         data = f.read()
  33.         f.seek(0)
  34.         f.truncate()
  35.         jsonData = json.loads(data)
  36.         jsonData['ExceptionEntries'].append({'Time': dateTime.isoformat(), 'ExceptionInfo': Info})
  37.         f.write(json.dumps(jsonData))
  38.     except ValueError as ex:
  39.         #Error in data, input valid sequence in file
  40.         print 'Decoding JSON failed! Document:'
  41.         print data
  42.         jsonData = {
  43.                 'LogEntries': [],
  44.                 'DeviceEntries': [],
  45.                 'ExceptionEntries': [{'Time': dateTime.isoformat(), 'ExceptionInfo': Info}]
  46.         }
  47.        
  48.         f.write(json.dumps(jsonData))
  49.         print '\nJSON Data Restored!'
  50.     except Exception as ex:
  51.         f.close()
  52.         LoggingLock.release()
  53.         LogExceptionInfo()
  54.         LoggingLock.acquire()
  55.         f = open(os.getcwd() + LogFile, "a+")
  56.         LogExceptionInfo()
  57.     finally:
  58.         if(f and not f.closed):
  59.             f.close()
  60.         LoggingLock.release()
  61.     print 'Exit LogException()'
  62.  
  63. def LogExceptionInfo():
  64.     print 'Enter LogExceptionInfo()'
  65.     try:            
  66.         exc_type, exc_obj, tb = sys.exc_info()
  67.         f = tb.tb_frame
  68.         lineno = tb.tb_lineno
  69.         filename = f.f_code.co_filename
  70.         linecache.checkcache(filename)
  71.         line = linecache.getline(filename, lineno, f.f_globals)
  72.         dateTime = datetime.datetime.utcnow()
  73.         text = '[{}] EXCEPTION OCCURRED IN ({}, LINE {} "{}"): {}'.format(dateTime, filename, lineno, line.strip(), exc_obj)
  74.         print text
  75.         LogException(text)
  76.     except ValueError as ex:
  77.         LogExceptionInfo()
  78.     except Exception as ex:
  79.         LogExceptionInfo()
  80.     print 'Exit LogExceptionInfo()'
  81.  
  82. def GetAuthorizationToken():
  83.     print 'Enter GetAuthorizationToken()'
  84.     try:
  85.         print "Lock - Token"
  86.         AuthorizationLock.acquire()
  87.         global AuthorizationType, AuthorizationCredentials, AuthorizationExpires, Authorized
  88.         data = {
  89.             'username': LoginAccountUsername,
  90.             'password': LoginAccountPassword,
  91.             'grant_type': 'password'
  92.         }
  93.         response = requests.post(BaseAuth, data = data)
  94.         data = response.json()
  95.        
  96.         if(response.status_code == 200):
  97.             AuthorizationExpires = datetime.datetime.utcnow() + datetime.timedelta(seconds=data['expires_in']) - datetime.timedelta(hours=1)
  98.             AuthorizationCredentials = data['access_token']
  99.             AuthorizationType = "Bearer "
  100.             Authorized = True
  101.             print "Authorization Expires at: " + str(AuthorizationExpires)
  102.             print "Authorization Type: " + str(AuthorizationType)
  103.             print "Authorization Credentials: " + str(AuthorizationCredentials)
  104.         else:
  105.             Authorized = False
  106.             LogAction("LOGIN FAIL")
  107.     except:
  108.         LogExceptionInfo()
  109.     finally:
  110.         print "Release - Token"
  111.         AuthorizationLock.release()
  112.     print 'Exit GetAuthorizationToken()'
  113.  
  114. def GetUpdates():
  115.     f = None
  116.     try:
  117.         AuthorizationLock.acquire()
  118.         headers = { "Authorization" : AuthorizationType + AuthorizationCredentials, "Accept": "text/*", "Accept-Encoding": "gzip;q=1.0, deflate;q=0.8, *;q=0" }
  119.         response = requests.get(BaseAPI + "/Logging/GetUpdater", headers = headers)
  120.         print str(response.content)
  121.         f = open(os.getcwd() + UpdaterFile, "a+")
  122.         f.seek(0)
  123.         f.truncate()
  124.         f.write(unicode(response.content, "UTF-8"))
  125.     except:
  126.         LogExceptionInfo()
  127.     finally:
  128.         AuthorizationLock.release()
  129.         if(f and not f.closed):
  130.             f.close()
  131.     try:
  132.         RunScript(os.getcwd() + UpdaterFile)
  133.         os._exit(1)
  134.     except:
  135.         LogExceptionInfo()      
  136.        
  137.    
  138. def GetConfig():
  139.     print 'Enter GetConfig()'
  140.     global Authorized, HardwareLogInterval, PostInterval
  141.     LatestBuild = CurrentBuild
  142.     try:
  143.         AuthorizationLock.acquire()
  144.         authorized = Authorized
  145.     except:
  146.         LogExceptionInfo()
  147.     finally:
  148.         AuthorizationLock.release()
  149.     try:
  150.         if(not authorized):
  151.             GetAuthorizationToken()
  152.     except:
  153.         LogExceptionInfo()
  154.        
  155.     try:
  156.         AuthorizationLock.acquire()
  157.         headers = { "Authorization" : AuthorizationType + AuthorizationCredentials, "Accept": "application/json", "Accept-Encoding": "gzip;q=1.0, deflate;q=0.8, *;q=0" }
  158.         response = requests.get(BaseAPI + "/Logging/GetConfig", headers = headers)
  159.         data = response.json()
  160.         if(response.status_code == 200):
  161.             try:
  162.                 ConfigLock.acquire()
  163.                 Status = data['Status']
  164.                 HardwareLogInterval = datetime.timedelta(seconds=data['LogInterval'])
  165.                 PostInterval = datetime.timedelta(seconds=data['PostInterval'])
  166.                 NextLogTime = datetime.datetime.utcnow() + HardwareLogInterval
  167.                 NextPostTime = datetime.datetime.utcnow() + PostInterval
  168.                 LatestBuild = data['LatestBuild']
  169.                 '''print "Retrieved config"
  170.                 print "Status: " + str(Status)
  171.                 print "LogInterval: " + str(HardwareLogInterval)
  172.                 print "PostInterval: " + str(PostInterval)'''
  173.                 LogAction("GET CONFIG")
  174.             except:
  175.                 LogExceptionInfo()
  176.             finally:
  177.                 ConfigLock.release()
  178.         else:
  179.             authorized = False
  180.             LogAction("GET CONFIG FAIL")      
  181.     except:
  182.         LogExceptionInfo()
  183.     finally:
  184.         AuthorizationLock.release()        
  185.    
  186.     try:
  187.         if(not authorized):
  188.             GetAuthorizationToken()
  189.     except:
  190.         LogExceptionInfo()
  191.  
  192.     if(LatestBuild != CurrentBuild):
  193.         GetUpdates()
  194.        
  195.     print 'Exit GetConfig()'
  196.        
  197. def GetCPUSerial():
  198.     print 'Enter GetCPUSerial()'
  199.     cpuSerial = '0000000000000000'
  200.     try:
  201.         f = open('/proc/cpuinfo','r') #RPi Serial location
  202.         for line in f:
  203.             if line[0:6]=='Serial':
  204.                 cpuSerial = line[10:26]
  205.         return int(str(cpuSerial), 16)
  206.     except Exception as ex:
  207.         LogExceptionInfo()
  208.     finally:
  209.         f.close()
  210.     print 'Exit GetCPUSerial()'
  211.  
  212. def StartHardwareLogger():
  213.     print 'Enter StartHardwareLogger()'
  214.     try:
  215.         print "StartHardwareLogger"
  216.         GPIO.setwarnings(False)
  217.         GPIO.setmode(GPIO.BCM)
  218.         GPIO.setup(HardwarePin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
  219.         GPIO.add_event_detect(HardwarePin, GPIO.RISING, callback=HardwareLoggerCallback, bouncetime=BounceIntervalMs)
  220.     except:
  221.         LogExceptionInfo()
  222.     print 'Exit StartHardwareLogger()'
  223.  
  224. def HardwareLoggerCallback(ch):
  225.     print 'Enter HardwareLoggerCallback(ch)'
  226.     try:
  227.         global CurrentEnergyLevel,CountEnergyTicks,DateTime,NextLogTime
  228.         print "HardwareLoggerCallback"
  229.         CurrentEnergyLevel += 10
  230.         CountEnergyTicks += 1
  231.         DateTime = datetime.datetime.utcnow()
  232.         if(DateTime >= NextLogTime and CurrentEnergyLevel > 0):
  233.             NextLogTime = DateTime + HardwareLogInterval
  234.             LogEntry(CurrentEnergyLevel)
  235.             CurrentEnergyLevel = 0
  236.         '''if (CountEnergyTicks >= 3):
  237.             print "HardwareLoggerCallback 3"
  238.             GPIO.remove_event_detect(HardwarePin)
  239.             GPIO.cleanup()
  240.             StartHardwareLogger()'''
  241.     except:
  242.         #GPIO.cleanup()
  243.         LogExceptionInfo()
  244.         #StartHardwareLogger()
  245.     print 'Exit HardwareLoggerCallback(ch)'
  246.  
  247. def LogEntry(EnergyLevel):
  248.     print 'Enter LogEntry(EnergyLevel)'
  249.     f = None
  250.     try:
  251.         LoggingLock.acquire()
  252.         f = open(os.getcwd() + LogFile, "a+")
  253.         dateTime = datetime.datetime.utcnow()
  254.         data = f.read()
  255.         f.seek(0)
  256.         f.truncate()
  257.         jsonData = json.loads(data)
  258.         jsonData['LogEntries'].append({
  259.                 'Time': dateTime.isoformat(),
  260.                 'EnergyAmount': EnergyLevel,
  261.                 })
  262.         f.write(json.dumps(jsonData))
  263.     except ValueError as ex:
  264.         print ex
  265.         #Error in data, input valid sequence in file
  266.         print 'Decoding JSON failed!\nDocument:\n'
  267.         print data
  268.         jsonData = {
  269.                 'LogEntries': [{
  270.                         'Time': dateTime.isoformat(),
  271.                         'EnergyAmount': EnergyLevel
  272.                         }],
  273.                 'DeviceEntries': [],
  274.                 'ExceptionEntries': []
  275.         }
  276.         f.write(json.dumps(jsonData))
  277.         print 'JSON Data Restored!'
  278.     except Exception as ex:
  279.         if(f and not f.closed):
  280.             f.close()
  281.         LoggingLock.release()
  282.         LogExceptionInfo()
  283.         LoggingLock.acquire()
  284.         f = open(os.getcwd() + LogFile, "a+")
  285.     finally:
  286.         if(f and not f.closed):
  287.             f.close()
  288.         LoggingLock.release()
  289.     print 'Exit LogEntry(EnergyLevel)'
  290.  
  291. def LogAction(Info):
  292.     print 'Enter LogAction(Info)'
  293.     f = None
  294.     try:
  295.         LoggingLock.acquire()
  296.         f = open(os.getcwd() + LogFile, "a+")
  297.         dateTime = datetime.datetime.utcnow()
  298.         data = f.read()
  299.         f.seek(0)
  300.         f.truncate()
  301.         jsonData = json.loads(data)
  302.         jsonData['DeviceEntries'].append({'Time': dateTime.isoformat(), 'Action': Info})
  303.         f.write(json.dumps(jsonData))
  304.     except ValueError as ex:
  305.         #Error in data, input valid sequence in file
  306.         print 'Decoding JSON failed! Document:'
  307.         print data
  308.         jsonData = {
  309.                 'LogEntries': [],
  310.                 'DeviceEntries': [{'Time': dateTime.isoformat(), 'Action': Info}],
  311.                 'ExceptionEntries': []
  312.         }
  313.         f.write(json.dumps(jsonData))
  314.         print 'JSON Data Restored!'
  315.     except Exception as ex:
  316.         if(f and not f.closed):
  317.             f.close()
  318.         LoggingLock.release()
  319.         LogExceptionInfo()
  320.         LoggingLock.acquire()
  321.         f = open(os.getcwd() + LogFile, "a+")
  322.         LogExceptionInfo()
  323.     finally:
  324.         if(f and not f.closed):
  325.             f.close()
  326.         LoggingLock.release()
  327.     print 'Exit LogAction(Info)'
  328.  
  329. def CheckPostLog():
  330.     print 'Enter CheckPostLog()'
  331.     global NextPostTime, PostInterval, HardwareLogInterval, NextLogTime, Status
  332.     f = None
  333.     LatestBuild = CurrentBuild
  334.     print "Time is " + str(datetime.datetime.utcnow().isoformat()) + " and next post will occur after " + str(NextPostTime.isoformat())
  335.     if(datetime.datetime.utcnow() >= NextPostTime):
  336.         try:
  337.             LoggingLock.acquire()
  338.             NextPostTime = datetime.datetime.utcnow() + PostInterval
  339.             f = open(os.getcwd() + LogFile, "a+")
  340.             jsonData = json.loads(f.read())
  341.             jsonData['Time'] = datetime.datetime.utcnow().isoformat()
  342.             headers = { "Authorization" : AuthorizationType + AuthorizationCredentials, "Accept": "application/json", "Content-Type": "application/json" }
  343.             response = requests.post(BaseAPI + "/Logging/Log", headers = headers, json=jsonData)
  344.             data = response.json()
  345.             if(response.status_code == 200):
  346.                 print "Posted Log - Current Log was cleared"
  347.                 f.seek(0)
  348.                 f.truncate()
  349.                 jsonData = {
  350.                         'LogEntries': [],
  351.                         'DeviceEntries': [],
  352.                         'ExceptionEntries': []
  353.                 }
  354.                 f.write(json.dumps(jsonData))
  355.                 try:
  356.                     ConfigLock.acquire()
  357.                     Status = data['Status']
  358.                     HardwareLogInterval = datetime.timedelta(seconds=data['LogInterval'])
  359.                     PostInterval = datetime.timedelta(seconds=data['PostInterval'])
  360.                     NextLogTime = datetime.datetime.utcnow() + HardwareLogInterval
  361.                     NextPostTime = datetime.datetime.utcnow() + PostInterval
  362.                     LatestBuild = data['LatestBuild']
  363.                 finally:
  364.                     ConfigLock.release()
  365.             else:
  366.                 print "Error Sending Log: "
  367.                 print data
  368.         except ValueError as ex:
  369.             if(f and not f.closed):
  370.                 f.seek(0)
  371.                 f.truncate()
  372.                 jsonData = {
  373.                     'LogEntries': [],
  374.                     'DeviceEntries': [],
  375.                     'ExceptionEntries': []
  376.                 }
  377.                 f.write(json.dumps(jsonData))
  378.         except:
  379.             if(f and not f.closed):
  380.                 f.close()
  381.             LoggingLock.release()
  382.             LogExceptionInfo()
  383.             LoggingLock.acquire()
  384.             f = open(os.getcwd() + LogFile, "a+")
  385.         finally:
  386.             if(f and not f.closed):
  387.                 f.close()
  388.             LoggingLock.release()
  389.  
  390.         try:
  391.             if(LatestBuild != CurrentBuild):
  392.                 GetUpdates()
  393.         except:
  394.             LogExceptionInfo()
  395.     print 'Exit CheckPostLog()'
  396.  
  397.  
  398.  
  399.  
  400. ########-----Global Variables-----########
  401. ConfigLock = threading.Lock()
  402.  
  403. Status = 0
  404. PostInterval = datetime.timedelta(seconds=3)
  405. HardwareLogInterval = datetime.timedelta(seconds=5) #How often to log to file
  406. DateTime = datetime.datetime.utcnow()
  407. NextLogTime = DateTime + HardwareLogInterval
  408. NextPostTime = DateTime + PostInterval
  409. BounceIntervalMs = 50 #Note, anything logged in this interval won't be counted
  410. HardwarePin = 24 #GPIO24
  411.  
  412.  
  413. AuthorizationLock = threading.Lock()
  414.  
  415. BaseAPI = "http://192.168.1.16:8080/API/"
  416. BaseAuth = "http://192.168.1.16:8080/oauth/token"
  417. AuthorizationType = ""
  418. AuthorizationCredentials = ""
  419. AuthorizationExpires = datetime.datetime.utcnow()
  420. Authorized = False
  421. LoginAccountUsername = "Device@AndrewPeters"
  422. LoginAccountPassword = "p4ssw0rd"
  423.  
  424.  
  425. LoggingLock = threading.Lock()
  426.  
  427. CurrentEnergyLevel = 0
  428. CountEnergyTicks = 0
  429. #CPUSerial = GetCPUSerial()
  430. LogFile = "/Log.json"
  431. UpdaterFile = "/Updater.py"
  432. CurrentBuild = 2
  433.  
  434. ########-----Main Program-----########
  435. print "\n==================="
  436. print "PowerCoins Logger - Running"
  437. print "\033[94mVersion 2.0\033[0m"
  438. print "===================\n"
  439.  
  440. while True:
  441.     try:
  442.  
  443.        
  444.         LogAction("BOOT")
  445.         StartHardwareLogger()
  446.         while(True):
  447.             GetAuthorizationToken()
  448.             if(Authorized):
  449.                 break
  450.             else:
  451.                 time.sleep(30)
  452.         GetConfig()
  453.         while True:
  454.             time.sleep(3)
  455.             if(randint(0,15) > 14):
  456.                 LogEntry(randint(30,120))
  457.             CheckPostLog()
  458.        
  459.     except Exception as e:
  460.         print e
  461.         LogAction("EXIT(AUTORESTART)")
  462.         GPIO.cleanup()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top