[python] Draft of web backend

This commit is contained in:
giuliof 2019-08-07 16:04:41 +02:00
parent f9eea54045
commit 14f962915a
4 changed files with 102 additions and 0 deletions

1
web/conf/.htaccess Normal file
View File

@ -0,0 +1 @@
Deny from all

4
web/conf/conf.custom.ini Normal file
View File

@ -0,0 +1,4 @@
[clima]
mode =
temperature =
fan =

4
web/conf/conf.ini Normal file
View File

@ -0,0 +1,4 @@
[clima]
mode =
temperature =
fan =

93
web/main.py Executable file
View File

@ -0,0 +1,93 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import xml.etree.ElementTree as ET
import sys
import cgitb, cgi
import datetime as dt
import locale
import json
import configparser
# Read configuration files (latest files in list override previous settings)
cfg = configparser.ConfigParser()
#locale.setlocale(locale.LC_TIME, 'it_IT')
remoteOpts = ('mode', 'temperature', 'fan')
# Start CGI handling for webserver
cgitb.enable()
inputvars = cgi.FieldStorage()
# Default format is json, keep HTML for light debug
#if 'format' in inputvars and inputvars['format'].value == 'html':
# format = 'html'
# print('Content-Type: text/html; charset=utf-8')
#else:
format = 'json'
print('Content-Type: text/json; charset=utf-8')
print()
### End of HTTP headers: it is now safe to output things
##########################################################
def error(msg):
print(json.dumps({'ret' : msg}, indent=4))
exit(-1)
def getClimaOpts():
cfg.read(['conf/conf.ini', 'conf/conf.custom.ini'])
if 'clima' in cfg:
return dict(cfg['clima'].items())
else:
return {'ret': 'err'}
def setClimaOpts(opt):
cfg['clima'] = opt
with open('conf/conf.custom.ini', 'w') as configfile:
cfg.write(configfile)
if 'cmd' in inputvars:
cmd = inputvars['cmd'].value
# Send a command to clima through DG interface
if cmd == 'setClima':
if not (set(remoteOpts).issubset(inputvars)):
error('Invalid cmd options')
else:
# parse and send
opt = { key:inputvars[key].value for key in inputvars if key in remoteOpts }
# Call DG and send this
print(json.dumps({'ret' : 'OK'}, indent=4))
# Get default clima options from cfg file
elif cmd == 'getClima':
# Parse cfg file and return json
opt = getClimaOpts()
print(json.dumps(opt, indent=4))
# Edit cfg file with new clima options
elif cmd == 'putClima':
if not (set(remoteOpts).issubset(inputvars)):
error('Invalid cmd options')
else:
# parse and send
opt = { key:inputvars[key].value for key in inputvars if key in remoteOpts }
# Edit cfg file
setClimaOpts(opt)
print(json.dumps({'ret' : 'OK'}, indent=4))
# Get ambient informations (i.e. temperature)
elif cmd == 'getAmbient':
print(json.dumps({'ret' : 'OK'}, indent=4))
else:
error('Invalid cmd code %s' % cmd)
else:
error('Invalid cmd')