def generate(self): num_drinks = 0 num_sessions = 0 now = BASE_TIME b = backend.KegbotBackend() while num_drinks < NUM_DRINKS: num_drinks += 1 ticks = 400 + random.randrange(0, 400) username = random.choice(DRINKERS) if username: models.User.objects.get_or_create(username=username) start_time = time.time() d = b.RecordDrink(TAP, ticks, pour_time=now, username=username) delta = time.time() - start_time end_session = random.random() >= 0.75 ms = int(delta * 1000) print '%s: %s: %s [%s]' % (ms, d.id, d.user, d.keg) if end_session: now += datetime.timedelta(hours=24 + random.randrange(0, 12)) else: now += datetime.timedelta(minutes=random.randrange(3, 60)) if d.keg.remaining_volume < 10000: b.EndKeg(TAP) b.StartKeg(TAP)
def handle(self, **options): installed = False try: b = backend.KegbotBackend() installed = defaults.db_is_installed() except backend.BackendError, e: pass
def _tap_detail_post(request, tap): form = forms.DrinkPostForm(request.POST) if not form.is_valid(): raise krest.BadRequestError, _form_errors(form) cd = form.cleaned_data if cd.get('pour_time') and cd.get('now'): pour_time = datetime.datetime.fromtimestamp(cd.get('pour_time')) now = datetime.datetime.fromtimestamp(cd.get('now')) skew = datetime.datetime.now() - now pour_time += skew else: pour_time = None duration = cd.get('duration') if duration is None: duration = 0 b = backend.KegbotBackend(site=request.kbsite) try: res = b.RecordDrink(tap_name=tap, ticks=cd['ticks'], volume_ml=cd.get('volume_ml'), username=cd.get('username'), pour_time=pour_time, duration=duration, auth_token=cd.get('auth_token'), spilled=cd.get('spilled')) return FromProto(res) except backend.BackendError, e: raise krest.ServerError(str(e))
def testShout(self): b = backend.KegbotBackend() keg = b.StartKeg('kegboard.flow0', beer_name='Unknown', brewer_name='Unknown', style_name='Unknown') d = b.RecordDrink('kegboard.flow0', ticks=123, shout='_UNITTEST_') response = self.client.get(d.get_absolute_url()) self.assertContains(response, '<p>_UNITTEST_</p>', status_code=200)
def testBasicEndpoints(self): for endpoint in ('/kegs/', '/stats/'): response = self.client.get(endpoint) self.assertEquals(200, response.status_code) for endpoint in ('/sessions/',): response = self.client.get(endpoint) self.assertEquals(404, response.status_code) b = backend.KegbotBackend() keg = b.StartKeg('kegboard.flow0', beer_name='Unknown', brewer_name='Unknown', style_name='Unknown') self.assertIsNotNone(keg) response = self.client.get('/kegs/') self.assertEquals(200, response.status_code) d = b.RecordDrink('kegboard.flow0', ticks=100) drink_id = d.id response = self.client.get('/d/%s' % drink_id, follow=True) self.assertRedirects(response, '/drinks/%s' % drink_id, status_code=301) session_id = d.session.id response = self.client.get('/s/%s' % session_id, follow=True) self.assertRedirects(response, d.session.get_absolute_url(), status_code=301)
def _thermo_sensor_post(request, sensor_name): form = forms.ThermoPostForm(request.POST) if not form.is_valid(): raise krest.BadRequestError, _form_errors(form) cd = form.cleaned_data b = backend.KegbotBackend(site=request.kbsite) sensor, created = models.ThermoSensor.objects.get_or_create( site=request.kbsite, raw_name=sensor_name) # TODO(mikey): use form fields to compute `when` return FromProto(b.LogSensorReading(sensor.raw_name, cd['temp_c']))
def setUp(self): models.KegbotSite.objects.filter(name='default').delete() self.site, created = models.KegbotSite.objects.get_or_create( name='default') self.backend = backend.KegbotBackend(site=self.site) self.brewer = bdb_models.Brewer.objects.create( name='Moonshine Beers', country='USA', origin_state='Anystate', origin_city='Bathtub', production='retail', url='http://example.com/', description='Pretty bad beers.', ) self.beer_style = bdb_models.BeerStyle.objects.create(name='Porter', ) self.beer_type = bdb_models.BeerType.objects.create( name='Moonshine Porter', brewer=self.brewer, style=self.beer_style, calories_oz=3.0, carbs_oz=10.0, abv=0.05, ) self.keg_vol = units.UnitConverter.Convert(2.0, units.UNITS.Liter, units.RECORD_UNIT) self.keg_size = models.KegSize.objects.create( name='Tiny Keg', volume_ml=self.keg_vol, ) self.keg = models.Keg.objects.create( site=self.site, type=self.beer_type, size=self.keg_size, startdate=datetime.datetime(2000, 4, 1), enddate=datetime.datetime(2000, 5, 1), status='online', description='Our first keg!', origcost=99.0, ) self.tap = models.KegTap.objects.create( site=self.site, name='Test Tap', meter_name='test', ml_per_tick=(1000.0 / 2200.0), current_keg=self.keg, ) self.user = models.User.objects.create(username='******', ) self.user2 = models.User.objects.create(username='******', )
def setUp(self): self.site, created = models.KegbotSite.objects.get_or_create(name='default') self.backend = backend.KegbotBackend(site=self.site) test_usernames = ('user1', 'user2', 'user3') self.users = [self.backend.CreateNewUser(name) for name in test_usernames] self.taps = [ self.backend.CreateTap('tap1', 'kegboard.flow0', ml_per_tick=1/2200.0), self.backend.CreateTap('tap2', 'kegboard.flow1', ml_per_tick=1/2200.0), ]
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 cancel_drink(request): #if request.method != 'POST': # raise krest.BadRequestError, 'Method not supported at this endpoint' #form = forms.DrinkCancelForm(request.POST) form = forms.CancelDrinkForm(request.GET) if not form.is_valid(): raise krest.BadRequestError, _form_errors(form) cd = form.cleaned_data b = backend.KegbotBackend(site=request.kbsite) try: res = b.CancelDrink(seqn=cd.get('id'), spilled=cd.get('spilled', False)) return FromProto(res) except backend.BackendError, e: raise krest.ServerError(str(e))
def __init__(self, local_backend=False): self._event_hub = kbevent.EventHub() self._logger = logging.getLogger('env') self._kegnet_server = kegnet.KegnetServer(name='kegnet', kb_env=self, addr=FLAGS.kb_core_bind_addr) if local_backend: # Database backend. self._logger.info('Using database backend.') self._backend = backend.KegbotBackend() else: # Web backend. self._logger.info('Using web backend: %s' % FLAGS.api_url) self._backend = backend.WebBackend() # Build managers self._tap_manager = manager.TapManager('tap-manager', self._event_hub) self._flow_manager = manager.FlowManager('flow-manager', self._event_hub, self._tap_manager) self._authentication_manager = manager.AuthenticationManager('auth-manager', self._event_hub, self._flow_manager, self._tap_manager, self._backend) self._drink_manager = manager.DrinkManager('drink-manager', self._event_hub, self._backend) self._thermo_manager = manager.ThermoManager('thermo-manager', self._event_hub, self._backend) self._subscription_manager = manager.SubscriptionManager('pubsub', self._event_hub, self._kegnet_server) # Build threads self._threads = set() self._service_thread = kb_threads.EventHandlerThread(self, 'service-thread') self._service_thread.AddEventHandler(self._tap_manager) self._service_thread.AddEventHandler(self._flow_manager) self._service_thread.AddEventHandler(self._drink_manager) self._service_thread.AddEventHandler(self._thermo_manager) self._service_thread.AddEventHandler(self._authentication_manager) self._service_thread.AddEventHandler(self._subscription_manager) self.AddThread(self._service_thread) self.AddThread(kb_threads.EventHubServiceThread(self, 'eventhub-thread')) self.AddThread(kb_threads.NetProtocolThread(self, 'net-thread')) self.AddThread(kb_threads.HeartbeatThread(self, 'heartbeat-thread')) self._watchdog_thread = kb_threads.WatchdogThread(self, 'watchdog-thread') self.AddThread(self._watchdog_thread)
def save(self, tap): if not self.is_valid(): raise ValueError('Form is not valid.') b = backend.KegbotBackend() if tap.is_active(): b.EndKeg(tap) cd = self.cleaned_data keg = b.StartKeg(tap, beer_name=cd['beer_name'], brewer_name=cd['brewer_name'], style_name=cd['style_name'], keg_size=cd['keg_size']) if cd['description']: keg.description = cd['description'] keg.save()
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 get_auth_token(request, auth_device, token_value): b = backend.KegbotBackend(site=request.kbsite) tok = b.GetAuthToken(auth_device, token_value) return FromProto(tok)
def __init__(self, addr=None): kegnet.SimpleKegnetClient.__init__(self, addr) self._backend = backend.KegbotBackend()