-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
391 lines (333 loc) · 13.7 KB
/
Copy pathmain.py
File metadata and controls
391 lines (333 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# -*- coding: cp1252 -*-
import time, sys, select, math, os, threading, random
from datetime import datetime
import pygame
import utility
from widgets.colors import *
from widgets.tempController import paintTempController
from widgets.brewSetup import paintBreweryDiagram
from widgets.menuStrip import drawMenuStrip
from widgets.oldGuiDisplay import guiDisplay
from widgets.switch import paintSwitch
from widgets.graph import graph_display
import interfaces.arduinoMMI as arduinoMMI
import interfaces.arduinoWaterLevel as arduinoWaterLevel
from constants import *
from simple_pid import PID
# Debug feature to run sw without the correct hardware
_DEBUG_ = False
_BLYNK_ = True
if _BLYNK_:
import interfaces.blynk_lib as blynk_lib
if (os.name == 'nt') or (_DEBUG_):
_ENABLE_EXTERNAL_IO_ = False
else:
_ENABLE_EXTERNAL_IO_ = True
if _ENABLE_EXTERNAL_IO_:
import hw_lib.ds1307_lib as ds1307_lib
import hw_lib.ds18b20_lib as ds18b20_lib
import hw_lib.lcd_lib as lcd_lib
import RPi.GPIO as GPIO
import interfaces.sql_database_lib as sql_database_lib
# Pygame frame variables
frame_count = 0
frame_rate = 100
start_time = 90
# Global Variables
indicatorFlashState = ['0', 125]
sensor_number = 0
sensor_temperature = [0,0,0]
temperature_log = [[0,0]]
heatOutput = False
current_time = datetime.now()
current_time_in_seconds = 0
power_up_time = datetime.now()
first_conversion_complete_flag = False
conversion_event = 0
current_temperature = 0
target_temperature = 212
waterLevelValue = 0
countdownTimerSeconds = 3600
gasSwitchState = 0
gasLedValue = False
pumpSwitchState = 0
# LCD variables
ipAddress = "0.0.0.0"
# Icon indicator vars
blynkConnected = False
wifiConnected = False
databaseSetup = False
# Fault indicator vars
mmiError = True
waterLevelError = True
rtcError = True
i2cError = True
##-----------------------------------------------------------------
# Configure this 0 for RPI B and 1 for RPI A
if (os.name != 'nt'):
if utility.isRpiA():
print(">> RPI Model A Detected")
smbusNumber = 1
else:
print(">> RPI Model B/C Detected")
smbusNumber = 0
# For use when debuggin code and a monitor is not connected
if (os.name != 'nt') and (_DEBUG_):
os.environ["SDL_VIDEODRIVER"] = "fbcon"
print(">> Pre Screen Init")
pygame.init()
pygame.display.set_caption("Temperature Controller")
# Init Libraries and Widgets
screen = pygame.display.set_mode([full_screen_width, full_screen_height])
print(">> Post Screen Init")
if _ENABLE_EXTERNAL_IO_:
realTime = ds1307_lib.ds1307(smbusNumber)
oneWireBus = ds18b20_lib.ds18b20(smbusNumber)
lcd = lcd_lib.lcd(smbusNumber)
#adc = ads1015_lib.ads1015()
database = sql_database_lib.sql_database_lib()
mmi = arduinoMMI.arduinoMMI()
waterLevel = arduinoWaterLevel.arduinoWaterLevel()
# Setup GPIO to control the mosfet
if _ENABLE_EXTERNAL_IO_:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(SOLENOID_PIN, GPIO.OUT)
GPIO.setup(PUMP_PIN, GPIO.OUT)
#Loop until the user clicks the close button.
done=False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
heat_font = pygame.font.Font(None, 100)
# Initialize BLYNK library
if _BLYNK_:
blynkLib = blynk_lib.blynk_lib()
blynkLib.run()
# Initialize PID algorithm for SSR control
pid = PID(0.5, 1, 1, setpoint=target_temperature)
# Only want to output a 0 or a 1
pid.output_limits = (0, 1)
# Set sample time to 0.5 seconds
pid.sample_time = 0.5
##-----------------------------------------------------------------
# Calculates the furute linear temperature
def calc_future_temp(prev_temp, current_temp):
#####change this to effect how soon to shut off burner
multiplier = 2
#####
slope = float(current_temp-prev_temp)
return ((multiplier * slope) + current_temp)
# Grab time before stepping into the main program loop
if _ENABLE_EXTERNAL_IO_:
try:
tmpTime = realTime.getDateDs1307()
power_up_time = time.mktime(tmpTime.timetuple())
rtcError = False
except:
# Might want to figure out a better way to come up with an RTC error??
rtcError = True
if _ENABLE_EXTERNAL_IO_:
# Get local IP Address
ipAddress = utility.get_ip_address()
if (os.name != 'nt'):
# Chech wifi connection
wifiConnected = utility.isWifiConnected()
# Check if database is configured
databaseSetup = utility.doesDatabaseExist()
# -------- Main Program Loop --------------------------------------
while done==False:
# ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
done=True
elif event.key == pygame.K_ESCAPE:
done=True
elif event.key == pygame.K_1:
sensor_number = 0
elif event.key == pygame.K_2:
sensor_number = 1
elif event.key == pygame.K_3:
sensor_number = 2
elif event.key == pygame.K_4:
sensor_temperature[1] = 120
elif event.key == pygame.K_UP:
sensor_temperature[sensor_number] += 1
elif event.key == pygame.K_DOWN:
sensor_temperature[sensor_number] -= 1
#elif event.type == pygame.MOUSEBUTTONDOWN:
# if button_1.pressed(pygame.mouse.get_pos()):
# sensor_temperature[sensor_number] += 5
# elif button_2.pressed(pygame.mouse.get_pos()):
# sensor_temperature[sensor_number] = 10
if _ENABLE_EXTERNAL_IO_:
# Due to not knowing how fast the temp readings are made and knowing
# that temperature conversions can take almost a second. The readings
# are staggered.
if first_conversion_complete_flag:
if conversion_event == 0:
# Read temperature sesnor
sensor_temperature[0] = oneWireBus.Sensor_Read_Temp(ROM1)
# Start next temp conversion
oneWireBus.Sensor_Convert(ROM1)
elif conversion_event == 1:
# Read temperature sesnor
sensor_temperature[1] = oneWireBus.Sensor_Read_Temp(ROM2)
# Start next temp conversion
oneWireBus.Sensor_Convert(ROM2)
elif conversion_event == 2:
# Read temperature sesnor
sensor_temperature[2] = oneWireBus.Sensor_Read_Temp(ROM3)
# Start next temp conversion
oneWireBus.Sensor_Convert(ROM3)
try:
# Get RTC time in string format
current_time = realTime.getDateDs1307()
# Convert to seconds
current_time_in_seconds = time.mktime(current_time.timetuple())
rtcError = False
except:
print("RTC Error")
rtcError = True
# Update database with newest temp
database.update_temperature(1, sensor_temperature[0])
database.update_temperature(2, sensor_temperature[1])
database.update_temperature(3, sensor_temperature[2])
else:
if conversion_event == 0:
oneWireBus.Sensor_Convert(ROM1)
database.add_sensor_to_db(ROM1, "Sensor 1")
elif conversion_event == 1:
oneWireBus.Sensor_Convert(ROM2)
database.add_sensor_to_db(ROM2, "Sensor 2")
elif conversion_event == 2:
oneWireBus.Sensor_Convert(ROM3)
database.add_sensor_to_db(ROM3, "Sensor 3")
first_conversion_complete_flag = True
# Cycle through temp calculations on all the sensors
conversion_event += 1
if conversion_event > 3:
conversion_event = 0
else:
# Test scenario, using fake data
first_conversion_complete_flag = True
#---------------------- Serial Device Logic -----------------------
# Check serial threads for new messages and process them
if _ENABLE_EXTERNAL_IO_:
mmi.doWork()
gasSwitchState = mmi.getGasSwitchState()
pumpSwitchState = mmi.getPumpSwitchState()
target_temperature = mmi.getTargetTempState()
mmiError = mmi.getCommStatus()
if _ENABLE_EXTERNAL_IO_:
waterLevel.doWork()
waterLevelError = waterLevel.getCommStatus()
#------------------------------------------------------------------
# I2c error is evaluated by checking all i2c devices
if _ENABLE_EXTERNAL_IO_:
if (realTime.getI2cErrors() > 0) or (oneWireBus.getI2cErrors() > 0) or (lcd.getI2cErrors() > 0):
# Print debug for diagnosing errors
print(">> rtc={0}, 1wire={1}, lcd={2}".format(
realTime.getI2cErrors(), oneWireBus.getI2cErrors(), lcd.getI2cErrors()))
# Set error flag for GUI
i2cError = True
else:
i2cError = False
#----------------------- Gas Controll Logic -----------------------
# Determine if the gas solenoid valve should be activated
if gasSwitchState == FIRE_SWITCH_AUTO:
# Automatic Gas Fire operation
if first_conversion_complete_flag:
# Update PID setpoint if needed
if not target_temperature == pid.setpoint:
pid.setpoint = target_temperature
# Translate current temp from sensors
current_temperature = sensor_temperature[0]
# Run algorithm
heatOutput = pid(current_temperature)
print(">> PID=" + str(heatOutput))
elif gasSwitchState == FIRE_SWITCH_ON:
heatOutput = True
else:
heatOutput = False
# Set indicator value
gasLedValue = heatOutput
# Set pin output state for mosfet controlling gas solenoid
if _ENABLE_EXTERNAL_IO_:
if heatOutput:
GPIO.output(SOLENOID_PIN, GPIO.HIGH)
else:
GPIO.output(SOLENOID_PIN, GPIO.LOW)
#----------------------- Update LCD Strings -----------------------
if _ENABLE_EXTERNAL_IO_:
lcd.lcd_display_string(ipAddress, 1)
lcd.lcd_display_string("Error: {0}".format(False), 2)
#----------------------- Update pump output -----------------------
if _ENABLE_EXTERNAL_IO_:
if (pumpSwitchState == PUMP_SWITCH_ON) or (pumpSwitchState == PUMP_SWITCH_AUTO):
GPIO.output(PUMP_PIN, GPIO.HIGH)
else:
GPIO.output(PUMP_PIN, GPIO.LOW)
#----------------------- Handle Timer logic -----------------------
if _BLYNK_:
if blynkConnected:
data = blynkLib.getTimerData()
# If the countdown timer is enabled, start decrementing the
# counter. Otherwise set the timer to whatever is enabled in
# blynk terminal
if data[0] == True:
countdownTimerSeconds = countdownTimerSeconds - 1
else:
countdownTimerSeconds = int(data[1])
else:
countdownTimerSeconds = countdownTimerSeconds - 1
#if (frame_count % 60) == 0:
if _BLYNK_:
# Check Blynk connection to cloud
blynkConnected = blynkLib.isAppConnected()
# Try to write data to the cloud
blynkLib.writeDataToServer(sensor_temperature[0],
sensor_temperature[1],
sensor_temperature[2],
gasLedValue,
pumpSwitchState,
target_temperature,
countdownTimerSeconds)
# Add this in for windows testsing
if not _ENABLE_EXTERNAL_IO_:
if (frame_count % 30) == 0:
#sensor_temperature[0] = random.uniform(1, 250)
#sensor_temperature[1] = random.uniform(1, 250)
#sensor_temperature[2] = random.uniform(1, 250)
#switch_heat = random.randint(0,1)
#waterLevelValue = random.randint(0,100)
#gasSwitchState = random.randint(0,2)
gasSwitchState = FIRE_SWITCH_AUTO
pumpSwitchState = random.randint(0,2)
#
#------------------- Rendering From Here Below --------------------
#
screen.fill(grey1)
drawMenuStrip(pygame, screen, 0, 0, 65, current_time, blynkConnected, databaseSetup,
wifiConnected, countdownTimerSeconds, mmiError, waterLevelError,
rtcError, i2cError, indicatorFlashState)
paintTempController(pygame, screen, 0, 68, sensor_temperature[0], target_temperature, gasLedValue)
paintSwitch(pygame, screen, 0 , 374, "Gas", gasSwitchState)
paintSwitch(pygame, screen, 0 , 580, "Pump", pumpSwitchState)
paintBreweryDiagram(pygame, screen, 305, 66, sensor_temperature[1], sensor_temperature[2],
pumpSwitchState, True, True, waterLevelValue);
graph_display(pygame, screen, 304, 565, full_screen_width-308, 200,
int(round(current_temperature)), target_temperature, temperature_log)
# If blynk features are turned on, consistently cal the run() function to handle socket traffic.
if _BLYNK_:
blynkLib.run()
#print("frame_count = {0}".format(frame_count))
frame_count += 1
pygame.display.flip()
clock.tick(frame_rate)
# Kill serial thread
mmi.close()
waterLevel.close()
# Stop pygame
pygame.quit()