Ejemplo n.º 1
0
def delete(ctx, appeui):
    """delete an application property.
    
    Args:
        ctx (Context): Click context
        appeui (str): Application EUI string
    """
    if '.' in appeui:
        appeui = str(hexStringInt(str(appeui)))

    # Translate kwargs to dict
    args = dict(item.split('=', 1) for item in ctx.args)

    # Port (int) is mandatory
    if not 'port' in args.keys():
        click.echo("Missing the port argument.")
        return
    if not isinstance(args['port'], (int, long)):
        click.echo("Port argument must be an integer.")
        return

    # Add the kwargs to payload as a dict
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
    payload.update([args['port'].split('=')])
        
    # Perform a DELETE on /property/appeui endpoint
    url = 'http://{}/api/v1.0/property/{}'.format(server, appeui)
    if restRequest(server, url, 'delete', payload, 200) is None:
        return
Ejemplo n.º 2
0
def add(ctx, host):
    """add a gateway.
    
    Args:
        ctx (Context): Click context
        host (str): Gateway IP address
    """
    # Translate args to dict
    args = dict(item.split('=', 1) for item in ctx.args)

    required = {'name', 'eui', 'enabled', 'power'}
    missing = [item for item in required if item not in args.keys()]
    if missing:
        if len(missing) == 1:
            click.echo("Missing argument " + missing[0])
        else:
            click.echo("Missing arguments: " + ' '.join(missing))
        return

    args['enabled'] = True if args['enabled'] == 'yes' else False
    args['eui'] = hexStringInt(str(args['eui']))

    # Create the payload
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token'], 'host': host}
    payload.update(args)

    # Perform a POST on /gateways endpoint
    url = 'http://' + server + '/api/v1.0/gateways'
    if restRequest(server, url, 'post', payload, 201) is None:
        return
Ejemplo n.º 3
0
def set(ctx, appeui):
    """modify an application.
    
    Args:
        ctx (Context): Click context
        appeui (str): Device EUI string
    """

    if '.' in appeui:
        appeui = str(hexStringInt(str(appeui)))

    args = dict(item.split('=', 1) for item in ctx.args)
    if 'appkey' in args:
        args['appkey'] = hexStringInt(str(args['appkey']))

    # Enabled is a yes or no
    if 'enabled' in args:
        args['enabled'] = args['enabled'].lower() == 'yes'

    # Add the kwargs to payload as a dict
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
    
    for item in args:
        payload.update(args)
        
    # Perform a PUT on /app/appeui endpoint
    url = 'http://{}/api/v1.0/app/{}'.format(server, appeui)
    if restRequest(server, url, 'put', payload, 200) is None:
        return
Ejemplo n.º 4
0
def set(ctx, deveui):
    """modify a device.
    
    Args:
        ctx (Context): Click context
        deveui (str): Device EUI string
    """

    deveui = hexStringInt(str(deveui))
    
    # Translate kwargs to dict
    args = dict(item.split('=', 1) for item in ctx.args)
    
    # Enabled is a yes or no
    if 'enabled' in args:
        args['enabled'] = True if args['enabled'].lower() == 'yes' else False
    
    if 'class' in args:
        args['devclass'] = args.pop('class').lower()
        
    if 'nwkskey' in args:
        args['nwkskey'] = hexStringInt(str(args['nwkskey']))
    
    if 'appskey' in args:
        args['appskey'] = hexStringInt(str(args['appskey']))

    # Add the args to payload
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
    payload.update(args)
    
    # Perform a PUT on /device/deveui endpoint
    url = 'http://{}/api/v{}/device/{}'.format(server, version, deveui)
    if restRequest(server, url, 'put', payload, 200) is None:
        return
Ejemplo n.º 5
0
def add(ctx, appeui):
    """add an application property.
    
    Args:
        ctx (Context): Click context
        appeui (str): Application EUI string
    """
    if '.' in appeui:
        appeui = str(hexStringInt(str(appeui)))
    
    # Translate kwargs to dict
    args = dict(item.split('=', 1) for item in ctx.args)
    
    # Check for required args
    required = ['port', 'name', 'type']
    
    missing = [item for item in required if item not in args.keys()]
    if missing:
        if len(missing) == 1:
            click.echo("Missing argument " + missing[0])
        else:
            click.echo("Missing arguments: " + ' '.join(missing))
        return

    # Create the payload
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token'], 'appeui': appeui}
    payload.update(args)
    
    # Perform a POST on /propertys endpoint
    url = 'http://{}/api/v{}/propertys'.format(server, str(version))
    if restRequest(server, url, 'post', payload, 201) is None:
        return
Ejemplo n.º 6
0
def modify(ctx, host):
    """modify a gateway.
    
    Args:
        ctx (Context): Click context
        host (str): Gateway IP address
    """
    server = ctx.obj['server']
    # Add the kwargs to payload as a dict
    payload = {'token': ctx.obj['token']}
    for item in ctx.args:
        payload.update([item.split('=')])

    # Convert EUI to integer
    if 'eui' in payload:
        payload['eui'] = hexStringInt(str(payload['eui']))

    # Enabled is a yes or no
    if 'enabled' in payload:
        payload['enabled'] = payload['enabled'].lower() == 'yes'

    # Perform a PUT on /gateway/host endpoint
    url = 'http://' + server + '/api/v1.0/gateway/' + host
    if restRequest(server, url, 'put', payload, 200) is None:
        return
Ejemplo n.º 7
0
def show(ctx, appeui):
    """show an application, or all applications.
    
    Args:
        ctx (Context): Click context
        appeui (str): Application EUI
    """
    if '.' in appeui:
        appeui = str(hexStringInt(str(appeui)))
    
    # Form the url and payload
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
    url = 'http://{}/api/v{}'.format(server, str(version))
    url += '/apps' if appeui == 'all' else '/app/{}'.format(appeui)
    
    # Make the request
    data = restRequest(server, url, 'get', payload, 200)
    if data is None:
        return
    
    # Single application
    if appeui != 'all':
        a = data
        indent = ' ' * 10
        if a['appinterface_id'] == 0:
            a['appinterface_id'] = '-'
        if a['domain'] is None:
            a['domain'] = '-'
        click.echo('Application EUI: ' + euiString(a['appeui']))
        click.echo('{}name: {}'.format(indent, a['name']))
        click.echo('{}domain: {}'.format(indent, a['domain']))
        click.echo('{}fport: {}'.format(indent, a['fport']))
        click.echo('{}interface: {}'.format(indent, a['appinterface_id']))
        if a['appinterface_id'] != '-':
            click.echo('{}Properties:'.format(indent))
            properties = sorted(a['properties'].values(), key=lambda k: k['port'])
            for p in properties:
                click.echo('{}  {}  {}:{}'.format(indent, p['port'], p['name'], p['type']))
        return
        
    # All applications
    click.echo('{:14}'.format('Application') + \
               '{:24}'.format('AppEUI') + \
               '{:15}'.format('Domain') + \
               '{:6}'.format('Fport') + \
               '{:10}'.format('Interface'))
    for i,a in data.iteritems():
        if a['appinterface_id'] == 0:
            a['appinterface_id'] = '-'
        if a['domain'] is None:
            a['domain'] = '-'
        click.echo('{:13.13}'.format(a['name']) + ' ' + \
                   '{:23}'.format(euiString(a['appeui'])) +  ' ' + \
                   '{:14.14}'.format(a['domain']) + ' ' + \
                   '{:5.5}'.format(str(a['fport'])) + ' ' + \
                   '{:10}'.format(str(a['appinterface_id'])))
Ejemplo n.º 8
0
def add(ctx, deveui):
    """add a device.
    
    Args:
        ctx (Context): Click context
        deveui (str): Device EUI string
    """
    if '.' in deveui:
        deveui = str(hexStringInt(str(deveui)))
    
    # Translate kwargs to dict
    args = dict(item.split('=', 1) for item in ctx.args)
    
    def check_missing(args, required):
        missing = [item for item in required if item not in args.keys()]
        if not missing:
            return True
        if len(missing) == 1:
            click.echo("Missing argument " + missing[0])
        else:
            click.echo("Missing arguments: " + ' '.join(missing))
        return False

    required = ['name', 'class', 'enabled', 'otaa', 'appeui']
    if not check_missing(args, required):
        return
        
    # Convert appeui 
    args['appeui'] = hexStringInt(str(args['appeui']))

    # Convert class
    args['devclass'] = args.pop('class').lower()
    
    # Enabled is a yes or no
    args['enabled'] = True if args['enabled'].lower() == 'yes' else False
        
    # If OTAA is false, we must have devaddr, nwkskey and appskey
    args['otaa'] = True if args['otaa'].lower() == 'yes' else False
    if not args['otaa']:
        required = ['appskey', 'nwkskey', 'devaddr']
        if not check_missing(args, required):
            return
        for r in required:
            args[r] = hexStringInt(str(args[r]))

    # Create the payload
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token'], 'deveui': deveui}
    payload.update(args)
    
    # Perform a POST on /devices endpoint
    url = 'http://{}/api/v{}/devices'.format(server, version)
    if restRequest(server, url, 'post', payload, 201) is None:
        return
Ejemplo n.º 9
0
def show(ctx, id):
    """show an interface, or all interfaces.
    
    Args:
        ctx (Context): Click context
        id (int): Application interface ID
    """
    # Form the url and payload
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
    url = 'http://{}/api/v{}'.format(server, str(version))
    url += '/interfaces' if id == 'all' else '/interface/{}'.format(id)

    # Make the request
    data = restRequest(server, url, 'get', payload, 200)
    if data is None:
        return

    # All interfaces
    if id == 'all':
        click.echo('{:4}'.format('ID') + \
                   '{:24}'.format('Name') + \
                   '{:15}'.format('Type'))
        for i, a in sorted(data.iteritems()):
            if a['type'] == 'AzureIotHttps':
                a['type'] = 'Azure HTTPS'
            click.echo('{:3}'.format(a['id']) + ' ' + \
                       '{:23}'.format(a['name']) +  ' ' + \
                       '{:14}'.format(a['type']))
        return

    # Single interface
    i = data
    indent = ' ' * 10
    started = 'Started' if i['started'] else 'Stopped'

    if i['type'] == 'Reflector':
        click.echo('{}name: {}'.format(indent, i['name']))
        click.echo('{}type: {}'.format(indent, i['type']))
        click.echo('{}status: {}'.format(indent, started))

    elif i['type'] == 'AzureIotHttps':
        protocol = 'HTTPS'
        click.echo('{}name: {}'.format(indent, i['name']))
        click.echo('{}protocol: {}'.format(indent, protocol))
        click.echo('{}key name: {}'.format(indent, i['keyname']))
        click.echo('{}key value: {}'.format(indent, i['keyvalue']))
        click.echo('{}Polling interval: {} minutes'.format(
            indent, i['poll_interval']))
        click.echo('{}status: {}'.format(indent, started))

    return
Ejemplo n.º 10
0
def delete(ctx, host):
    """delete a gateway.
    
    Args:
        ctx (Context): Click context
        host (str): Gateway IP address
    """
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}

    # Perform a DELETE on /gateway/host endpoint
    url = 'http://' + server + '/api/v1.0/gateway/' + host
    if restRequest(server, url, 'delete', payload, 200) is None:
        return
Ejemplo n.º 11
0
def delete(ctx, id):
    """delete an interface.
    
    Args:
        ctx (Context): Click context
        id (str): Application interface id
    """
    # Add the kwargs to payload as a dict
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}

    # Perform a DELETE on /interface/id endpoint
    url = 'http://{}/api/v1.0/interface/{}'.format(server, id)
    if restRequest(server, url, 'delete', payload, 200) is None:
        return
Ejemplo n.º 12
0
def add(ctx, type):
    """add an interface.
    
    Args:
        ctx (Context): Click context
        iftype (str): Application interface type
    """

    # Translate kwargs to dict
    args = dict(item.split('=', 1) for item in ctx.args)

    iftype = type.lower()
    types = {'reflector', 'azure', 'filetext'}

    # Check for required args
    if not iftype in types:
        click.echo("Unknown interface type")
        return

    required = {
        'reflector': ['name'],
        'filetext': ['name', 'file'],
        'azure': ['protocol', 'name', 'iothost', 'keyname', 'keyvalue']
    }

    missing = [item for item in required[iftype] if item not in args.keys()]

    if type == 'azure' and 'protocol' == 'https' and not 'pollinterval' in args.keys(
    ):
        missing.append('pollinterval')

    if missing:
        if len(missing) == 1:
            click.echo("Missing argument " + missing[0])
        else:
            click.echo("Missing arguments: " + ' '.join(missing))
        return

    # Create the payload
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token'], 'type': iftype}
    payload.update(args)

    # Perform a POST on /apps endpoint
    url = 'http://{}/api/v{}/interfaces'.format(server, str(version))
    if restRequest(server, url, 'post', payload, 201) is None:
        return
Ejemplo n.º 13
0
def state(ctx, host, enabled):
    """Enable or disable a gateway.
    
    Args:
        ctx (Context): Click context
        host (str): Gateway IP address
        enabled (bool): Enable/disable flag
    """
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token'], 'enabled': enabled}

    # Perform a PUT on /gateway/host endpoint
    url = 'http://' + ctx.obj['server'] + '/api/v1.0/gateway/' + host
    if restRequest(server, url, 'put', payload, 200) is None:
        return

    e = 'enabled' if enabled else 'disabled'
Ejemplo n.º 14
0
def delete(ctx, deveui):
    """delete a device.
    
    Args:
        ctx (Context): Click context
        deveui (str): Device EUI string
    """
    if '.' in deveui:
        deveui = str(hexStringInt(str(deveui)))

    # Add the kwargs to payload as a dict
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
        
    # Perform a DELETE on /device/deveui endpoint
    url = 'http://{}/api/v{}/device/{}'.format(server, version, deveui)
    if restRequest(server, url, 'delete', payload, 200) is None:
        return
Ejemplo n.º 15
0
def delete(ctx, appeui):
    """delete an application.
    
    Args:
        ctx (Context): Click context
        appeui (str): Application EUI string
    """
    if '.' in appeui:
        appeui = str(hexStringInt(str(appeui)))

    # Add the kwargs to payload as a dict
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
        
    # Perform a DELETE on /app/appeui endpoint
    url = 'http://{}/api/v1.0/app/{}'.format(server, appeui)
    if restRequest(server, url, 'delete', payload, 200) is None:
        return
Ejemplo n.º 16
0
def show(ctx, host):
    """show a gateway, or all gateways
    
    Args:
        ctx (Context): Click context
        host (str): Gateway IP address
    """
    # Form the url and payload
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
    if host == 'all':
        url = 'http://' + server + '/api/v' + str(version) + \
              '/gateways'
    else:
        url = 'http://' + server + '/api/v' + str(version) + \
              '/gateway/' + host

    # Make the request
    data = restRequest(server, url, 'get', payload, 200)
    if data is None:
        return

    # Print a gateway
    if host != 'all':
        g = data
        status = 'enabled' if g['enabled'] else 'disabled'
        indent = ' ' * 10
        click.echo(g['host'] + ': ' + g['name'])
        click.echo(indent + 'eui ' + euiString(g['eui']))
        click.echo(indent + 'power: ' + str(g['power']) + ' dBm')
        click.echo(indent + 'status: ' + status)
        return

    # Print all gateways
    click.echo('{:15}'.format('Gateway') + '{:17}'.format('IP-Address') + \
               '{:24}'.format('EUI') + \
               '{:9}'.format('Enabled') + '{:12}'.format('Power-dBm'))
    for i, g in data.iteritems():
        enabled = 'Yes' if g['enabled'] else 'No'
        click.echo('{:14.14}'.format(g['name']) + ' ' + \
                   '{:17}'.format(g['host']) + \
                   '{:24}'.format(euiString(g['eui'])) + \
                   '{:9}'.format(enabled) + \
                   '{:2}'.format(g['power']))
Ejemplo n.º 17
0
def show(ctx):
    """show the system configuration.
    
    Args:
        ctx (Context): Click context
    """

    # Form the url and payload
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
    url = 'http://{}/api/v{}/system'.format(server, str(version))

    # Make the request
    data = restRequest(server, url, 'get', payload, 200)
    if data is None:
        return

    # Single application
    c = data
    indent = ' ' * 10
    click.echo('System: {} at {}'.format(c['name'], server))
    click.echo('{}Network interface: {}'.format(indent, c['listen']))
    click.echo('{}LoraWAN port: {}'.format(indent, c['port']))
    click.echo('{}Web server port: {}'.format(indent, c['webport']))
    click.echo('{}Frequency band: {}'.format(indent, c['freqband']))
    click.echo('{}Network ID: 0x{}'.format(indent,
                                           intHexString(c['netid'], 3, sep=2)))
    click.echo('{}OTAA Address Range: 0x{} - 0x{}'.format(
        indent, devaddrString(c['otaastart']), devaddrString(c['otaaend'])))
    t = 'Yes' if c['adrenable'] else 'No'
    click.echo('{}ADR enabled: {}'.format(indent, t))
    if c['adrenable']:
        click.echo('{}ADR margin: {} dB'.format(indent, c['adrmargin']))
        click.echo('{}ADR cycle time: {} s'.format(indent, c['adrcycletime']))
        click.echo('{}ADR message time: {} s'.format(indent,
                                                     c['adrmessagetime']))
    t = 'Yes' if c['fcrelaxed'] else 'No'
    click.echo('{}Relaxed frame count: {}'.format(indent, t))
    t = 'Yes' if c['macqueueing'] else 'No'
    click.echo('{}MAC queueing: {}'.format(indent, t))
    if c['macqueueing']:
        click.echo('{}MAC queue limit: {} s'.format(indent,
                                                    c['macqueuelimit']))
    return
Ejemplo n.º 18
0
def state(ctx, deveui, enabled):
    """Issue a PUT request to enable or disable a device.
    
    Args:
        ctx (): Click context
        deveui (int): Device EUI
        enabled (bool): Enable/disable flag
    """
    if ':' in deveui:
        deveui = str(hexStringInt(str(deveui)))
        
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token'],
               'enabled': enabled}
    
    # Perform a PUT on /device/deveui endpoint
    url = 'http://{}/api/v{}/device/{}'.format(server, version, deveui)
    if restRequest(server, url, 'put', payload, 200) is None:
        return

    e = 'enabled' if enabled else 'disabled'
Ejemplo n.º 19
0
def set(ctx, id):
    """modify an interface.
    
    Args:
        ctx (Context): Click context
        id (str): App interface id
    """

    # Add the kwargs to payload as a dict
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
    for item in ctx.args:
        payload.update([item.split('=')])

    # Enabled is a yes or no
    if 'enabled' in payload:
        payload['enabled'] = payload['enabled'].lower() == 'yes'

    # Perform a PUT on /app/appeui endpoint
    url = 'http://{}/api/v1.0/interface/{}'.format(server, id)
    if restRequest(server, url, 'put', payload, 200) is None:
        return
Ejemplo n.º 20
0
def set(ctx):
    """set system configuration parameters.
    
    Args:
        ctx (Context): Click context
    """
    # Translate kwargs to dict
    args = dict(item.split('=', 1) for item in ctx.args)

    if not args:
        return

    # Check for valid args
    valid = {
        'name', 'listen', 'port', 'webport', 'apitoken', 'freqband', 'netid',
        'duplicateperiod', 'fcrelaxed', 'otaastart', 'otaaend', 'macqueueing',
        'macqueuelimit', 'adrenable', 'adrmargin', 'adrcycletime',
        'adrmessagetime'
    }
    bool_args = {'fcrelaxed', 'adrenable', 'macqueueing'}
    for arg, param in args.items():
        if not arg in valid:
            click.echo('Invalid argument: {}'.format(arg))
            return
        if arg in bool_args:
            args[arg] = True if param.lower() == 'yes' else False
        if arg in {'netid', 'otaastart', 'otaaend'}:
            args[arg] = hexStringInt(str(param))

    # Form the url and payload
    server = ctx.obj['server']
    url = 'http://{}/api/v{}/system'.format(server, str(version))
    payload = {'token': ctx.obj['token']}
    payload.update(args)

    # Make the request
    data = restRequest(server, url, 'put', payload, 200)
    if data is None:
        return
Ejemplo n.º 21
0
def show(ctx, deveui):
    """show a device, or all devices.
    
    Args:
        ctx (Context): Click context
        deveui (str): Device EUI string
    """
    if '.' in deveui:
        deveui = str(hexStringInt(str(deveui)))
    
    # Form the url and payload
    server = ctx.obj['server']
    payload = {'token': ctx.obj['token']}
    url = 'http://{}/api/v{}'.format(server, version)
    url += '/devices' if deveui == 'all' else '/device/{}'.format(deveui)
    
    # Make the request
    data = restRequest(server, url, 'get', payload, 200)
    if data is None:
        return
    
    # Single device
    if deveui != 'all':
        d = data
        indent = ' ' * 10
        enable = 'enabled' if d['enabled'] else 'disabled'
        drate = d['tx_datr'] if d['tx_datr'] else 'N/A'
        nwkid = hex(d['devaddr'] >> 25)
        snrav = '{0:.2f} dBm'.format(d['snr_average']) if d['snr_average'] else 'N/A'
        appname = d['appname'] if d['appname'] else 'N/A'
        lat = '{0:.4f}'.format(d['latitude']) if d['latitude'] else 'N/A'
        lon = '{0:.4f}'.format(d['longitude']) if d['longitude'] else 'N/A'
        activ = 'Over the air (OTAA)' if d['otaa'] else 'Personalization (ABP)'
        click.echo('Device EUI: ' + euiString(d['deveui']))
        click.echo(indent + 'device address ' + devaddrString(d['devaddr']) + \
                   ' nwkID ' + nwkid + ' ' + enable)
        click.echo(indent + 'name: ' + d['name'])
        click.echo(indent + 'class: ' + d['devclass'].upper())
        click.echo(indent + 'application EUI: ' + euiString(d['appeui']))
        click.echo(indent + 'activation: ' + activ)
        click.echo(indent + 'appname: ' + appname)
        click.echo(indent + 'latitude: ' + lat)
        click.echo(indent + 'longitude: ' + lon)
        if not d['otaa']:
            click.echo(indent + 'appskey: ' + intHexString(d['appskey'], 16))
            click.echo(indent + 'nwkskey: ' + intHexString(d['nwkskey'], 16))
        click.echo(indent + 'data rate: ' + drate)
        click.echo(indent + 'average SNR: ' + snrav)
        return
        
    # All devices
    click.echo('{:15}'.format('Device') + \
               '{:24}'.format('DeviceEUI') + \
               '{:12}'.format('DevAddr') + \
               '{:9}'.format('Enabled') + \
               '{:5}'.format('Act') + \
               '{:12}'.format('Average-SNR'))
    for i,d in data.iteritems():
        enable = 'Yes' if d['enabled'] else 'No'
        active = 'OTA' if d['otaa'] else 'ABP'
        snravg = '{0:.2f} dBm'.format(d['snr_average']) if d['snr_average'] else 'N/A'
        click.echo('{:14.14}'.format(d['name']) + ' ' + \
                   '{:23}'.format(euiString(d['deveui'])) +  ' ' + \
                   '{:12}'.format(devaddrString(d['devaddr'])) + \
                   '{:9}'.format(enable) + \
                   '{:5}'.format(active) + \
                   '{:12}'.format(snravg))