Skip to content

Commit

Permalink
Lots lot changes
Browse files Browse the repository at this point in the history
  • Loading branch information
Manuel83 committed Jul 16, 2016
1 parent f61974e commit ee321c8
Show file tree
Hide file tree
Showing 306 changed files with 86,898 additions and 36,539 deletions.
2 changes: 1 addition & 1 deletion .bowerrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"directory": "brewapp/static/addon/"
"directory": "static/addon/"
}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,5 @@ target/

#sqllitefiles
*.db

.idea/*
43 changes: 39 additions & 4 deletions brewapp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flask import Flask, abort, redirect, url_for, render_template
from flask import Flask, abort, redirect, url_for, render_template, request, Response
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.socketio import SocketIO, emit
from thread import start_new_thread
Expand All @@ -7,7 +7,9 @@
from logging.handlers import RotatingFileHandler
import time
import os

import inspect
from functools import wraps


app = Flask(__name__)
Expand Down Expand Up @@ -41,16 +43,22 @@
app.brewapp_switch_state = {}
app.brewapp_hardware_config = {}
app.brewapp_config = {}
app.brewapp_thermometer_cfg = {}
app.brewapp_thermometer_log = {}
app.brewapp_thermometer_last = {}


## Create Database
db = SQLAlchemy(app)


manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)


## Import modules (Flask Blueprints)
from .base.views import base
from .module1.views import mymodule
#from .module1.views import mymodule
from .ui.views import ui

if os.path.exists("craftbeerpi.db"):
app.createdb = False
Expand All @@ -62,11 +70,37 @@

## Register modules (Flask Blueprints)
app.register_blueprint(base,url_prefix='/base')
app.register_blueprint(mymodule,url_prefix='/mymodule')
#app.register_blueprint(mymodule,url_prefix='/mymodule')
app.register_blueprint(ui,url_prefix='/ui')



@app.route('/login', methods=['GET', 'POST'])
def login():
if flask.request.method == 'GET':
return '''
<form action='login' method='POST'>
<input type='text' name='email' id='email' placeholder='email'></input>
<input type='password' name='pw' id='pw' placeholder='password'></input>
<input type='submit' name='submit'></input>
</form>
'''

email = flask.request.form['email']
if flask.request.form['pw'] == users[email]['pw']:
user = User()
user.id = email
flask_login.login_user(user)
return flask.redirect(flask.url_for('protected'))

return 'Bad login'




@app.route('/')
def index():
return redirect('base')
return redirect('ui')

## Invoke Initializers
app.logger.info("## INITIALIZE DATA")
Expand All @@ -77,6 +111,7 @@ def index():
param = app.brewapp_config.get(i.get("config_parameter"), False)
if(param == 'False'):
continue
print "INIT : %s" % (i.get("function").__name__)
app.logger.info("--> Method: " + i.get("function").__name__ + "() File: "+ inspect.getfile(i.get("function")))
i.get("function")()

Expand Down
2 changes: 2 additions & 0 deletions brewapp/base/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@
import setup
import stats
import system
import thermo
import securtiy
6 changes: 5 additions & 1 deletion brewapp/base/automatic/automaticlogic.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ def isRunning(self):
return app.brewapp_kettle_automatic[key]

def getCurrentTemp(self):
return app.brewapp_kettle_state[self.kid]["temp"]
try:
id = int(app.brewapp_kettle_state[self.kid]["sensorid"])
return app.brewapp_thermometer_last[id]
except:
return None

def getTargetTemp(self):
return app.brewapp_kettle_state[self.kid]["target_temp"]
Expand Down
12 changes: 6 additions & 6 deletions brewapp/base/automatic/examplelogic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@
import time
from brewapp.base.util import *


@brewautomatic()
class CustomLogic(Automatic):

## Define config paramter as array of dicts
configparameter = [{"name":"PumpGPIO","value":17}]
# Define config paramter as array of dicts
configparameter = [{"name" : "PumpGPIO" , "value" : 17}]

def run(self):
## loop for automatic
# loop for automatic
while self.isRunning():
## access config paramter at runtime
# access config paramter at runtime
print self.config


## make sure to add a sleep to the while loop
# make sure to add a sleep to the while loop
time.sleep(1)
19 changes: 10 additions & 9 deletions brewapp/base/automatic/fermentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,28 @@
import time
from brewapp.base.util import *


@brewautomatic()
class SimpleFermentationLogic(Automatic):

## Define config paramter as array of dicts
configparameter = [{"name":"overshoot","value":2}]
# Define config paramter as array of dicts
configparameter = [{"name": "overshoot", "value" : 2}]

state = False

def run(self):
while self.isRunning():
currentTemp = self.getCurrentTemp() ## Current temperature
targetTemp = self.getTargetTemp() ## Target Temperature
## Current Temp is below Target Temp ... switch heater on
if(currentTemp > targetTemp and self.state == False):
currentTemp = self.getCurrentTemp() # Current temperature
targetTemp = self.getTargetTemp() # Target Temperature
# Current Temp is below Target Temp ... switch heater on
if currentTemp > targetTemp and self.state is False:
self.state = True
self.switchHeaterON()
## Current Temp is equal or higher than Target Temp ... switch Heater off
if(currentTemp <= targetTemp and self.state == True):
# Current Temp is equal or higher than Target Temp ... switch Heater off
if currentTemp <= targetTemp and self.state is True:
self.state = False
self.switchHeaterOFF()
time.sleep(1)

self.switchHeaterOFF()
app.logger.info("Stop Automatic - Kettle Id: "+ str(self.kid))
app.logger.info("Stop Automatic - Kettle Id: " + str(self.kid))
8 changes: 8 additions & 0 deletions brewapp/base/automatic/overshoot.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,23 @@ class OvershootLogic(Automatic):

def run(self):


try:
overshoot = float(self.config["Overshoot"])
except Exception as e:
app.logger.error("Wrong overshoot parameter! Set overshoot parameter to 0")
overshoot = 0

while self.isRunning():

currentTemp = self.getCurrentTemp() ## Current temperature
targetTemp = self.getTargetTemp() ## Target Temperature

if(currentTemp == None):
time.sleep(1)
return


## Current Temp is below Target Temp ... switch heater on
if(currentTemp + overshoot < targetTemp and self.state == False):
self.state = True
Expand Down
30 changes: 19 additions & 11 deletions brewapp/base/config.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,37 @@
from flask import Blueprint, render_template, jsonify, request
from util import *
from model import *
import time
from brewapp import app, socketio
from views import base
from brewapp import manager
from brewapp import app, socketio, manager

import json

def pre_post(data, **kw):
if(data["type"] == "json"):

if data["type"] is "json":
data["value"] = json.dumps(data["value"])


def post_post(result, **kw):
if(result["type"] == "json"):
if result["type"] is "json":
result["value"] = json.loads(result["value"])
readConfig()
socketio.emit('config', app.brewapp_config, namespace='/brew')


def post_get_many(result, **kw):
for o in result["objects"]:
if(o["type"] == "json"):
if o["type"] is "json":
o["value"] = json.loads(o["value"])

result["objects"] = sorted(result["objects"], key=lambda k: k['name'])


def readConfig():
app.brewapp_config = {}
config = Config.query.all()
for c in config:
app.brewapp_config[c.name] = c.value


@brewinit(order=-1000)
def init():
manager.create_api(Config, methods=['GET', 'POST', 'DELETE', 'PUT'],
Expand All @@ -47,20 +51,24 @@ def init():
@brewinit(order=-1001)
def initDriver():
if(app.createdb is False):
return
return



db.session.add(Config(name="BUZZER_GPIO", value="23", type="", default="23", description="Buzzer GPIO"))
db.session.add(Config(name="BREWNAME", value="", type="", default="", description="Brew Name"))
db.session.add(Config(name="UNIT", value="C", type="", default="C", description="Thermometer unit", options="C,F"))
db.session.add(Config(name="THERMOMETER_TYPE", value="1WIRE", type="", default="1WIRE", description="Thermometer Type !!RESTART AFTER CHANGE OF THIS PARAMETER!!!", options="1WIRE,USB,DUMMY"))
db.session.add(Config(name="SWITCH_TYPE", value="GPIO", type="", default="GPIO", description="Hardware Control type. !!!RESTART AFTER CHANGE OF THIS PARAMETER!!!", options="GPIO,PIFACE,GEMBIRD,DUMMY"))
#db.session.add(Config(name="SETUP", value="1", type="", default="1", description="Hardware Control type. !!!RESTART AFTER CHANGE OF THIS PARAMETER!!!", options="0,1"))
db.session.add(Config(name="SEND_STATS", value="True", type="", default="True", description="Sending statistic informaiton to CraftBeerPI. This helps to improve CraftBeerPI in the future", options="True,False"))
db.session.add(Config(name="USE_LCD", value="False", type="", default="False", description="Activate LCD display control", options="True,False"))
db.session.add(Config(name="BREWERY_NAME", value="", type="", default="", description="Name of your Berwery"))

db.session.add(Config(name="USERNAME", value="admin", type="", default="admin", description="Login User"))
db.session.add(Config(name="PASSWORD", value="123", type="", default="123", description="Login Password"))
db.session.add(Config(name="THEME", value="static/themes/dark-theme.css", type="", default="static/themes/dark-theme.css", description="UI Theme", options="static/themes/dark-theme.css,static/themes/blue-theme.css,"))
db.session.commit()


@brewinit()
def initDriver():
app.logger.info("INIT Driver")
Expand Down
37 changes: 28 additions & 9 deletions brewapp/base/hardwareswitch.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
from flask import Blueprint, render_template, jsonify, request
from util import *
from model import *
from brewapp import app, socketio
from views import base
from brewapp import manager
from flask.ext.restless.helpers import to_dict
import json


@app.route('/api/hardware/devices', methods=['GET'])
def getHardwareDevices():
return json.dumps(app.brewapp_hardware.getDevices())

@app.route('/api/hardware/state', methods=['GET'])
def pumpstate():
Expand Down Expand Up @@ -50,20 +54,27 @@ def init():
})
initHardware(False)



def initHardware(cleanup = True):

app.brewapp_switch_state = {}
app.brewapp_hardware_config = {}
app.brewapp_thermometer_cfg = {}
hw = Hardware.query.all()

for h in hw:
h1 = to_dict(h)
if(h1['config'] != None):
h1['config'] = json.loads(h1['config'])
app.brewapp_hardware_config[h1['switch']] = h1
if(h.switch != None):
app.brewapp_switch_state[h.switch] = False

if(h1["type"] == "T"):
app.brewapp_thermometer_cfg[h1["id"]] = h1
elif (h1["type"] == "F"):
pass
else:
app.brewapp_hardware_config[h1["id"]] = h1
app.brewapp_switch_state[h1["id"]] = False

if(cleanup):
app.brewapp_hardware.cleanup()
Expand All @@ -76,16 +87,24 @@ def switchstate():

@socketio.on('switch', namespace='/brew')
def ws_switch(data):
s = data["switch"]
s = int(data["switch"])

if(app.brewapp_switch_state.get(s, None) == None):
return

if(app.brewapp_hardware_config[s]["config"].get("switch", None) is None):
socketio.emit('message', {"headline": "HARDWARE_ERROR", "message": "PLEASE_CHECK_YOUR_HARDWARE_CONFIG"},
namespace='/brew')
return

if(app.brewapp_switch_state[s] == True):
app.logger.info("Switch off: " + str(s))
app.brewapp_hardware.switchOFF(s);
app.brewapp_hardware.switchOFF(app.brewapp_hardware_config[s]["config"]["switch"]);
app.brewapp_switch_state[s] = False
else:
app.logger.info("Switch on: " + str(s))
app.brewapp_hardware.switchON(s);
app.brewapp_hardware.switchON(app.brewapp_hardware_config[s]["config"]["switch"]);
app.brewapp_switch_state[s] = True

socketio.emit('switch_state_update', app.brewapp_switch_state, namespace ='/brew')


Expand Down
Loading

0 comments on commit ee321c8

Please sign in to comment.