#!/usr/bin/python3

# https://shelly-api-docs.shelly.cloud/gen2/ComponentsAndServices/Shelly
# https://shelly-api-docs.shelly.cloud/gen2/ComponentsAndServices/HTTP
# https://requests.readthedocs.io/en/latest/user/quickstart/#json-response-content
#payload = { "id": 1, "user": "andy", "method": "Switch.GetConfig" }
#response = requests.get("http://192.168.1.190/rpc/", auth=(USER, PWD), params=payload)

import requests
import requests.auth
import pprint
import hashlib
import json
import sys
import re
import time

pp = pprint.PrettyPrinter()

user = "admin"
pwd = "Easypost12"
chargerIP = "192.168.1.190"
monitorIP = "192.168.1.192"

chargerSession = requests.Session()
chargerSession.auth = requests.auth.HTTPDigestAuth("admin", "Easypost12")

# Make request
response = chargerSession.get("http://192.168.1.178/rpc/Shelly.GetStatus")
print("\n#### GetStatus CAR CHARGER ##### ", response)
print(response.url)
print(response.headers)
print(response.text)


response = chargerSession.get("http://192.168.1.178/rpc/Shelly.GetConfig")
print("\n#### GetStatus CAR CHARGER ##### ", response)
print(response.url)
print(response.headers)
print(response.text)
print("\n\n")
pp.pprint(response.text)

sys.exit(0)

response = chargerSession.get("http://192.168.1.190/rpc/Switch.GetStatus?id=0")
print("\n#### GetStatus CAR CHARGER ##### ", response)
print(response.url)
print(response.headers)
print(response.text)


#response = chargerSession.get("http://192.168.1.190/rpc/Switch.Set?id=0&on=true")
#print("\n#### GetStatus CAR CHARGER ##### ", response)
#print(response.url)
#print(response.headers)
#print(response.text)

response = chargerSession.get("http://192.168.1.190/rpc/Switch.GetStatus?id=0")
print("\n#### GetStatus CAR CHARGER ##### ", response)
print(response.url)
print(response.headers)
print(response.text)


monitorSession = requests.Session()
#monitorSession.auth = requests.auth.HTTPDigestAuth("admin", "Easypost12")
monitorSession.auth = requests.auth.HTTPBasicAuth("admin", "Easypost12")

response = monitorSession.get("http://192.168.1.192/shelly")
print("\n#### /shelly MONITOR ##### ", response)
print(response.url)
print(response.headers)
print(response.text)

response = monitorSession.get("http://192.168.1.192/status")
print("\n#### /status MONITOR ##### ", response)
print(response.url)
print(response.headers)
print(response.text)

response = monitorSession.get("http://192.168.1.192/relay/0")
print("\n#### /relay/0 MONITOR ##### ", response)
print(response.url)
print(response.headers)
print(response.text)

response = monitorSession.get("http://192.168.1.192/emeter/0")
print("\n#### /emeter/0 MONITOR ##### ", response)
print(response.url)
print(response.headers)
print(response.text)

response = monitorSession.get("http://192.168.1.192/emeter/1")
print("\n#### /emeter/1 MONITOR ##### ", response)
print(response.url)
print(response.headers)
print(response.text)

pwrUrl = "http://" + monitorIP + "/emeter/0"
print("####################################################")
endTime = time.time() + 60
while time.time() < endTime:
	response = monitorSession.get(pwrUrl)
	jsonResp = response.json()
	print("Power: " + str(jsonResp['power']))
	time.sleep(1)



monitorSession.close()
chargerSession.close()

sys.exit()

# Get the response and work out details needed for auth
header=response.headers
wwwAuth = "{" + header['WWW-Authenticate'] + "}"
wwwAuthList = re.split(',| ', wwwAuth)
print("wwwAuthList\n", wwwAuthList)
wwwAuthDict = {}
for keyVal in wwwAuthList:
	kv = keyVal.split('=')
	if(len(kv)) < 2:
		continue
	wwwAuthDict[kv[0]] = kv[1]
	print("Added: " + kv[0])
print(wwwAuthDict)

hString = user + ":" + wwwAuthDict['realm'] + ":" + pwd
hStringB = bytes(hString, 'utf=8')
hash = hashlib.sha256(hStringB)
print(hash.hexdigest())
secResponse = hash.hexdigest()

#auth = {'realm': wwwAuthDict['realm'], 'username': user, 'nonce': wwwAuthDict['nonce'], 'cnonce': 123435, 'response': secResponse, 'alogrithm': wwwAuthDict['algorithm']}
authStr = "realm=" + wwwAuthDict['realm'].replace('"', '')  + "&username=" + user + "&nonce=" + wwwAuthDict['nonce'].replace('"', '') + "&cnonce=" + "123456" + "&response=" + secResponse + "&algorithm=SHA-256"
print(authStr)

response = chargerSession.get("http://192.168.1.190/rpc/Shelly.GetStatus?" + authStr)
print("\n#### GetStatus CAR CHARGER ##### ", response)
print(response.url)
print(response.headers)

sys.exit()

# {'Server': 'Mongoose/6.18', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*', 'Content-Length': '0', 'Connection': 'close', 'WWW-Authenticate': 'Digest qop="auth", realm="shellyplus1pm-4855199bd67c", nonce="644fa798", algorithm=SHA-256'}


# curl -X POST -d '{"id":1, "method":"Shelly.DetectLocation", "auth":
# {"realm": "shellypro4pm-f008d1d8b8b8", "username": "admin", "nonce": 1625038762,
# "cnonce": 313273957, "response": "eab75cbbd7acdb7082164cb52148cfbe351f28bf80856f93a23387c6157dbb69",
# "algorithm": "SHA-256"}}' \
# http://${SHELLY}/rpc

sys.exit()

response = requests.get("http://192.168.1.192/rpc/Shelly.GetStatus?id=0&auth={response=f8b34bed5db9e0d5f8bce34e898b54322d570f99920c3e49cfbb2f6ffeb932f5}")
print("\n#### GetStatus CAR CHARGER ##### ", response)
print(response.url)
print(response.headers)
pp.pprint(response.json())


response = requests.get("http://192.168.1.190/rpc/Switch.GetConfig?id=0", auth)
print("\n#### GetConfig(0) CAR CHARGER ##### ", response)
pp.pprint(response.json())

response = requests.get("http://192.168.1.190/Shelly.GetDeviceInfo/", auth=(user, pwd))
print("\n#### GetDeviceInfo CAR CHARGER ##### ", response)
pp.pprint(response.json())

#response = requests.get("http://192.168.1.190/Shelly.GetConfig", auth=(user, pwd))
#print("\n#### GetConfig CAR CHARGER ##### ", response)
#pp.pprint(response.json())

#response = requests.get("http://192.168.1.190/Shelly.ListMethods", auth=(user, pwd))
#print("\n#### ListMethods CAR CHARGER ##### ", response)
#pp.pprint(response.json())

