def set_defaults(force=False): """ default values (contents may change with schema) """ if not force and db_is_installed(): raise RuntimeError, "Database is already installed." site = models.KegbotSite.objects.create(name='default') # KegTap defaults main_tap = models.KegTap(site=site, name='Main Tap', meter_name='kegboard.flow0') main_tap.save() secondary_tap = models.KegTap(site=site, name='Second Tap', meter_name='kegboard.flow1') secondary_tap.save() b = backend.KegbotBackend() # brewer defaults unk_brewer = bdb.Brewer(name='Unknown Brewer') unk_brewer.save() # beerstyle defaults unk_style = bdb.BeerStyle(name='Unknown Style') unk_style.save() # beertype defaults unk_type = bdb.BeerType(name="Unknown Beer", brewer=unk_brewer, style=unk_style) unk_type.save() # KegSize defaults - from http://en.wikipedia.org/wiki/Keg#Size default_sizes = ( (15.5, "Full Keg (half barrel)"), (13.2, "Import Keg (European barrel)"), (7.75, "Pony Keg (quarter barrel)"), (6.6, "European Half Barrel"), (5.23, "Sixth Barrel (torpedo keg)"), (5.0, "Corny Keg"), (1.0, "Mini Keg"), ) for gallons, description in default_sizes: volume = units.Quantity(gallons, units.UNITS.USGallon) volume_int = volume.Amount(in_units=units.RECORD_UNIT) ks = models.KegSize( name=description, volume_ml=volume_int, ) ks.save()
def volume(text, fmt='pints'): try: vol = units.Quantity(float(text)) except ValueError: return text if fmt == 'pints': res = vol.InPints() elif fmt == 'liters': res = vol.InLiters() elif fmt == 'ounces': res = vol.InOunces() elif fmt == 'gallons': res = vol.InUSGallons() elif fmt == 'twelveounces': res = vol.InTwelveOunceBeers() elif fmt == 'halfbarrels': res = vol.InHalfBarrelKegs() else: raise TemplateSyntaxError, 'Unknown volume format: %s' % fmt return float(res)
def KegVolumeChart(keg): if not isinstance(keg, models.Keg): raise ChartError('Bad value given for keg') stats = keg.GetStats() served = units.Quantity(stats.total_volume_ml) served_pints = to_pints(served) full_pints = to_pints(keg.full_volume()) remain_pints = full_pints - served_pints res = { 'chart': { 'defaultSeriesType': 'bar', }, 'series': [ {'data': [served_pints]}, ], 'tooltip': { 'enabled': False, }, 'xAxis': { 'categories': ['Served'], 'labels': { 'enabled': False, }, 'gridLineWidth': 0, }, 'yAxis': { 'endOnTick': False, 'min': 0, 'max': full_pints, 'lineWidth': 0, 'labels': { 'enabled': False, }, }, } return res
def onFlowUpdate(self, event): flow_id = event.flow_id if event.state == event.FlowState.COMPLETED: if flow_id in self._flows: del self._flows[flow_id] return curr_ounces = float( units.Quantity(event.volume_ml, units=units.UNITS.Ounce, from_units=units.UNITS.Milliliter)) if flow_id not in self._flows: self._flows[flow_id] = -1 last_ounces = self._flows[flow_id] for trigger in OUNCE_TRIGGER_THRESHOLDS: if (last_ounces < trigger) and (curr_ounces >= trigger): self._ThresholdEvent(trigger, event) break self._flows[flow_id] = curr_ounces
def backwards(self, orm): for dc in orm.DrinkClassification.objects.all(): volume_ml = units.Quantity(dc.minimum_volume, units=UNITS.Milliliter) volume_orig = volume_ml.Amount(in_units=UNITS.KbMeterTick) dc.minimum_volumel = volume_orig dc.save()
def Volume(self): return units.Quantity(self.volume_ml)
def __str__(self): gallons = units.Quantity(self.volume_ml).InUSGallons() return "%s [%.2f gal]" % (self.name, gallons)
def testDrinkSessions(self): """ Checks for the DrinkingSession records. """ u1 = self.user u2 = self.user2 vol = units.Quantity(1200) drinks = {} base_time = datetime.datetime(2009, 1, 1, 1, 0, 0) ticks = volume = vol.InKbMeterTicks() td_10m = datetime.timedelta(minutes=10) td_200m = datetime.timedelta(minutes=200) td_190m = td_200m - td_10m self.assertEqual(models.Drink.objects.all().count(), 0) self.assertEqual(models.DrinkingSession.objects.all().count(), 0) ### User 1 # t=0 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u1.username, pour_time=base_time, ) # t=10 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u1.username, pour_time=base_time + td_10m, ) # t=200 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u1.username, pour_time=base_time + td_200m, ) drinks_u1 = u1.drinks.all().order_by('starttime') ### User 2 # t=0 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u2.username, pour_time=base_time, ) # t=200 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u2.username, pour_time=base_time + td_200m, ) # t=190 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u2.username, pour_time=base_time + td_190m, ) drinks_u2 = u2.drinks.all().order_by('starttime') u1_chunks = u1.session_chunks.all().order_by('starttime') self.assertEqual(len(u1_chunks), 2) u2_chunks = u2.session_chunks.all().order_by('starttime') self.assertEqual(len(u2_chunks), 2) s1, s2 = models.DrinkingSession.objects.all().order_by('starttime')[:2] SESSION_DELTA = datetime.timedelta( minutes=kb_common.DRINK_SESSION_TIME_MINUTES) # session 1: should be 10 minutes long as created above self.assertEqual(s1.starttime, drinks_u1[0].starttime) self.assertEqual(s1.endtime, drinks_u1[1].starttime) self.assertEqual(s1.drinks.valid().filter(user=u1).count(), 2) self.assertEqual(s1.drinks.valid().filter(user=u2).count(), 1) # session 2: at time 200, 1 drink self.assertEqual(s2.starttime, base_time + td_190m) self.assertEqual(s2.endtime, base_time + td_200m) self.assertEqual(s2.drinks.valid().filter(user=u1).count(), 1) self.assertEqual(s2.drinks.valid().filter(user=u2).count(), 2) # user2 session2: drinks are added out of order to create this, ensure times # match u2_c2 = u2_chunks[1] self.assertEqual(u2_c2.starttime, base_time + td_190m) self.assertEqual(u2_c2.endtime, base_time + td_200m) # Now check DrinkingSessions were created correctly; there should be # two groups capturing all 4 sessions. all_groups = models.DrinkingSession.objects.all().order_by('starttime') self.assertEqual(len(all_groups), 2) self.assertEqual(all_groups[0].starttime, base_time) self.assertEqual(all_groups[0].endtime, base_time + td_10m) self.assertEqual(all_groups[0].user_chunks.all().count(), 2) self.assertEqual(all_groups[1].starttime, base_time + td_190m) self.assertEqual(all_groups[1].endtime, base_time + td_200m) self.assertEqual(all_groups[1].user_chunks.all().count(), 2)
def gentestdata(): """ default values (contents may change with schema) """ sn = bdb.Brewer(name='Sierra Nevada Brewing Company', country='USA', origin_state='California', origin_city='Chico', production='commercial', url='http://www.sierranevada.com/') sn.save() an = bdb.Brewer(name='Anchor Brewing Company', country='USA', origin_state='California', origin_city='San Francisco', production='commercial', url='http://www.anchorsteam.com/') an.save() # beerstyle defaults pale_ale = bdb.BeerStyle(name='Pale Ale') pale_ale.save() # beertype defaults sn_pa = bdb.BeerType(name="Sierra Nevada Pale Ale", brewer=sn, style=pale_ale, calories_oz=10, carbs_oz=10, abv=5.5) sn_pa.save() as_pa = bdb.BeerType(name="Anchor Liberty Ale", brewer=an, style=pale_ale, calories_oz=10, carbs_oz=10, abv=5.0) as_pa.save() usernames = ['abe', 'bort', 'charlie'] users = [] b = backend.KegbotBackend() for name in usernames: users.append(b.CreateNewUser(name)) half_barrel = models.KegSize(name="half barrel", volume_ml=10000) half_barrel.save() k = models.Keg(type=as_pa, size=half_barrel, status='online', origcost=100) k.save() drink_base = datetime.datetime(2007, 1, 1, 8, 0, 0) drink_interval = datetime.timedelta(seconds=600) drink_num = 0 drink_vols = [] for ml in (2200, 1100, 550, 715, 780): drink_vols.append( units.Quantity(ml, from_units=units.UNITS.KbMeterTick)) # generate some drinks times = (drink_base, drink_base + datetime.timedelta(days=1)) for drink_time in times: for rounds in range(3): for u in users: start = drink_time + drink_num * drink_interval end = start + datetime.timedelta(seconds=10) vol = drink_vols[drink_num % len(drink_vols)] drink = models.Drink(ticks=vol.InKbMeterTicks(), volume_ml=vol.Amount(units.RECORD_UNIT), starttime=start, user=u, keg=k, status='valid') drink.save() drink_num += 1 # fake thermo data thermo_start = datetime.datetime.now() - datetime.timedelta(hours=24) sensor_name = "thermo-0000000000000000" sensor = models.ThermoSensor.objects.create(raw_name=sensor_name, nice_name='Test sensor') for minute in xrange(60 * 24): temp_time = thermo_start + datetime.timedelta(minutes=minute) slot = (minute + 1) / 30.0 var = math.cos(2 * math.pi * slot) temp_value = 5.0 + 2.0 * var record = models.Thermolog(sensor=sensor, temp=temp_value, time=temp_time) record.save()
def __str__(self): vol = units.Quantity(self.minimum_volume_ml, units.UNITS.Milliliter) oz = vol.InOunces() return '%s (%.1foz or more)' % (self.name, oz)
def setUp(self): del logging.root.handlers[:] if not defaults.db_is_installed(): defaults.set_defaults() models.Drink.objects.all().delete() self.site, _ = models.KegbotSite.objects.get_or_create(name='default') self.keg_size = models.KegSize.objects.create( name='10Liter Keg', volume_ml=units.Quantity(10000)) self.beer_style = bdb_models.BeerStyle.objects.create( name='test style') self.brewer = bdb_models.Brewer.objects.create(name='test brewer') self.beer_type = bdb_models.BeerType.objects.create( name='test beer type', brewer=self.brewer, style=self.beer_style, calories_oz=10.0, carbs_oz=2.0, abv=5.0) self.test_keg = models.Keg.objects.create(site=self.site, type=self.beer_type, size=self.keg_size, status='online', description='None') self.test_tap = models.KegTap.objects.create( site=self.site, name='Test Tap', meter_name='test_meter_name', ml_per_tick=(1000.0 / 2200.0), current_keg=self.test_keg) self.kegbot = kegbot.KegbotCoreApp(local_backend=True) self.env = self.kegbot._env self.backend = self.env.GetBackend() self.test_user = self.backend.CreateNewUser('tester') self.test_token = self.backend.CreateAuthToken('core.onewire', '0000111122223333', 'tester') self.test_user_2 = self.backend.CreateNewUser('tester_2') self.test_token_2 = self.backend.CreateAuthToken( 'core.onewire', 'baadcafebeeff00d', 'tester_2') kb_common.AUTH_DEVICE_MAX_IDLE_SECS['core.onewire'] = 2 # Kill the kegbot flow processing thread so we can single step it. self.service_thread = self.env._service_thread self.env._threads.remove(self.service_thread) self.kegbot._Setup() self.kegbot._StartThreads() self.client = kegnet.KegnetClient() while True: if self.client.Reconnect(): break
def to_pints(volume): return float(units.Quantity(volume).InPints())