Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

executable file 246 lines (202 sloc) 5.978 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
#!/usr/bin/env python

import RPi.GPIO as GPIO
import mcp3008
import mediorc
import sys
import time
import pidvarmap

CHILLPIN = 17

def nv(v) :
if v is None :
return 0.0
else :
return v

def mean(l, default=0) :
try :
return reduce(lambda x,y: x+y, l) / float(len(l))
except :
return default

def beersafe(v) :
return min(110.0, max(38.0, v))

class PID(object) :
def __init__(self, temp_probe, target) :
self.temp_probe = temp_probe
self.samples = []
self.target = beersafe(target)
GPIO.setup(CHILLPIN, GPIO.OUT)

self.pid_ts = None
self.events = []
GPIO.output(CHILLPIN, False)

self.fPeriod = 300.0
self.fMinOff = 60.0 * 3
assert self.fPeriod > self.fMinOff

# pid state
self.fError = None
self.fIError = 0.0
self.fDError = None
self.fPriorError = None

self.fP = None
self.fI = None
self.fD = 0.0
self.fPID = None

self.fTemp = None

# guesstimated PID constants. ratio, not percentage based.
self.fKP = 0.02
self.fKI = 0.002
self.fKD = 0.0

# physical state
self.bCompressor = False

@property
def state(self) :
return {
'constants' : {
'kp' : nv(self.fKP),
'ki' : nv(self.fKI),
'kd' : nv(self.fKD),
},
'errors' : {
'err' : nv(self.fError),
'ierr' : nv(self.fIError),
'derr' : nv(self.fDError),
},
'pidstate' : {
'p' : nv(self.fP),
'i' : nv(self.fI),
'd' : nv(self.fD),
'pid' : nv(self.fPID)
},
'physical' : {
'compressor' : self.bCompressor
}
}

def step(self) :
now = time.time()
self.samples.append(self.temp_probe.read())
self.fTemp = mean(self.samples, default=self.target)
if self.pid_ts is None or self.pid_ts < now - self.fPeriod :
self.pid_ts = now
self.samples = []

# This is the error we want to reduce to 0. Positive values mean it is too warm.
self.fError = self.fTemp - self.target
print 'err: %f' % self.fError

# figure out proportion to use, start at 0
self.fPID = 0.0

# apply proportional...
self.fP = self.fKP * self.fError

# to degree-minutes
self.fIError += (self.fError * self.fPeriod) / 60.0

# apply integral...
self.fI = self.fKI * self.fIError

if self.fPriorError is not None :
self.fDError = ((self.fError - self.fPriorError) * 60.0) / self.fPeriod
self.fPriorError = self.fError

# if we've got a derivative... apply it
if self.fDError is not None :
self.fD = self.fKD * self.fDError

# sum it all up
self.fPID = self.fP + self.fI + self.fD

print time.ctime(), 'PID output: %f' % self.fPID

if self.fPID < 0.02 :
# nope, it's less than 2%. just turn it off and leave it that way until next time
self.events.append((now, False))
print time.ctime(), 'no chilling, pid output way low. just turning off'
else :
off_sec = (1.0 - min(self.fPID, 1.0)) * self.fPeriod
off_sec = max(off_sec, self.fMinOff) # 3 minute minimum to be off
on_sec = self.fPeriod - off_sec

self.events.append((now, True))
self.events.append((now + on_sec, False))
print time.ctime(), 'scheduled on/off events for pid output. on for %f, off for %f' % (on_sec, off_sec)

kept_events = []
for event in self.events :
ts,val = event
if ts <= now :
print time.ctime(), 'set chiller: %f' % val
GPIO.output(CHILLPIN, val)
self.bCompressor = val
else :
kept_events.append(event)

self.events = kept_events

class ChillmonBot(mediorc.IRC) :
def __init__(self, server, nick, chan, temp_probes, pid, zmqpub=None, zmqctrl=None) :
self.temp_probes = temp_probes
self.pid = pid
self.zmqpub = zmqpub
self.zmqctrl = zmqctrl
mediorc.IRC.__init__(self, server, nick, chan)

def on_pubmsg(self, c, e) :
chan = e.target()
words = e.arguments()[0].split(' ')

msg = None
if words[0] == '!temp' :
msg = 'temperatures: %s' % (', '.join(['%s: %0.1f F' % (name, probe.read()) for name,probe in self.temp_probes.items()]))

if msg :
self.connection.privmsg(chan, msg)

def do_work(self) :
if self.zmqpub :
ret = {
'temps' : dict(
[(k,v.read()) for k,v in self.temp_probes.items()]
+ [('run_avg', self.pid.fTemp), ('target', self.pid.target)]
                                )
}
ret.update(self.pid.state)
self.zmqpub.send(ret)

"""
self.fKP = 0.02
self.fKI = 0.002
self.fKD = 0.0

fIError
"""

if self.zmqctrl :
try :
v = self.zmqctrl.recv()
try :
cmd = v['cmd']
if cmd == 'set' :
k = v['k']
val = pidvarmap.typemap[k](v['v'])
try :
if k == 'target' :
val = beersafe(val)
setattr(self.pid, k, val)
except Exception, e :
print 'set error', e
pass
else :
print 'ERR: unknown command %s' % cmd
except KeyError, ke :
print 'ERR: %s' % ke
except IndexError, ie :
print 'ERR: %s' % ie

except zmqsub.NoMessagesException :
pass
self.pid.step()

class ChillmonBotThread(mediorc.IRCThread) :
def __init__(self, server, nick, chan, temperature_probes, pid, zmqpub=None, zmqctrl=None) :
self.bot_create = lambda: ChillmonBot(server, nick, chan, temperature_probes, pid, zmqpub=zmqpub, zmqctrl=zmqctrl)
mediorc.IRCThread.__init__(self)

if __name__ == '__main__' :
a2d = mcp3008.MCP3008(1000.0)
beer = mcp3008.TMP36(mcp3008.TMP36.F)
a2d.setup_channel(1, beer)
room = mcp3008.TMP36(mcp3008.TMP36.F)
a2d.setup_channel(2, room)
beertop = mcp3008.TMP36(mcp3008.TMP36.F)
a2d.setup_channel(3, beertop)

zmqpub = None
zmqctrl = None
try :
url = sys.argv[4]
import zmqsub
zmqpub = zmqsub.JSONZMQBindPub(url)
try :
zmqctrl = zmqsub.JSONZMQBindSub(sys.argv[5])
except IndexError :
pass
except IndexError :
pass

temp_probes = {'beer' : beer, 'room' : room, 'beertop' : beertop}
pid = PID(beer, 66) # TODO configuration system for what temp to stick to

chill = ChillmonBotThread(sys.argv[1], sys.argv[2], sys.argv[3], temp_probes, pid, zmqpub=zmqpub, zmqctrl=zmqctrl)
chill.run()

Something went wrong with that request. Please try again.