Exemplo n.º 1
0
def update_tokens(request):
    """
    We need to record these updates to token states and provide a
    way to view this in the Gateway Interface.
    """
    session = DBSession()
    data = simplejson.loads(request.body)
    if not 'device_id' in data:
        return Response('You must provide an device_id')
    device = session.query(Device)\
        .filter_by(device_id=data['device_id']).first()
    if device:
        for i in data['tokens']:
            token = session.query(Token)\
                .filter_by(token=i['token_id']).first()
            if token:
                circuit = session.query(Circuit)\
                    .filter_by(pin=i['account_id']).first()
                if circuit:
                    job = AddCredit(token.value, circuit, token)
                    session.add(job)
                token.state = 5
                session.merge(token)
        session.flush()
        return Response('Ok')
    else:
        return Response('You must provide a valid device_id')
def check_meters(env):
    """
    Function to check the state of a meter. Run via the command line

      python process_check_meters.py config.ini

    or via a cron job.
    """
    sql_settings = env["registry"].settings["sqlalchemy.url"]
    #  initialze the database and bind the models to the connection.
    #  bad things happen if we don't call this.
    initialize_sql(sql_settings)
    session = DBSession()
    meters = session.query(Meter).all()

    for meter in meters:
        time_difference = datetime.now() - timedelta(hours=1)
        log.info("Check meter %s" % meter)
        for c in meter.get_circuits():
            log.info("--> Check for circuit %s " % c)
            last_log = c.get_last_log()
            # if we have a log
            # often circuits are configured and we never hear from them.
            if last_log is not None:
                if time_difference > last_log.gateway_time:
                    alert = UnresponsiveCircuit(datetime.now(), meter, c, last_log.gateway_time)
                    session.add(alert)
            else:
                log.info("We have not heard from circuit %s" % c.id)
Exemplo n.º 3
0
def make_tokens(request):
    """
    A view function that allows the vendor application to request to
    new tokens.
    """
    session = DBSession()
    batch = TokenBatch()
    session.add(batch)
    session.flush()
    data = simplejson.loads(request.body)
    if not 'device_id' in data:
        return Response('You must provide an device_id')
    else:
        device = session.query(
            Device).filter_by(device_id=data['device_id']).first()
        if device:
            if not 'tokens' in data:
                return Response('You must provide an amount of tokens')
            for group in data['tokens']:
                for i in range(0, group['count']):
                    token = Token(Token.get_random(),
                                  batch=batch,
                                  value=group['denomination'])
                    session.add(token)
                    session.flush()
            return Response(
                [{'token_id': int(token.token),
                  'denomination':
                  float(token.value)} for token in batch.getTokens()])
        else:
            return Response('Not a valid device')
Exemplo n.º 4
0
def login(request):
    """
    View function to allow users to log into the Gateway auth's
    system. Checks the sanity of the user's input and then makes sure
    that we have a the user in the database.

    Returns a HTTPFound to the user's last url.
    """
    session = DBSession()
    came_from = request.params.get('came_from', '/')
    errors = []
    name = ''
    if request.method == 'POST':
        name = request.POST['name']
        # query the database making sure that a user with both the
        # username and password exists.
        user = session.query(User).filter_by(name=name).first()
        if user is None:
            errors.append(
                u'Unable to find an user matching (%s)' % name
                )
            return {'errors': errors, 'name': '', 'came_from': came_from }
        if user.check_password(request.params.get('password')):
            # if we have a user, send them on their way.
            # else allow them to try again.
            headers = remember(request, user.name)
            return HTTPFound(
                location='%s' % came_from,
                headers=headers
                )
        else:
            errors.append(u'Wrong password, please try again')
            return {'errors': errors, 'name': name, 'came_from': came_from}
        errors.append(u'Unable to log in, please try again')
    return {'errors': errors, 'name': name, 'came_from': came_from }
Exemplo n.º 5
0
def admin_user(request):
    """
    Function that displays the main user admin interface of the
    Gateway.  Right now displays a list of all the users and gives the
    user the option to add a new user.
    """
    session = DBSession()
    return {'users': session.query(User).all()}
Exemplo n.º 6
0
def group_finder(user_id, request):
    """
    """
    session = DBSession()
    user = session.query(User).filter_by(name=user_id).first()
    if user:
        if user.group:
            return [user.group.name]
Exemplo n.º 7
0
def list_metes(request):
    """
    Lists all of the active meters currently configure in the
    Gateway. TODO, need to limit this view to only the meters
    associated with a user's org.
    """
    session = DBSession()
    meters = session.query(Meter).all()
    return {'meters': meters}
Exemplo n.º 8
0
def edit_user(request):
    """
    Allows a user to edit the profile. This should be limited...
    """
    session = DBSession()
    user = get_object_or_404(User, request.matchdict.get('user'))
    form = EditUserForm(request.POST, obj=user)
    form.group.query = session.query(Group).all()
    if request.method == 'POST' and form.validate():
        group = session.query(Group).get(form.group_id.data)
        user.name = form.name.data
        user.email = form.email.data
        user.group = group
        session.merge(user)
        return HTTPFound(location=request.route_url('admin-users'))
    else:
        return {'user': user, 'form': form}
Exemplo n.º 9
0
def get_object_or_404(kls, id):
    """
    Function to find an object from the database by its id.
    Args: class for query the database for
          id of the object you want.
    Returns:
       The Object if it is found in the database.
       Or a 404 is the query resultls in None

    """
    if id is None:
        raise HTTPNotFound('No id provided')
    session = DBSession()
    obj = session.query(kls).get(id)
    if obj is None:
        raise HTTPNotFound()
    else:
        return obj
Exemplo n.º 10
0
def new_meter(request):
    """
    View function that allows users to add a new meter to the
    Gateway's database.
    """
    session = DBSession()
    form = AddMeterForm(request.POST)
    form.time_zone.query = session.query(TimeZone).all()

    def post_validate(form):
        meter = Meter(form.name.data,
                      form.phone.data,
                      form.location.data,
                      form.time_zone.data,
                      True,
                      datetime.now(),
                      form.battery_capacity.data,
                      form.panel_capacity.data)
        session.add(meter)
        start_ip_address = 200
        for x in range(0, int(form.number_of_circuits.data)):
            ip_address = '192.168.1.%s' % (start_ip_address + x)
            # create an account for each circuit
            account = Account('default-account', '', form.language.data)
            session.add(account)
            # create the circuit1
            circuit = Circuit(
                meter,
                account,
                datetime.now(),
                Circuit.get_pin(),
                form.pmax.data,
                form.emax.data,
                ip_address,
                0,
                0)
            session.add(circuit)
        # flush the session so i can send the user to the meter's id
        session.flush()
        return HTTPFound(
            location=request.route_url('show-meter', meter_id=meter.id)
            )
    return process_form(request, form, post_validate)
Exemplo n.º 11
0
def find_message_gaps(env, start_time_str, end_time_str):
    """
    Arguments:
          start_time_str: YYYY-MM-DD
          end_time_str:   YYYY-MM-DD
          env: Pyramid context

    Values: returns None

    Purpose:

    """
    sql_settings = env['registry'].settings['sqlalchemy.url']
    #  initialze the database and bind the models to the connection.
    #  bad things happen if we don't call this.
    initialize_sql(sql_settings)
    session = DBSession()

    try:
        start_date = datetime.strptime(start_time_str, time_format)
    except:
        raise NameError(time_error_msg)

    try:
        end_date = datetime.strptime(end_time_str, time_format)
    except:
        raise NameError(time_error_msg)

    if start_date >= end_date:
        raise NameError('start must be before end')

    time_diff = end_date - start_date
    time_diff_hours = ((time_diff.total_seconds() / 60) / 60)
    print 'Find gaps for %s ' % time_diff_hours

    logs = session.query(PrimaryLog)\
        .filter(PrimaryLog.meter_time >= start_date)\
        .filter(PrimaryLog.meter_time < end_date)

    print 'Total number of logs %s ' % logs.count()
    excepted = len(session.query(Circuit).all()) * time_diff_hours * 2 
    print (logs.count() / excepted)
Exemplo n.º 12
0
def new_user(request):
    """
    Function to add a new user to the Gateway's auth system.
    Requires the user to provide a user name, password and email address.
    The group for the new user is give a list to select from.

    TODO, add support for org's once they are add to the models.
    """
    session = DBSession()
    form = AddUserForm(request.POST)
    form.group.query = session.query(Group).all()
    if request.method == 'POST' and form.validate():
        user = User(form.name.data,
                    form.password.data,
                    form.email.data,
                    form.group.data)
        session.add(user)
        return HTTPFound(location=request.route_url('admin-users'))
    else:
        return {'form': form}
Exemplo n.º 13
0
 def wrap(message):
     session = DBSession()
     number = message.get('phone-number', None)
     if number:
         meter = session.query(Meter).filter_by(phone=number).first()
     return func(message, meter)