Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions Scripts/Common.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,21 @@
CONFIG_UPDATE_AVAILABLE = True
NO_CONFIG_UPDATE = False

TANK_HEIGHT = 60 # Example tank height
TOP_EMPTY_DISTANCE = 5
BOTTOM_FULL_DISTANCE = 5
ONE_THIRD_LEVEL = TANK_HEIGHT / 3
TANK_HEIGHT = 125 # Example tank height
TOP_EMPTY_DISTANCE = 25
BOTTOM_FULL_DISTANCE = 65
ONE_THIRD_LEVEL = TANK_HEIGHT // 3

CHECK_INTERVAL_SECONDS = 1
MAX_PRE_NIGHT_FILL_TIME = 600

MORNING_7AM = 7
MORNING_8AM = 8
EVENING_7PM = 19
EVENING_8PM = 20
NIGHT_10PM = 22
NIGHT_9PM = 21


VALVE1_DEFAULT_DURATION = 1 # in minutes
VALVE2_DEFAULT_DURATION = 1 # in minutes
95 changes: 85 additions & 10 deletions Scripts/Main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,18 @@ def setupGpio(gpio:GpioManager):
gpio.setup(MOTOR_PIN, True)
gpio.setup(ULTRASONIC_TRIG, True)
gpio.setup(ULTRASONIC_ECHO, False)
gpio.setup(VALVE1_PIN, True)
gpio.setup(VALVE2_PIN, True)

gpio.output(MOTOR_PIN, False)
gpio.output(VALVE1_PIN, False)
gpio.output(VALVE2_PIN, False)


def cleanupGpio(gpio:GpioManager):
gpio.output(MOTOR_PIN, False)
gpio.output(VALVE1_PIN, False)
gpio.output(VALVE2_PIN, False)
gpio.cleanup()


Expand Down Expand Up @@ -51,25 +58,90 @@ def readDistance(gpio:GpioManager, trig, echo):
def isNightTime():
now = datetime.now()
hour = now.hour
return hour >= 22 or hour < 7
return hour >= NIGHT_10PM or hour < MORNING_7AM


def main():
gpio = GpioManager()
setupGpio(gpio)

# Default valves and durations
valve1Duration = VALVE1_DEFAULT_DURATION
valve2Duration = VALVE2_DEFAULT_DURATION
Comment thread
arghyabi marked this conversation as resolved.
valve1On = False
valve2On = False
valve1StartTime = 0
valve2StartTime = 0
morningRunDone = False
eveningRunDone = False
motorStatus = "OFF"
lastMotorStatus = "OFF"
waterLevel = 0
lastWaterLevel = 0
lastDay = datetime.now().day

try:
lastCheckTime = time.time()
preNightFillActive = False
preNightFillStart = None
while True:
currentTime = time.time()
now = datetime.now()

# Reset daily flags
if now.day != lastDay:
morningRunDone = False
eveningRunDone = False
lastDay = now.day

rtDb = readRtDb()
configUpdateAvailable = rtDb.get("configUpdateAvailable", False)

# Check for config updates for valves
if configUpdateAvailable:
valve1Duration = rtDb.get("valve1Duration", VALVE1_DEFAULT_DURATION)
valve2Duration = rtDb.get("valve2Duration", VALVE2_DEFAULT_DURATION)
print(f"Updated valve durations: Valve1={valve1Duration} min, Valve2={valve2Duration} min")

# Morning valve operation
if now.hour == MORNING_8AM and not morningRunDone:
Copy link

Copilot AI Sep 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The valve scheduling logic only checks the hour but not minutes/seconds. This means valves could be activated multiple times within the same hour if the loop runs multiple times, despite the morningRunDone/eveningRunDone flags.

Copilot uses AI. Check for mistakes.
print("Morning run: Activating valves.")
gpio.output(VALVE1_PIN, True)
gpio.output(VALVE2_PIN, True)
valve1On = True
valve2On = True
valve1StartTime = currentTime
valve2StartTime = currentTime
morningRunDone = True

# Evening valve operation
if now.hour == EVENING_8PM and not eveningRunDone:
Copy link

Copilot AI Sep 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The valve scheduling logic only checks the hour but not minutes/seconds. This means valves could be activated multiple times within the same hour if the loop runs multiple times, despite the morningRunDone/eveningRunDone flags.

Copilot uses AI. Check for mistakes.
print("Evening run: Activating valves.")
gpio.output(VALVE1_PIN, True)
gpio.output(VALVE2_PIN, True)
valve1On = True
valve2On = True
valve1StartTime = currentTime
valve2StartTime = currentTime
eveningRunDone = True

# Check to turn off valves
if valve1On and (currentTime - valve1StartTime >= valve1Duration * 60):
gpio.output(VALVE1_PIN, False)
valve1On = False
print("Valve 1 duration complete. Turned off.")

if valve2On and (currentTime - valve2StartTime >= valve2Duration * 60):
gpio.output(VALVE2_PIN, False)
valve2On = False
print("Valve 2 duration complete. Turned off.")

# Original motor logic
if currentTime - lastCheckTime >= CHECK_INTERVAL_SECONDS:
distance = readDistance(gpio, ULTRASONIC_TRIG, ULTRASONIC_ECHO)
print(f"Distance: {distance} cm")
waterLevel = TANK_HEIGHT - distance
now = datetime.now()
rtDb = readRtDb()
configUpdateAvailable = rtDb.get("configUpdateAvailable", False)
motorStatus = rtDb.get("motorStatus", "OFF")

if configUpdateAvailable:
Expand All @@ -80,18 +152,16 @@ def main():
else:
gpio.output(MOTOR_PIN, False)
print("Config update: Motor OFF")
# Reset configUpdateAvailable after applying
writeRtDb(motorStatus=motorStatus, tankLevel=waterLevel, configUpdateAvailable=False)
else:
# Automatic logic
motorStatus = "OFF"
if isNightTime():
if isNightTime(): # Check if it's night time between 10 PM and 7 AM
gpio.output(MOTOR_PIN, False)
motorStatus = "OFF"
print("Night time: Motor OFF")
preNightFillActive = False
else:
if now.hour == 21 and waterLevel < ONE_THIRD_LEVEL and not preNightFillActive:
if now.hour == NIGHT_9PM and waterLevel < ONE_THIRD_LEVEL and not preNightFillActive:
print("Pre-night: Water < 1/3, filling tank...")
gpio.output(MOTOR_PIN, True)
motorStatus = "ON"
Expand Down Expand Up @@ -119,10 +189,15 @@ def main():
gpio.output(MOTOR_PIN, False)
motorStatus = "OFF"
print("Tank level OK: Motor OFF")
writeRtDb(motorStatus=motorStatus, tankLevel=waterLevel, configUpdateAvailable=False)

lastCheckTime = currentTime
time.sleep(0.1)
# Short sleep to reduce CPU usage and maintain responsiveness

if configUpdateAvailable or motorStatus != lastMotorStatus or waterLevel != lastWaterLevel:
writeRtDb(motorStatus = motorStatus, tankLevel = waterLevel, configUpdateAvailable = False)
Comment thread
arghyabi marked this conversation as resolved.
lastMotorStatus = motorStatus
lastWaterLevel = waterLevel

time.sleep(0.1) # Sleep to reduce CPU usage
except KeyboardInterrupt:
cleanupGpio(gpio)
Copy link

Copilot AI Sep 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cleanupGpio function only turns off MOTOR_PIN but doesn't turn off VALVE1_PIN and VALVE2_PIN. This could leave valves running after the program exits.

Copilot uses AI. Check for mistakes.

Expand Down
3 changes: 3 additions & 0 deletions Scripts/PinDescription.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
MOTOR_PIN = 32
ULTRASONIC_TRIG = 40
ULTRASONIC_ECHO = 38

VALVE1_PIN = 36
VALVE2_PIN = 37
14 changes: 14 additions & 0 deletions Web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ <h2>Motor Status</h2>
<button id="motorToggleBtn">Loading...</button>
</div>
</div>

<div class="container">
<h2>Valve Configuration</h2>
<div class="config-group">
<label for="valve1Duration">Valve 1 Duration (min):</label>
<select id="valve1Duration"></select>
<p>Selected: <span id="selectedValve1Duration"></span></p>
</div>
<div class="config-group">
<label for="valve2Duration">Valve 2 Duration (min):</label>
<select id="valve2Duration"></select>
<p>Selected: <span id="selectedValve2Duration"></span></p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
27 changes: 23 additions & 4 deletions Web/motor.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ function getStatus() {
return ["error" => "rtDb.json not found"];
}
return [
"motorStatus" => isset($data['motorStatus']) ? $data['motorStatus'] : 'OFF',
"tankLevel" => isset($data['tankLevel']) ? $data['tankLevel'] : 0,
"motorStatus" => isset($data['motorStatus']) ? $data['motorStatus'] : 'OFF',
"tankLevel" => isset($data['tankLevel']) ? $data['tankLevel'] : 0,
"valve1Duration" => isset($data['valve1Duration']) ? $data['valve1Duration'] : 1,
"valve2Duration" => isset($data['valve2Duration']) ? $data['valve2Duration'] : 1,
"configUpdateAvailable" => isset($data['configUpdateAvailable']) ? $data['configUpdateAvailable'] : false
];
}
Expand All @@ -25,9 +27,26 @@ function setMotor($motorStatus) {
return ["success" => true, "motorStatus" => $motorStatus];
}

function setConfig($key, $value) {
$data = readDb();
if ($data === false) {
return ["error" => "rtDb.json not found"];
}
$data[$key] = $value;
$data['configUpdateAvailable'] = true;
writeDb($data);
return ["success" => true, $key => $value];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$motorStatus = isset($_POST['motorStatus']) && $_POST['motorStatus'] === 'ON' ? 'ON' : 'OFF';
echo json_encode(setMotor($motorStatus));
if (isset($_POST['motorStatus'])) {
$motorStatus = $_POST['motorStatus'] === 'ON' ? 'ON' : 'OFF';
echo json_encode(setMotor($motorStatus));
} elseif (isset($_POST['valve1Duration'])) {
echo json_encode(setConfig('valve1Duration', (int)$_POST['valve1Duration']));
} elseif (isset($_POST['valve2Duration'])) {
echo json_encode(setConfig('valve2Duration', (int)$_POST['valve2Duration']));
}
} else {
echo json_encode(getStatus());
}
51 changes: 51 additions & 0 deletions Web/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ function fetchStatus() {
toggleBtn.classList.remove('on');
}
toggleBtn.disabled = false;

// Update dropdowns and selected values
updateConfigValue('valve1Duration', data.valve1Duration);
updateConfigValue('valve2Duration', data.valve2Duration);
})
.catch(err => {
document.getElementById('tankLevel').textContent = 'Error';
Expand All @@ -40,6 +44,40 @@ function setMotor(status) {
});
}

function setConfig(key, value) {
fetch('motor.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `${key}=${value}`
})
.then(res => res.json())
.then(() => fetchStatus())
.catch(err => {
alert('Failed to set config. Network error.');
fetchStatus();
console.error('Set config error:', err);
});
}

function populateDropdown(selectId) {
const select = document.getElementById(selectId);
for (let i = 1; i <= 15; i++) {
const option = document.createElement('option');
option.value = i;
option.textContent = `${i} min`;
select.appendChild(option);
}
}

function updateConfigValue(id, value) {
const select = document.getElementById(id);
const selectedSpan = document.getElementById(`selected${id.charAt(0).toUpperCase() + id.slice(1)}`);
if (value) {
select.value = value;
selectedSpan.textContent = `${value} min`;
Comment on lines +72 to +77
Copy link

Copilot AI Sep 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The string manipulation to generate the selectedSpan ID is complex and error-prone. Consider using a mapping object or more explicit ID generation to improve readability.

Suggested change
function updateConfigValue(id, value) {
const select = document.getElementById(id);
const selectedSpan = document.getElementById(`selected${id.charAt(0).toUpperCase() + id.slice(1)}`);
if (value) {
select.value = value;
selectedSpan.textContent = `${value} min`;
// Mapping from select element IDs to their corresponding span IDs
const selectToSpanMap = {
valve1Duration: 'selectedValve1Duration',
valve2Duration: 'selectedValve2Duration'
};
function updateConfigValue(id, value) {
const select = document.getElementById(id);
const spanId = selectToSpanMap[id];
const selectedSpan = document.getElementById(spanId);
if (value) {
select.value = value;
if (selectedSpan) {
selectedSpan.textContent = `${value} min`;
}

Copilot uses AI. Check for mistakes.
}
}

const motorToggleBtn = document.getElementById('motorToggleBtn');
motorToggleBtn.onclick = function() {
motorToggleBtn.disabled = true;
Expand All @@ -50,5 +88,18 @@ motorToggleBtn.onclick = function() {
}
};

// Populate dropdowns
populateDropdown('valve1Duration');
populateDropdown('valve2Duration');

// Add event listeners for dropdowns
document.getElementById('valve1Duration').addEventListener('change', function() {
setConfig('valve1Duration', this.value);
});

document.getElementById('valve2Duration').addEventListener('change', function() {
setConfig('valve2Duration', this.value);
});

fetchStatus();
setInterval(fetchStatus, 3000);
2 changes: 1 addition & 1 deletion config.yaml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
appVersion: 1.1.0.1002
appVersion: 1.2.0.1003