Exemple #1
0
def signal_processing_data(request):
    """
    Generates data for the monitor status page
    """
    junk = data._gen_now()

    sreadings = dict()
    for s_id in data.SENSOR_IDS:
        sreadings[s_id] = [None, None, None, None]
        try:
            sr = SensorReading.objects.filter(sensor__id=s_id).latest('reading_time')
            sreadings[s_id][0] = int(
                calendar.timegm(sr.reading_time.timetuple()) * 1000)
        except SensorReading.DoesNotExist:
            pass
        # TODO: magic number
        d = SRProfile.objects.filter(
            sensor_reading__sensor__id=s_id,
            sensor_reading__reading_time__gte=(
                datetime.datetime.now() - datetime.timedelta(1))
            ).aggregate(
            Avg('transaction_time'), 
            Min('transaction_time'),
            Max('transaction_time')) 
        sreadings[s_id][1] = int(d['transaction_time__avg'])
        sreadings[s_id][2] = d['transaction_time__min']
        sreadings[s_id][3] = d['transaction_time__max']
    return HttpResponse(simplejson.dumps({'sensor_readings': sreadings,
                                          'sensor_groups': data.SENSOR_GROUPS,
                                          'data_url': reverse(
                                              'energyweb.graph.views.signal_processing_data')
                                          + '?junk=' + junk}),
                        mimetype='application/json')
Exemple #2
0
def dynamic_graph_data(request, input_data):
    '''
    A view returning the JSON data used to populate the dynamic graph.
    '''
    # Set the maximum possible start time to two hours ago
    # to prevent excessive drawing of data
    max_time = datetime.datetime.now() -DYNAMIC_START_TIME
    start = max( datetime.datetime.utcfromtimestamp(int(int(input_data)/1000)) ,
                 max_time )
    
    # Grab the xy pairs
    data_dump = data._make_data_dump( calendar.timegm(start.timetuple()) ,
                        None,
                        'second*10')

    if not data_dump['no_results']:
        # Create the URL to refresh for more data
        junk = data._gen_now()
        data_url = reverse('energyweb.graph.views.dynamic_graph_data', \
                           kwargs={'input_data': \
                                   str(data_dump['last_record'])}) + \
                                   '?junk=' + junk
        data_dump['data_url'] = data_url
    
    json_serializer = serializers.get_serializer("json")()
    return HttpResponse(simplejson.dumps(data_dump),
                        mimetype='application/json')
Exemple #3
0
def statistics_table_data(request):
    '''
    A view returning the JSON data used to populate the averages table.
    '''
    all_averages = data._get_averages()

    data_url = reverse('energyweb.graph.views.statistics_table_data') \
               +'?junk=' + data._gen_now()

    # Create the final return dictionary
    d = {
        'no_results': False,
        'min_averages': all_averages['minute'],
        'week_averages': all_averages['week'],
        'month_averages': all_averages['month'],
        'sensor_groups': data.SENSOR_GROUPS,
        'data_url': data_url
        }
             
    # Use json to transfer the data from Python to Javascript
    json_serializer = serializers.get_serializer("json")()
    return HttpResponse(simplejson.dumps(d),
                        mimetype='application/json')
Exemple #4
0
def data_access(request):
    '''                                                                                   
    A view returning the HTML for the unrestricted data download page.
    Two return possibilities:
       1) Did not input data yet
       2) Input valid data
    '''
    # Increase the viewCount for today
    data.increase_count(DATA_ACCESS)

    def _request_valid(request):
        return request.method == 'GET' \
               and 'start_0' in request.GET \
               and 'end_0' in request.GET \
               and 'res' in request.GET

    def _clean_input(get):
        # *_0 gives date, *_1 gives time in 12 hr w/ AM or PM
        for field in ('start_0', 'start_1', 'end_0', 'end_1'):
            if field in ('start_1', 'end_1'):
                # Allow e.g. pm or p.m. instead of PM
                get[field] = get[field].upper().replace('.', '')
                # Allow surrounding whitespace
            get[field] = get[field].strip()
        return get

    def _show_only_form():
        '''
        Refuse to show them a graph until they give you good parameters
        '''
        now = datetime.datetime.now()
        one_day_ago = now - datetime.timedelta(1)
        form = data.CustomGraphForm(initial={
            'start': one_day_ago,
            'end': now
        })
        return render_to_response('graph/maintenance/data_access.html',
            {'form_action': reverse('energyweb.graph.views.data_access'),
             'form': form},
            context_instance=RequestContext(request))
    # BEGIN Case 1
    if not _request_valid(request):
        return _show_only_form()

    _get = _clean_input(request.GET.copy())
    form = data.CustomGraphForm(_get)

    if not form.is_valid():
        return _show_only_form()

    # We've passed the checks, now can display the graph!
    # The following functions are for setting the various arguments
    start = form.cleaned_data['start']
    end = form.cleaned_data['end']
    res = form.cleaned_data['computed_res']

    int_start = int(calendar.timegm(start.timetuple()))
    int_end = int(calendar.timegm(end.timetuple()))
    junk = data._gen_now()
    keyword_args = {'start': str(int_start),
                    'end': str(int_end),
                    'res': res}

    # generate the URLs for data dumps
    download_url = reverse('energyweb.graph.views.download_csv',
                           kwargs=keyword_args) + '?junk=' + junk

    final_args = {
                  'download_url': download_url,
                  'form': form,
                  'form_action': reverse('energyweb.graph.views.data_access'),
                  'res': res}

    return render_to_response('graph/maintenance/data_access_graph.html',
                              final_args,
                              context_instance=RequestContext(request))
Exemple #5
0
def static_graph(request):
    '''
    A view returning the HTML for the static (custom-time-period) graph.
    Several return possibilities:
       1) Did not input data yet
       2) Input invalid data
       3) Input valid data
    They only get a graph back if they have input valid data!
    '''
    # Increase the viewCount for today
    data.increase_count(CUSTOM)

    def _request_valid(request):
        return request.method == 'GET' \
               and 'start_0' in request.GET \
               and 'end_0' in request.GET \
               and 'res' in request.GET
    
    def _clean_input(get):
        # *_0 gives date, *_1 gives time in 12 hr w/ AM or PM
        for field in ('start_0', 'start_1', 'end_0', 'end_1'):
            if field in ('start_1', 'end_1'):
                # Allow e.g. pm or p.m. instead of PM
                get[field] = get[field].upper().replace('.', '')
                # Allow surrounding whitespace
            get[field] = get[field].strip()
        return get
    
    def _show_only_form():
        '''
        Refuse to show them a graph until they give you good parameters
        '''
        now = datetime.datetime.now()
        one_day_ago = now - datetime.timedelta(1)
        form = data.StaticGraphForm(initial={
            'start': one_day_ago,
            'end': now
        })
        return render_to_response('graph/static_graph_form.html',
            {'form_action': reverse('energyweb.graph.views.static_graph'),
             'form': form},
            context_instance=RequestContext(request))
    # BEGIN Case 1

    if not _request_valid(request):
        return _show_only_form()
    # BEGIN Case 2
    
    _get = _clean_input(request.GET.copy())
    form = data.StaticGraphForm(_get)

    if not form.is_valid():
        return _show_only_form()
    # We've passed the checks, now can display the graph!

    # The following functions are for setting the various arguments
    start = form.cleaned_data['start']
    end = form.cleaned_data['end']
    res = form.cleaned_data['computed_res']
    
    # int_* is in seconds. REMEMBER highcharts needs milliseconds!
    int_start = int(calendar.timegm(start.timetuple()))
    int_end = int(calendar.timegm(end.timetuple()))

    junk = data._gen_now()
    keyword_args = {'start': str(int_start), 
                    'end': str(int_end), 
                    'res': res}
    
    # generate the URLs for data dumps
    data_url = reverse('energyweb.graph.views.static_graph_data',
                       kwargs=keyword_args) + '?junk=' + junk
    
    download_url = reverse('energyweb.graph.views.download_csv',
                           kwargs=keyword_args) + '?junk=' + junk

    final_args = {'start': int_start*1000,
                  'end': int_end*1000,
                  'data_url': data_url,
                  'download_url': download_url,
                  'form': form,
                  'form_action': reverse('energyweb.graph.views.static_graph'),
                  'res': RESOLUTION_DELTAS[res].seconds,
                  'timedelta_ms': (int_end-int_start)*1000}
    
    return render_to_response('graph/static_graph.html', 
                              final_args,
                              context_instance=RequestContext(request))