def state_update(data, scoring_device): if data['state'] == 'no_match': return data data['match_number'] = 0 try: match = ScoringSystem.objects.all()[0].current_match data['match_number'] = str(match.id) except: data['state'] = 'no_match' return data if not match.actual_start: data['state'] = 'prematch' return data else: timer = (match.actual_start + datetime.timedelta(seconds=151)) - tz_aware_now() if timer.days < 0: if getattr(match, 'scorer_' + data['tower_name'] + '_confirmed'): data['state'] = 'match_done_confirmed' else: data['state'] = 'match_done_not_confirmed' if data['state'] and not scoring_device.on_center: return data if not scoring_device.on_center: data['state'] = 'normal' return data center_start = getattr(match, data['tower_name'].split('_')[1] + '_center_active_start') try: diff = (center_start + datetime.timedelta(seconds=30)) - tz_aware_now() if diff.days < 0: data['state'] = 'normal_center_not_confirmed' else: data['state'] = 'center' except: data['state'] = 'normal' return data
def get_timer_dict(): match = ScoringSystem.objects.all()[0].current_match match_state = 'pre_match' try: timer = (match.actual_start + datetime.timedelta(seconds=151)) - tz_aware_now() if timer.days < 0: timer = '0:00' match_state = 'done' else: seconds = '00' + str(timer.seconds % 60) timer = str(timer.seconds / 60) + ':' + seconds[-2:] match_state = 'match' except: timer = '2:30' try: red_timer = (match.red_center_active_start + datetime.timedelta(seconds=31)) - tz_aware_now() if red_timer.days < 0: red_timer = '00' else: seconds = '00' + str(red_timer.seconds) red_timer = seconds[-2:] except: red_timer = '00' try: blue_timer = (match.blue_center_active_start + datetime.timedelta(seconds=31)) - tz_aware_now() if blue_timer.days < 0: blue_timer = '00' else: seconds = '00' + str(blue_timer.seconds) blue_timer = seconds[-2:] except: blue_timer = '00' try: red_score = match.red_score except: red_score = 0 try: blue_score = match.blue_score except: blue_score = 0 if match.is_practice: practice = 'Practice ' else: practice = '' response = {'timer': timer, 'blue_timer': blue_timer, 'red_timer': red_timer, \ 'match': {'red_score': red_score, 'blue_score': blue_score, 'id':match.id }, \ 'match_state':match_state, 'practice':practice, \ } return response
def batch_actions(request): scoring_device = ScoringDevice.objects.get(scorer=request.user) scoring_device.last_contact = tz_aware_now() scoring_device.save() match = ScoringSystem.objects.all()[0].current_match if scoring_device.on_center: tower = Tower.objects.get(name='center') else: tower = scoring_device.tower actions = json.loads(request.GET.get('actions', {})) keys = actions.keys() keys.sort() saved_actions = [] for key in keys: data = actions[key]['data'] action = actions[key]['action'] if action == 'score': score_match_event(request.user, match, tower, key, data) elif action == 'done_scoring_center': finish_scoring_center(scoring_device) elif action == 'done_scoring_match': finish_scoring_match(scoring_device, match) else: continue saved_actions.append(key) scorer_data = get_scorer_data(scoring_device) scorer_data = state_update(scorer_data, scoring_device) return HttpResponse(json.dumps({ 'success': True, 'action_ids':saved_actions, 'scorer_data': scorer_data, }), 'application/json')
def get_microseconds(): now = tz_aware_now() ms = now.microsecond ms += now.second * 1000000 ms += now.minute * 60000000 ms += now.hour * 3600000000 return ms
def reset_match(request): group = Group.objects.get(name='Scorekeepers') if group not in request.user.groups.all(): raise Http404 ss = ScoringSystem.objects.all()[0] match = ss.current_match timer = (match.actual_start + datetime.timedelta(seconds=151)) - tz_aware_now() if timer.days >= 0 and ss.task_id: task = abort_match.delay() revoke(ss.task_id, terminate=True) from celery.task.control import discard_all discard_all() else: prematch_lighting() match.reset() ScoringDevice.objects.all().update(on_center=False) for tower_name in ['low_red', 'high_red', 'low_blue', 'high_blue']: setattr(match, 'scorer_' + tower_name, None) for sd in ScoringDevice.objects.filter(tower__isnull=False): setattr(match, 'scorer_' + sd.tower.name, sd.scorer) match.save() return scorekeeper(request)
def init(): play_sound('start') match = ScoringSystem.objects.all()[0].current_match match.reset() ScoringDevice.objects.all().update(on_center=False) match.actual_start = tz_aware_now() match.save() start_match_lighting() us = get_microseconds() return match, us
def get_stats(self, confirmed): stats = {} stats['scorer'] = self.scorer.username stats['scorer_id'] = self.scorer.id stats['confirmed'] = confirmed diff = tz_aware_now() - self.last_contact stats['last_contact'] = elapsed_time(diff.seconds, separator=', ') try: diff = get_microseconds()-self.scorer.matchevent_set.all().latest('id').microseconds stats['last_event'] = elapsed_time(diff/1000000, separator=', ') except: stats['last_event'] = 'N/A' return stats
def state_update(data, scoring_device): if data['state'] == 'no_match': return data data['match_number'] = 0 try: match = ScoringSystem.objects.all()[0].current_match data['match_number'] = str(match.id) except: data['state'] = 'no_match' return data if not match.actual_start: data['state'] = 'prematch' return data else: timer = (match.actual_start + datetime.timedelta(seconds=151)) - tz_aware_now() if timer.days < 0: if getattr(match, 'scorer_' + data['tower_name'] + '_confirmed'): data['state'] = 'match_done_confirmed' else: data['state'] = 'match_done_not_confirmed' if data['state'] and not scoring_device.on_center: return data if not scoring_device.on_center: data['state'] = 'normal' return data center_start = getattr( match, data['tower_name'].split('_')[1] + '_center_active_start') try: diff = (center_start + datetime.timedelta(seconds=30)) - tz_aware_now() if diff.days < 0: data['state'] = 'normal_center_not_confirmed' else: data['state'] = 'center' except: data['state'] = 'normal' return data
def get_stats(self, confirmed): stats = {} stats['scorer'] = self.scorer.username stats['scorer_id'] = self.scorer.id stats['confirmed'] = confirmed diff = tz_aware_now() - self.last_contact stats['last_contact'] = elapsed_time(diff.seconds, separator=', ') try: diff = get_microseconds() - self.scorer.matchevent_set.all( ).latest('id').microseconds stats['last_event'] = elapsed_time(diff / 1000000, separator=', ') except: stats['last_event'] = 'N/A' return stats
def start_match(request): group = Group.objects.get(name='Scorekeepers') if group not in request.user.groups.all(): raise Http404 if settings.USE_CELERY: task = run_match.delay() print task ss = ScoringSystem.objects.all()[0] ss.task_id = task.task_id ss.save() else: match = ScoringSystem.objects.all()[0].current_match match.reset() ScoringDevice.objects.all().update(on_center=False) match.actual_start = tz_aware_now() match.save() start_match_lighting() return scorekeeper(request)
def forwards(self, orm): if not db.dry_run: users = User.objects.all() i = 0 for tower in towers: t = orm['match.Tower'](name=tower) t.save() tl = orm['match.TowerLevel'](tower=t, level=1, lighting_controller_id=0, state='off') tl.save() if 'high_' in tower or tower=='center': tl = orm['match.TowerLevel'](tower=t, level=2, lighting_controller_id=0, \ state='off') tl.save() try: user = users[i] i += 1 orm['match.ScoringDevice'](scorer=user, tower=t) except: pass db_teams = [] for team in all_teams: t = orm['tournament.Team'](number=team['number'], name=team['name'], \ school=team['school'], location=team['location'], sponsors=team['sponsors'], \ av_name=team['av_name'], gv_name=team['gv_name']) t.save() db_teams.append(t) start = tz_aware_now() matches = [] for i in range(1, 13): start += datetime.timedelta(minutes=8) teams = random.sample(db_teams, 4) match = orm['match.Match'](is_practice=True, time=start, \ red_1=teams[0], red_2=teams[1], blue_1=teams[2], blue_2=teams[3], \ red_1_gv_present=True, red_1_av_present=True, \ red_2_gv_present=True, red_2_av_present=True, \ blue_1_gv_present=True, blue_1_av_present=True, \ blue_2_gv_present=True, blue_2_av_present=True) match.save() matches.append(match) ss = orm['match.ScoringSystem'](current_match=matches[0]) ss.save()
def get_timer_dict(): match = ScoringSystem.objects.all()[0].current_match match_state = 'pre_match' try: timer = (match.actual_start + datetime.timedelta(seconds=151)) - tz_aware_now() if timer.days < 0: timer = '0:00' match_state = 'done' else: seconds = '00' + str(timer.seconds%60) timer = str(timer.seconds/60) + ':' + seconds[-2:] match_state = 'match' except: timer = '2:30' try: red_timer = (match.red_center_active_start + datetime.timedelta(seconds=31)) - tz_aware_now() if red_timer.days < 0: red_timer = '00' else: seconds = '00' + str(red_timer.seconds) red_timer = seconds[-2:] except: red_timer = '00' try: blue_timer = (match.blue_center_active_start + datetime.timedelta(seconds=31)) - tz_aware_now() if blue_timer.days < 0: blue_timer = '00' else: seconds = '00' + str(blue_timer.seconds) blue_timer = seconds[-2:] except: blue_timer = '00' try: red_score = match.red_score except: red_score = 0 try: blue_score = match.blue_score except: blue_score = 0 if match.is_practice: practice = 'Practice ' else: practice = '' response = {'timer': timer, 'blue_timer': blue_timer, 'red_timer': red_timer, \ 'match': {'red_score': red_score, 'blue_score': blue_score, 'id':match.id }, \ 'match_state':match_state, 'practice':practice, \ } return response
def batch_actions(request): scoring_device = ScoringDevice.objects.get(scorer=request.user) scoring_device.last_contact = tz_aware_now() scoring_device.save() match = ScoringSystem.objects.all()[0].current_match if scoring_device.on_center: tower = Tower.objects.get(name='center') else: tower = scoring_device.tower actions = json.loads(request.GET.get('actions', {})) keys = actions.keys() keys.sort() saved_actions = [] for key in keys: data = actions[key]['data'] action = actions[key]['action'] if action == 'score': score_match_event(request.user, match, tower, key, data) elif action == 'done_scoring_center': finish_scoring_center(scoring_device) elif action == 'done_scoring_match': finish_scoring_match(scoring_device, match) else: continue saved_actions.append(key) scorer_data = get_scorer_data(scoring_device) scorer_data = state_update(scorer_data, scoring_device) return HttpResponse( json.dumps({ 'success': True, 'action_ids': saved_actions, 'scorer_data': scorer_data, }), 'application/json')
def reset_match(request): group = Group.objects.get(name='Scorekeepers') if group not in request.user.groups.all(): raise Http404 ss = ScoringSystem.objects.all()[0] match = ss.current_match timer = (match.actual_start + datetime.timedelta(seconds=151)) - tz_aware_now() if timer.days >= 0 and ss.task_id: task = abort_match.delay() revoke(ss.task_id, terminate=True) from celery.task.control import discard_all discard_all() else: prematch_lighting() match.reset() ScoringDevice.objects.all().update(on_center=False) for tower_name in ['low_red', 'high_red', 'low_blue', 'high_blue']: setattr(match, 'scorer_'+tower_name, None) for sd in ScoringDevice.objects.filter(tower__isnull=False): setattr(match, 'scorer_'+sd.tower.name, sd.scorer) match.save() return scorekeeper(request)
def mark_as_failed(self): """Sets the status of the job to failed.""" self.status = 2 self.date_completion = tz_aware_now() self.save()
def can_be_applied(self): # We have to use timezone-aware date-time objects because we # set USE_TZ=True in settings.py if self.is_open and self.change_allowed_date >= tz_aware_now(): return True return False
def change_application_approved(self, request, queryset): # got from django.contrib.admin.actions opts = self.model._meta app_label = opts.app_label if request.POST.get('post'): n = queryset.count() if n: if request.POST['status'] == 'True': queryset.update(approved=True, approved_by=request.user, approve_date=tz_aware_now()) status_string = _("approved") else: queryset.update(approved=False, approved_by=None, approve_date=None) status_string = _("rejected") # Log the change and send email to user msg = [] for application in queryset.all(): if logger.isEnabledFor(logging.DEBUG): logger.debug( "Başvuru %s: %s , request.user='******' , request.META['REMOTE_ADDR']='%s'" % (status_string, application, request.user, request.META["REMOTE_ADDR"])) # Get the site name to display in mail subject if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) # Prepeare email subject and body context = Context({ 'application': application.course, 'approval_date': application.approve_date, 'site': site.name, 'status_string': status_string }) subject = render_to_string( "admin/approval_email_subject.txt", context) body = render_to_string("admin/approval_email.txt", context) msg.append((subject, body, settings.DEFAULT_FROM_EMAIL, [ application.person.email, ])) # Send mail for all changed applications in bulk send_mass_mail(tuple(msg)) # Display a notification in admin page self.message_user( request, _("Successfully changed %(count)d %(items)s.") % { "count": n, "items": model_ngettext(self.opts, n) }) # Return None to display the change list page again. return None title = _("Are you sure?") if len(queryset) == 1: objects_name = force_unicode(opts.verbose_name) else: objects_name = force_unicode(opts.verbose_name_plural) courses = queryset.all() editable_objects = [] for course in courses: editable_objects.append(course.__unicode__()) context = { "title": title, "objects_name": objects_name, "editable_objects": [editable_objects], 'queryset': queryset, "opts": opts, "app_label": app_label, 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME, } # Display the confirmation page return TemplateResponse(request, 'admin/change_application_approved.html', context, current_app=self.admin_site.name)
def mark_as_result_synchronized(self): """Sets the status of the job to the one that marks that the result of the job has been handled.""" self.status = 4 self.date_completion = tz_aware_now() self.save()
def update_from_match_event(me): alliance = me.alliance tower = me.tower match = me.match level = me.level if '_' in tower.name: # low or high alliance tower if alliance in tower.name: # alliance scoring in own goal tl_1 = tower.towerlevel_set.get(level=1) if str(level) == str(1) or tl_1.state != alliance or 'low_' in tower.name: tl = tl_1 else: tl = tower.towerlevel_set.get(level=2) if tl.state == alliance or tl.state == 'off': me.dud = True me.save() else: # It is scorable if me.dud == True: me.dud = False me.save() tl.state = alliance tl.save() alliance_towers = TowerLevel.objects.filter(tower__name__contains='_'+alliance) alliance_towers_uncharged = alliance_towers.exclude(state=alliance) if not alliance_towers_uncharged.exists() \ and not getattr(match, alliance+'_center_active'): center = Tower.objects.get(name='center') low_center = center.towerlevel_set.get(level=1) off_color = 'blue' if alliance=='red' else 'red' setattr(match, alliance + '_center_active', True) this_start = tz_aware_now() if match.actual_start+datetime.timedelta(seconds=120) < this_start: this_start = match.actual_start + datetime.timedelta(seconds=120) if not getattr(match, off_color + '_center_active'): low_center.state = alliance else: low_center.state = 'purple' elif not getattr(match, off_color + '_center_active'): low_center.state = alliance else: low_center.state = 'purple' other_start = getattr(match, off_color + '_center_active_start') if (this_start - other_start).total_seconds() < 5.0: td = datetime.timedelta(seconds=5) this_start = other_start+td setattr(match, alliance + '_center_active_start', this_start) update_test_led(low_center) update_real_leds(low_center) alliance_towers.update(state='off') for tl_alliance in alliance_towers: update_test_led(tl_alliance) update_real_leds(tl_alliance) alliance_scorers = ScoringDevice.objects.filter(tower__name__contains='_'+alliance) alliance_scorers.update(on_center=True) else: update_test_led(tl) update_real_leds(tl) if alliance == 'red': match.red_score += SCORE_SETTINGS[level] match.red_score_pre_penalty += SCORE_SETTINGS[level] else: match.blue_score += SCORE_SETTINGS[level] match.blue_score_pre_penalty += SCORE_SETTINGS[level] else: # alliance attempting to descore descoring_alliance = alliance if descoring_alliance == 'red': descored_alliance = 'blue' else: descored_alliance = 'red' try: tl_2 = tower.towerlevel_set.get(level=2) except: tl = tower.towerlevel_set.get(level=1) tl_2 = False else: if int(level) == 1 or tl_2.state != descored_alliance or 'low_' in tower.name: tl = tower.towerlevel_set.get(level=1) else: tl = tl_2 if tl.state == descored_alliance and not \ (tl.level == 1 and tl_2 and tl_2.state == descored_alliance): tl.state = 'green' tl.save() update_test_led(tl) update_real_leds(tl) if me.dud == True: me.dud = False me.save() else: me.dud = True me.save() elif 'center' in tower.name: # scoring on center tower s = SCORE_SETTINGS[level] if me.undo_score: s = 0 - s if alliance == 'red': match.red_score += s match.red_score_pre_penalty += s else: match.blue_score += s match.blue_score_pre_penalty += s match.save()
def mark_as_deleted_on_glacier(self): """This method then sets the appropriate status for the Job if it takes to long to request the job output the job is deleted on Glacier.""" self.status = 3 self.date_completion = tz_aware_now() self.save()
def update_from_match_event(me): alliance = me.alliance tower = me.tower match = me.match level = me.level if '_' in tower.name: # low or high alliance tower if alliance in tower.name: # alliance scoring in own goal tl_1 = tower.towerlevel_set.get(level=1) if str(level) == str( 1) or tl_1.state != alliance or 'low_' in tower.name: tl = tl_1 else: tl = tower.towerlevel_set.get(level=2) if tl.state == alliance or tl.state == 'off': me.dud = True me.save() else: # It is scorable if me.dud == True: me.dud = False me.save() tl.state = alliance tl.save() alliance_towers = TowerLevel.objects.filter( tower__name__contains='_' + alliance) alliance_towers_uncharged = alliance_towers.exclude( state=alliance) if not alliance_towers_uncharged.exists() \ and not getattr(match, alliance+'_center_active'): center = Tower.objects.get(name='center') low_center = center.towerlevel_set.get(level=1) off_color = 'blue' if alliance == 'red' else 'red' setattr(match, alliance + '_center_active', True) this_start = tz_aware_now() if match.actual_start + datetime.timedelta( seconds=120) < this_start: this_start = match.actual_start + datetime.timedelta( seconds=120) if not getattr(match, off_color + '_center_active'): low_center.state = alliance else: low_center.state = 'purple' elif not getattr(match, off_color + '_center_active'): low_center.state = alliance else: low_center.state = 'purple' other_start = getattr( match, off_color + '_center_active_start') if (this_start - other_start).total_seconds() < 5.0: td = datetime.timedelta(seconds=5) this_start = other_start + td setattr(match, alliance + '_center_active_start', this_start) update_test_led(low_center) update_real_leds(low_center) alliance_towers.update(state='off') for tl_alliance in alliance_towers: update_test_led(tl_alliance) update_real_leds(tl_alliance) alliance_scorers = ScoringDevice.objects.filter( tower__name__contains='_' + alliance) alliance_scorers.update(on_center=True) else: update_test_led(tl) update_real_leds(tl) if alliance == 'red': match.red_score += SCORE_SETTINGS[level] match.red_score_pre_penalty += SCORE_SETTINGS[level] else: match.blue_score += SCORE_SETTINGS[level] match.blue_score_pre_penalty += SCORE_SETTINGS[level] else: # alliance attempting to descore descoring_alliance = alliance if descoring_alliance == 'red': descored_alliance = 'blue' else: descored_alliance = 'red' try: tl_2 = tower.towerlevel_set.get(level=2) except: tl = tower.towerlevel_set.get(level=1) tl_2 = False else: if int( level ) == 1 or tl_2.state != descored_alliance or 'low_' in tower.name: tl = tower.towerlevel_set.get(level=1) else: tl = tl_2 if tl.state == descored_alliance and not \ (tl.level == 1 and tl_2 and tl_2.state == descored_alliance): tl.state = 'green' tl.save() update_test_led(tl) update_real_leds(tl) if me.dud == True: me.dud = False me.save() else: me.dud = True me.save() elif 'center' in tower.name: # scoring on center tower s = SCORE_SETTINGS[level] if me.undo_score: s = 0 - s if alliance == 'red': match.red_score += s match.red_score_pre_penalty += s else: match.blue_score += s match.blue_score_pre_penalty += s match.save()
def change_application_approved(self, request, queryset): # got from django.contrib.admin.actions opts = self.model._meta app_label = opts.app_label if request.POST.get("post"): n = queryset.count() if n: if request.POST["status"] == "True": queryset.update(approved=True, approved_by=request.user, approve_date=tz_aware_now()) status_string = _("approved") else: queryset.update(approved=False, approved_by=None, approve_date=None) status_string = _("rejected") # Log the change and send email to user msg = [] for application in queryset.all(): if logger.isEnabledFor(logging.DEBUG): logger.debug( "Başvuru %s: %s , request.user='******' , request.META['REMOTE_ADDR']='%s'" % (status_string, application, request.user, request.META["REMOTE_ADDR"]) ) # Get the site name to display in mail subject if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) # Prepeare email subject and body context = Context( { "application": application.course, "approval_date": application.approve_date, "site": site.name, "status_string": status_string, } ) subject = render_to_string("admin/approval_email_subject.txt", context) body = render_to_string("admin/approval_email.txt", context) msg.append((subject, body, settings.DEFAULT_FROM_EMAIL, [application.person.email])) # Send mail for all changed applications in bulk send_mass_mail(tuple(msg)) # Display a notification in admin page self.message_user( request, _("Successfully changed %(count)d %(items)s.") % {"count": n, "items": model_ngettext(self.opts, n)}, ) # Return None to display the change list page again. return None title = _("Are you sure?") if len(queryset) == 1: objects_name = force_unicode(opts.verbose_name) else: objects_name = force_unicode(opts.verbose_name_plural) courses = queryset.all() editable_objects = [] for course in courses: editable_objects.append(course.__unicode__()) context = { "title": title, "objects_name": objects_name, "editable_objects": [editable_objects], "queryset": queryset, "opts": opts, "app_label": app_label, "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME, } # Display the confirmation page return TemplateResponse( request, "admin/change_application_approved.html", context, current_app=self.admin_site.name )