32 Commits

Author SHA1 Message Date
66442bf4de fixed a bug in rendering the correct picture, due to changes of multiple levels 2016-06-19 00:59:25 +02:00
78f052a664 - failed temp and humidity reading wont prevent data sending
- printing of water level
2016-06-12 12:03:19 +02:00
Senad Uka
8fc028aaab fixed duplicate controller folder 2016-06-11 18:56:47 +02:00
Senad Uka
cc7aebc6f9 Merge pull request #23 from senaduka/config_pumping_levels_and_draining_period
Config pumping levels and draining period
2016-06-10 10:01:39 +02:00
e5d4c820d6 set both start and stop pumping levels by default to full 2016-06-09 21:56:26 +02:00
cfd7d677dd deleted draining period and amount from config file as this does not work like i thought it would 2016-06-09 20:56:42 +02:00
4872f4a910 expanded the water levels to be used to configure pumping levels and moved the water draining period to config file 2016-06-09 20:07:38 +02:00
Senad Uka
5c1f1629e7 Update __init__.py
removing canceling shutdown
2016-06-08 18:50:32 +02:00
46af39c7af Update README.md
changed the crontab info in means of changing
*/15 * * * * /usr/bin/python /home/pi/projects/tfm/controller/sensors.py "Automatski, Senad Uka" 120
*/1 * * * * /usr/bin/python /home/pi/projects/tfm/controller/sync_state.py "Automatski, Senad Uka" 120
to 
*/5 * * * * cd /home/pi/projects/tfm/controller && sh activity.sh
2016-06-08 13:18:08 +02:00
bcb84e4400 Update copy__init__.py.example 2016-06-08 13:12:36 +02:00
79651cb6af Merge pull request #22 from senaduka/local_safe_autonomy
Local safe autonomy
2016-06-08 11:15:04 +02:00
Senad Uka
bffab2bf26 Merge pull request #17 from senaduka/shell_script_to_unify_activities
created activity.sh to unify all activities in a specific order
2016-06-08 11:14:33 +02:00
Senad Uka
718968f57d readme 2016-06-08 10:45:32 +02:00
Senad Uka
f1d7232c10 network check script 2016-06-08 10:34:05 +02:00
Senad Uka
fec689a5bc dweet fix again 2016-06-08 10:03:17 +02:00
Senad Uka
533135013b dweet fix again 2016-06-08 10:01:55 +02:00
Senad Uka
e0e0f0d24c dweet fix 2016-06-08 09:48:36 +02:00
Senad Uka
b30af162a1 reboot time 2016-06-08 09:38:54 +02:00
Senad Uka
c11e6b29b1 dweet exception 2016-06-08 09:31:51 +02:00
Senad Uka
d2a2fae936 dweet source code 2016-06-08 09:30:06 +02:00
Senad Uka
a12a218e85 reboot canceling 2016-06-08 09:28:42 +02:00
Senad Uka
f8a8284944 added dweet and reboot 2016-06-08 09:16:44 +02:00
Senad Uka
f9defb8e2a fixed syntax error 4 2016-06-08 08:39:31 +02:00
Senad Uka
5ae36641a2 fixed syntax error 3 2016-06-08 08:31:58 +02:00
Senad Uka
62f9cabb83 fixed syntax error 2 2016-06-08 08:31:42 +02:00
Senad Uka
91027c5330 fixed syntax error 2016-06-08 08:28:48 +02:00
Senad Uka
7d434625ca Local autonomy test 1 2016-06-08 08:24:43 +02:00
Senad Uka
61bb6d0d4b Merge pull request #21 from senaduka/multipleWaterLevelSensors
Multiple level sensors added
2016-06-05 11:14:25 +02:00
1ae13f6fb1 Multiple level sensors added 2016-06-02 23:13:42 +02:00
db843163f2 Merge pull request #20 from senaduka/last_fill_time
Disabled temperature graph
2016-05-17 16:12:53 +02:00
336b82be3f Merge pull request #19 from senaduka/last_fill_time
Added last valve open time
2016-05-08 06:06:31 +02:00
90e43b8bd2 created activity.sh to unify all activities in a specific order 2016-04-23 14:32:31 +00:00
18 changed files with 262 additions and 39 deletions

View File

@@ -1,3 +1,3 @@
<template name="sensorData">
<li>{{owner}} / <strong>{{temperatureValue}}°C</strong> / <strong>{{humidityValue}}%</strong> / Bačva puna: <strong>{{tankFull}}</strong> / {{created_at_formatted}}</li>
<li>{{owner}} / <strong>{{temperatureValue}}°C</strong> / <strong>{{humidityValue}}%</strong> / Bačva puna: <strong>{{tankFull}}</strong> (L0:{{tankLevel0}}-L1:{{tankLevel1}}-L2:{{tankLevel2}}-L3:{{tankLevel3}}-L4:{{tankLevel4}}-full:{{tankFull}}) / {{created_at_formatted}}</li>
</template>

View File

@@ -5,7 +5,7 @@
<img src="{{ bucket_image }}" class="img-responsive center-block" id="bucket_image" />
<div class="text-center">
{{controller_id}}:
{{#with last_sensor_reading}} <strong> {{ temperatureValue }} °C, {{ humidityValue }} % </strong> {{/with}}
{{#with last_sensor_reading}} <strong> temp: {{ temperatureValue }} °C, vlaga: {{ humidityValue }} % <br/>nivo vode: {{water_level}} </strong> {{/with}}
</div>
<div class="text-center">
Automatsko zalijevanje:<br /> <strong>{{ pretty_days config.automaticDaysOfWeek }} {{ pretty_time config.automaticDaysOfWeek config.automaticTimeOfDay }}</strong> <button id="run_settings" class="btn btn-default"> <i class="fa fa-wrench"></i> </button>

View File

@@ -61,6 +61,18 @@ Template.state.helpers({
last_sensor_reading: last_sensor_reading,
water_level: function() {
var sensor = last_sensor_reading();
if (sensor) {
if (parseInt(sensor.tankFull) === 1) return '100 %';
else if (parseInt(sensor.tankLevel4) === 1) return '80 %';
else if (parseInt(sensor.tankLevel3) === 1) return '60 %';
else if (parseInt(sensor.tankLevel2) === 1) return '40 %';
else if (parseInt(sensor.tankLevel1) === 1) return '20 %';
else '0 %'
}
},
water_now_button_class: function() {
var stateObject = controller_state();
if (stateObject.state && (stateObject.state.out_valve === 'open' || stateObject.state.out_valve === 'opening')) {

View File

@@ -13,7 +13,14 @@ Api.addRoute('sensorData', {
SensorData.insert({
temperatureValue: parseFloat(this.bodyParams.temperatureValue),
humidityValue: parseFloat(this.bodyParams.humidityValue),
tankLevel0: this.bodyParams.tankLevel0,
tankLevel1: this.bodyParams.tankLevel1,
tankLevel2: this.bodyParams.tankLevel2,
tankLevel3: this.bodyParams.tankLevel3,
tankLevel4: this.bodyParams.tankLevel4,
tankFull: this.bodyParams.tankFull,
startPumpingAt: this.bodyParams.startPumpingAt,
stopPumpingAt: this.bodyParams.stopPumpingAt,
owner: this.bodyParams.owner,
controllerId: this.bodyParams.controllerId,
created_at: new Date()
@@ -24,12 +31,19 @@ Api.addRoute('sensorData', {
function reactToSensorData(nextSensorReading) {
console.log("reacting to sensor");
var controllerId = nextSensorReading.controllerId;
var state = stateOrDefault(controllerId).state;
console.log(nextSensorReading , state);
var shouldStartPumping = (!state.in_valve || state.in_valve === 'closed' || state.in_valve === 'closing') && ((parseInt(nextSensorReading.tankFull) === 0) && (state.out_valve === 'closed' || state.out_valve === 'closing'));
var shouldStopPumping = (state.in_valve === 'open' || state.in_valve === 'opening') && (parseInt(nextSensorReading.tankFull) === 1 || state.out_valve === 'open' || state.out_valve === 'opening');
var startPumpingLevelReached;
if (nextSensorReading.startPumpingAt == 'TANKLEVEL0') startPumpingLevelReached = (parseInt(nextSensorReading.tankLevel0) === 0)
else if (nextSensorReading.startPumpingAt == 'TANKLEVEL1') startPumpingLevelReached = (parseInt(nextSensorReading.tankLevel1) === 0)
else if (nextSensorReading.startPumpingAt == 'TANKLEVEL2') startPumpingLevelReached = (parseInt(nextSensorReading.tankLevel2) === 0)
else if (nextSensorReading.startPumpingAt == 'TANKLEVEL3') startPumpingLevelReached = (parseInt(nextSensorReading.tankLevel3) === 0)
else if (nextSensorReading.startPumpingAt == 'TANKLEVEL4') startPumpingLevelReached = (parseInt(nextSensorReading.tankLevel4) === 0)
else startPumpingLevelReached = true;
var shouldStartPumping = (!state.in_valve || state.in_valve === 'closed') && ((parseInt(nextSensorReading.tankFull) === 0) && startPumpingLevelReached && (state.out_valve === 'closed' || state.out_valve === 'closing'));
if (shouldStartPumping) {
ControllerState.update({
@@ -37,12 +51,23 @@ function reactToSensorData(nextSensorReading) {
}, {
'$set': {
'state.in_valve': 'opening',
'significantEvents.lastInValveOpen': new Date(),
'time': new Date(),
'set_by': 'server'
}
});
} else if (shouldStopPumping) {
}
var stopPumpingLevelReached;
if (nextSensorReading.stopPumpingAt == 'TANKLEVEL0') stopPumpingLevelReached = (parseInt(nextSensorReading.tankLevel0) === 1)
else if (nextSensorReading.stopPumpingAt == 'TANKLEVEL1') stopPumpingLevelReached = (parseInt(nextSensorReading.tankLevel1) === 1)
else if (nextSensorReading.stopPumpingAt == 'TANKLEVEL2') stopPumpingLevelReached = (parseInt(nextSensorReading.tankLevel2) === 1)
else if (nextSensorReading.stopPumpingAt == 'TANKLEVEL3') stopPumpingLevelReached = (parseInt(nextSensorReading.tankLevel3) === 1)
else if (nextSensorReading.stopPumpingAt == 'TANKLEVEL4') stopPumpingLevelReached = (parseInt(nextSensorReading.tankLevel4) === 1)
else stopPumpingLevelReached = false;
var shouldStopPumping = (state.in_valve === 'open' || state.in_valve === 'opening') && (parseInt(nextSensorReading.tankFull) === 1 || stopPumpingLevelReached || state.out_valve === 'open' || state.out_valve === 'opening');
if (shouldStopPumping) {
ControllerState.update({
controller_id: controllerId
}, {
@@ -91,7 +116,7 @@ function stateOrDefault(id) {
},
time: new Date(),
config: {
draining_period_amount: 60,
draining_period_amount: 40,
draining_period_unit: 'minutes'
},
set_by: 'server'
@@ -102,6 +127,3 @@ function stateOrDefault(id) {
});
return stateEntry;
}
Meteor.sharedFunctions = Meteor.sharedFunctions || {};
Meteor.sharedFunctions.reactToSensorData = reactToSensorData;

View File

@@ -4,10 +4,34 @@ if (Meteor.isServer) {
SyncedCron.start();
});
// Global API configuration
var Api = new Restivus({
useDefaultAuth: true,
prettyJson: true
});
Api.addRoute('sensorData', {
authRequired: false
}, {
post: function() {
SensorData.insert({
temperatureValue: parseFloat(this.bodyParams.temperatureValue),
humidityValue: parseFloat(this.bodyParams.humidityValue),
tankLevel0: this.bodyParams.tankLevel0,
tankLevel1: this.bodyParams.tankLevel1,
tankLevel2: this.bodyParams.tankLevel2,
tankLevel3: this.bodyParams.tankLevel3,
tankLevel4: this.bodyParams.tankLevel4,
tankFull: this.bodyParams.tankFull,
startPumpingAt: this.bodyParams.startPumpingAt,
stopPumpingAt: this.bodyParams.stopPumpingAt,
owner: this.bodyParams.owner,
created_at: new Date()
});
return [];
}
});
}

View File

@@ -3,12 +3,19 @@
## Installation
1. Go to every subdirectory in drivers directory and follow instructions about installation of drivers
2. edit controller/config/__init__.py and set your controller ID to unique number
2. edit controller/config/__init__.py and set your controller ID to unique number
3. configure cron to run controller.py every 15 minutes as a superuser:
```
crontab -e -u root
#enter these lines
*/15 * * * * /usr/bin/python /home/pi/projects/tfm/controller/sensors.py "Automatski, Senad Uka" 120
*/1 * * * * /usr/bin/python /home/pi/projects/tfm/controller/sync_state.py "Automatski, Senad Uka" 120
*/5 * * * * cd /home/pi/projects/tfm/controller && sh activity.sh
*/30 * * * * /usr/bin/python /home/pi/projects/tfm/controller/network_check.py
```
4. add following lines at the end of /etc/rc.local
```
python /home/pi/projects/tfm/controller/lockdown.py
python /home/pi/projects/tfm/controller/dweet.py
```

3
controller/activity.sh Executable file
View File

@@ -0,0 +1,3 @@
#!/bin/bash
sudo /usr/bin/python /home/pi/projects/tfm/controller/sensors.py
sudo /usr/bin/python /home/pi/projects/tfm/controller/sync_state.py

View File

@@ -1,10 +1,17 @@
GPIO_PIN_DHT = 4 # BCM
SENSORDATA_URL = 'http://tfm.meteor.com/api/v1.0/sensorData'
SENSORDATA_URL = 'http://agrar.zoblak.com/api/v1.0/sensorData'
GPIO_PIN_TANKLEVEL0 = 5 # BCM
GPIO_PIN_TANKLEVEL1 = 6 # BCM
GPIO_PIN_TANKLEVEL2 = 13 # BCM
GPIO_PIN_TANKLEVEL3 = 19 # BCM
GPIO_PIN_TANKLEVEL4 = 26 # BCM
GPIO_PIN_TANKFULL = 20 # BCM
GPIO_PIN_OUT_VALVE = 21 # BCM
GPIO_PIN_IN_VALVE = 18 # BCM
API_BASE_URL = 'http://tfm.meteor.com/api/v1.0'
START_PUMPING_AT = 'TANKFULL' # start pumping when this level = 0
STOP_PUMPING_AT = 'TANKFULL' # stop pumping when this level = 1
API_BASE_URL = 'http://agrar.zoblak.com/api/v1.0'
CONTROLLER_ID = '120' # every controller must have a different one
STATE_FILE = '/var/run/controller_state'

6
controller/dweet.py Normal file
View File

@@ -0,0 +1,6 @@
import config
import commands
command = """curl -H "Content-Type: application/json" -X POST -d '{"message": "I am aliveeee (again!)", "controller_id": %s}' https://dweet.io:443/dweet/quietly/for/5410ab1e-319c-4f14-a2e4-04725df69121""" % config.CONTROLLER_ID
print commands.getoutput(command)

3
controller/lockdown.py Normal file
View File

@@ -0,0 +1,3 @@
import state
state.safely_panic()

View File

@@ -0,0 +1,3 @@
import state
state.reboot_if_network_down()

View File

@@ -5,20 +5,38 @@ import Adafruit_DHT
import config
import RPi.GPIO as GPIO
# Try to read the state of GPIO_PIN_TANKFULL
# Try to read the state of GPIO_PIN_TANKLEVELx and GPIO_PIN_TANKFULL
GPIO.setmode(GPIO.BCM)
GPIO.setup(config.GPIO_PIN_TANKLEVEL0, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(config.GPIO_PIN_TANKLEVEL1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(config.GPIO_PIN_TANKLEVEL2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(config.GPIO_PIN_TANKLEVEL3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(config.GPIO_PIN_TANKLEVEL4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(config.GPIO_PIN_TANKFULL, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# tank sensor has inverse logic - 0 when it is full 1 when it is not
# so we are inverting its value here
tankLevel0 = (GPIO.input(config.GPIO_PIN_TANKLEVEL0) == GPIO.LOW)
tankLevel1 = (GPIO.input(config.GPIO_PIN_TANKLEVEL1) == GPIO.LOW)
tankLevel2 = (GPIO.input(config.GPIO_PIN_TANKLEVEL2) == GPIO.LOW)
tankLevel3 = (GPIO.input(config.GPIO_PIN_TANKLEVEL3) == GPIO.LOW)
tankLevel4 = (GPIO.input(config.GPIO_PIN_TANKLEVEL4) == GPIO.LOW)
tankFull = (GPIO.input(config.GPIO_PIN_TANKFULL) == GPIO.LOW)
GPIO.cleanup()
print 'Bacva Level0: {}'.format(tankLevel0)
print 'Bacva Level1: {}'.format(tankLevel1)
print 'Bacva Level2: {}'.format(tankLevel2)
print 'Bacva Level3: {}'.format(tankLevel3)
print 'Bacva Level4: {}'.format(tankLevel4)
print 'Bacva puna: {}'.format(tankFull)
# Go on to DHT
SENSOR_TYPE = Adafruit_DHT.DHT11
controller_id = config.CONTROLLER_ID
owner = "Controller: %s" % controller_id
startPumpingAt = config.START_PUMPING_AT
stopPumpingAt = config.STOP_PUMPING_AT
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
@@ -31,9 +49,9 @@ humidity, temperature = Adafruit_DHT.read_retry(SENSOR_TYPE, config.GPIO_PIN_DHT
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if temperature is not None and humidity is not None:
response = requests.post(config.SENSORDATA_URL, json={"owner": owner, "temperatureValue": temperature, "humidityValue":humidity, "tankFull": "1" if tankFull else "0",
"controllerId": controller_id
if tankFull is not None:
response = requests.post(config.SENSORDATA_URL, json={"owner": owner, "temperatureValue": temperature, "humidityValue":humidity, "tankLevel0": "1" if tankLevel0 else "0","tankLevel1": "1" if tankLevel1 else "0","tankLevel2": "1" if tankLevel2 else "0","tankLevel3": "1" if tankLevel3 else "0", "tankLevel4": "1" if tankLevel4 else "0", "tankFull": "1" if tankFull else "0",
"startPumpingAt": startPumpingAt,"stopPumpingAt": stopPumpingAt,"controllerId": controller_id
})
print 'Temp={0:0.1f}*C'.format(temperature)
print 'Humidity={0:0.1f}%'.format(humidity)

View File

@@ -2,26 +2,42 @@ import config
from state.server import Server
from state.changer import Changer
from state.file import File
import commands
def safely_panic():
safe_state = {}
changer = Changer(safe_state,safe_state)
changer.stop_everything()
def reboot_if_network_down():
try:
server = Server(config.API_BASE_URL, config.CONTROLLER_ID)
server_state = server.get_state()
print "Got state from server: " + repr(server_state)
except:
print "Problem with the network!"
commands.getoutput('/sbin/shutdown -r +3')
def sync():
server = Server(config.API_BASE_URL, config.CONTROLLER_ID)
local = File(config.STATE_FILE)
server_state = server.get_state()
try:
server = Server(config.API_BASE_URL, config.CONTROLLER_ID)
local = File(config.STATE_FILE)
server_state = server.get_state()
if local.present():
local.load()
print "local present: " + repr(local.data)
else:
local.data = server_state
print "local not present, server: " + repr(local.data)
local.save()
local_state = local.data
if local.present():
local.load()
print "local present: " + repr(local.data)
else:
local.data = server_state
print "local not present, server: " + repr(local.data)
local.save()
changer = Changer(local_state, server_state)
current_state = changer.process_change()
local_state = local.data
changer = Changer(local_state, server_state)
current_state = changer.process_change()
server.post_state(current_state)
server.post_state(current_state)
except:
print " panicking safely ! "
safely_panic()

View File

@@ -24,6 +24,10 @@ class Changer(object):
'closed': self.close_in_valve
}
def stop_everything(self):
self.close_in_valve()
self.close_out_valve()
def safe_remote_state(self, key):
if key in ['out_valve', 'in_valve']:
return self.remote_state.get(key, 'closed')

View File

@@ -0,0 +1,33 @@
import json
import requests
DWEET_UID = "5410ab1e-319c-4f14-a2e4-04725df69121"
class DweetServer(object):
"Gets state from server and sends it to the server after change"
def __init__(self, controller_id=None):
self.url_base = "https://dweet.io:443/dweet/quietly/for/%s" % DWEET_UID
self.controller_id = controller_id
def send_message(self, message):
result = requests.post(self.full_url(),
json=json.dumps({
'controller_id': self.controller_id,
'message': message
}))
return handle_response(result)
def full_url(self):
if self.controller_id is None:
raise ClassNotReadyException("Controller id not set!")
if self.url_base is None:
raise ClassNotReadyException("URL base not set!")
return self.url_base
def handle_response(response):
if response.status_code != 200 or response.status_code != 204:
raise Exception("Response not 200 or 204!")
else:
return response.json()

View File

@@ -16,8 +16,6 @@ class Server(object):
result = requests.post(self.full_url('state/%s') % self.controller_id, local_state)
return handle_response(result)
def full_url(self, action):
if self.controller_id is None:
raise ClassNotReadyException("Controller id not set!")

43
misc/latest_dweets.html Normal file
View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<style>
body {
background: #F9F9FA;
}
</style>
</head>
<body>
<a href="#" id="get-data">Get JSON data</a>
<div id="show-data"></div>
<script>
$(document).ready(function() {
$('#get-data').click(function() {
var showData = $('#show-data');
$.getJSON('https://dweet.io:443/get/dweets/for/5410ab1e-319c-4f14-a2e4-04725df69121', function(data) {
console.log(data);
var items = data.with.map(function(item) {
return item.created + ': ' + item.content.controller_id + ' (' + item.content.message + ')';
});
showData.empty();
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
showData.text('Loading the JSON file.');
});
});
</script>
</body>
</html>

24
misc/latest_dweets.js Normal file
View File

@@ -0,0 +1,24 @@
$(document).ready(function () {
$('#get-data').click(function () {
var showData = $('#show-data');
$.getJSON('https://dweet.io:443/get/dweets/for/5410ab1e-319c-4f14-a2e4-04725df69121', function (data) {
console.log(data);
var items = data.items.map(function (item) {
return item.key + ': ' + item.value;
});
showData.empty();
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
showData.text('Loading the JSON file.');
});
});