Esempio n. 1
0
 def _prompt(self, attrName, attrDef):
     attrDef["attr_type"] = str(attrDef["attr_type"]).lower()
     v = []
     if attrDef["attr_type"] == "string":
         if attrDef["attr_mandatory"]:
             v.append(
                 validators.RegexValidator(
                     r'.+', 'Enter a value, that is not empty.'))
         result = prompt.query(attrDef["attr_name"] + ":", validators=v)
         if result == "" or result is None:
             return None
         return str(result)
     elif attrDef["attr_type"] == "bool":
         if attrDef["attr_mandatory"]:
             v.append(
                 validators.RegexValidator(
                     re.compile('^(true|false|0|1)$', re.IGNORECASE),
                     'Enter true, 1, false or 0.'))
         else:
             v.append(
                 validators.RegexValidator(
                     re.compile('^(true|false|0|1)?$', re.IGNORECASE),
                     'Enter true, 1, false or 0.'))
         result = prompt.query(attrDef["attr_name"] + ":", validators=v)
         if result == "" or result is None:
             return None
         return bool(result)
     elif attrDef["attr_type"] == "int":
         v.append(
             IntegerValidator('Enter a valid integer.',
                              not attrDef["attr_mandatory"]))
         result = prompt.query(attrDef["attr_name"] + ":", validators=v)
         if result == "" or result is None:
             return None
         return int(result)
     elif attrDef["attr_type"] == "float":
         v.append(
             FloatValidator('Enter a valid float.',
                            not attrDef["attr_mandatory"]))
         result = prompt.query(attrDef["attr_name"] + ":", validators=v)
         if result == "" or result is None:
             return None
         return float(result)
     elif attrDef["attr_type"] == "json":
         # todo add json validation
         if attrDef["attr_mandatory"]:
             v.append(validators.RegexValidator(r'.+'))
         return prompt.query(attrDef["attr_name"] + ":", validators=v)
     return None
Esempio n. 2
0
def prompt_edit_drive(drive_list):
    try:
        while True:
            puts()
            target_id = prompt.query(
                'Please enter command: ',
                validators=[validators.RegexValidator('-?[0-9]+')])
            try:
                if target_id[0] == '-':
                    target_id = int(target_id[1:])
                    drive = drive_list[target_id]
                    if drive is None:
                        raise ValueError('the Drive has been deleted.')
                    drive_store.delete_record(drive)
                    drive_list[target_id] = None
                    puts(
                        colored.green('Successfully deleted Drive "%s"' %
                                      drive.drive_id))
                else:
                    target_id = int(target_id)
                    drive = drive_list[target_id]
                    if drive is None:
                        raise ValueError('the Drive has been deleted.')
                    prompt_drive_config(drive)
                    drive_store.add_record(drive)
                    puts(
                        colored.green('Successfully edited Drive "%s"' %
                                      drive.drive_id))
            except ValueError as ex:
                puts(colored.red('Error: ' + str(ex)))
    except KeyboardInterrupt:
        puts(colored.green('Aborted.'))
Esempio n. 3
0
def setup_hostapd():
    if get_hostapd_setup_status():
        print(get_hostapd_setup_status())
        return

    print("Installing Hostapd...")
    os.system('apt-get -yq install hostapd')
    print("... done!")

    print("Setting up hostapd config...")

    interface = env.var("ONEIOT_C_NETWORK_INTERFACE")
    ssid = env.var("ONEIOT_C_NETWORK_SSID")
    psk = prompt.query(
        'Network Password (8-63 alphanumeric chars)',
        validators=[
            validators.RegexValidator(
                regex=r"([a-z]|[0-9]){8,63}",
                message="Password must be 8 to 63 alphanumeric characters")
        ])

    if not path.exists("/etc/hostapd"):
        os.mkdir("/etc/hostapd")

    hostapd = Parsers.HostAPDParser("/etc/hostapd/hostapd.conf",
                                    "/etc/default/hostapd")
    hostapd.set_options({
        'interface': interface,
        'driver': 'nl80211',
        'ssid': ssid,
        'hw_mode': 'g',
        'channel': '6',
        'ieee80211n': '1',
        'wmm_enabled': '1',
        'ht_capab': '[HT40][SHORT-GI-20][DSSS_CCK-40]',
        'macaddr_acl': '0',
        'auth_algs': '1',
        'ignore_broadcast_ssid': '0',
        'wpa': '2',
        'wpa_key_mgmt': 'WPA-PSK',
        'wpa_passphrase': psk,
        'rsn_pairwise': 'CCMP'
    })
    hostapd.save()

    hostapd.set_master_options({
        'DAEMON_CONF': '"/etc/hostapd/hostapd.conf"',
    })
    hostapd.save_master()

    os.system('systemctl unmask hostapd')
    os.system('update-rc.d hostapd enable')

    print(".. done!")
Esempio n. 4
0
def modifySettings(settings):
    putSeparator()
    puts('Modify Settings:')
    with indent(4):
        invalidSettings = True
        while invalidSettings:
            settings['method'] = prompt.query(
                'Output Method:',
                default=settings['method'],
                validators=[
                    validators.RegexValidator(regex=re.compile('[a-b]+'))
                ])
            settings['min'] = prompt.query(
                'Minimum X Value:',
                default="%f" % settings['min'],
                validators=[sab_validators.FloatValidator()])
            settings['max'] = prompt.query(
                'Max X Value:',
                default="%f" % settings['max'],
                validators=[sab_validators.FloatValidator()])
            if settings['min'] > settings['max']:
                puts(
                    colored.red(
                        'Minimum X value can not be larger than Maximum X value!'
                    ))
                continue
            settings['formats'] = prompt.query(
                'Comma Separated List of Output Formats(Formats: {}):'.format(
                    ','.join(getValidFormats())),
                default=','.join(settings['formats']),
                validators=[
                    sab_validators.CommaSeparatedValidator(
                        options=getValidFormats())
                ])
            settings['smooth'] = prompt.query(
                'AirPLS Smoothing:',
                default=str(settings['smooth']),
                validators=[validators.IntegerValidator()])
            settings['max_it'] = prompt.query(
                'AirPLS Max Iterations:',
                default=str(settings['max_it']),
                validators=[validators.IntegerValidator()])
            settings['porder'] = prompt.query(
                'AirPLS POrder:',
                default=str(settings['porder']),
                validators=[validators.IntegerValidator()])
            settings['prec'] = prompt.query(
                'Data Output Decimal Precision:',
                default=str(settings['prec']),
                validators=[validators.IntegerValidator()])

            invalidSettings = False
Esempio n. 5
0
 def __sendMessage(self):
     sigfoxPattern = re.compile("^[0-9A-F]{1,24}$")
     command = self.commands['Send'].encode('ascii', 'ignore')
     payload = prompt.query("Message (Hexidecimal):",
                            validators=[
                                validators.RegexValidator(
                                    sigfoxPattern, 'Invalid Payload')
                            ])
     try:
         with serial.Serial(self.name, self.baud, timeout=10) as ser:
             ser.write(command + payload + '\r')
             line = ser.readline()
             print line
     except serial.SerialException as e:
         print 'Could not connect to device...'
Esempio n. 6
0
def prompt_param(param):
    """
    prompt to the user the parameters to input
    :param param: list of parameters
    :return: answer (string)
    """
    if param == 'filial':
        answer = prompt.query(f'Insert subsidiary code ({param}):',
                              '02',
                              validators=[
                                  validators.RegexValidator(
                                      r"^\d{2}$",
                                      'Value must be two numeric digits')
                              ],
                              batch=False)
        answer = f"'{answer}'"  # puts result in single quotes because of SQL interpreter
    elif param == 'armazem':
        answer = prompt.query(f'Insert warehouse code ({param}):',
                              '21',
                              validators=[
                                  validators.RegexValidator(
                                      r"^\d{2}$",
                                      'Value must be two numeric digits')
                              ],
                              batch=False)
        answer = f"'{answer}'"  # puts result in single quotes because of SQL interpreter
    elif param == 'codigo':
        answer = prompt.query(f'Insert product code ({param}):',
                              '02500727',
                              validators=[
                                  validators.RegexValidator(
                                      r"^\d{8}$",
                                      'Value must be eight numeric digits')
                              ],
                              batch=False)
        answer = f"'{answer}'"  # puts result in single quotes because of SQL interpreter
    elif param == 'intervalo':
        answer = prompt.query(f'Insert range ({param}) in days:',
                              '365',
                              validators=[
                                  _InputValidator(
                                      _greater_than,
                                      "Must to be greater than 30 days", 30)
                              ],
                              batch=False)
        answer = int(answer) * -1
    elif param in ['driver', 'server', 'database', 'uid',
                   'pwd']:  # input for the ini file of the app, if necessary
        example = 'no example presented'
        if param == 'driver':
            example = 'SQL Server'
        elif param == 'server':
            example = 'db.domain.com'
        elif param == 'database':
            example = 'the database used in the company'
        elif param == 'uid':
            example = 'user identification'
        elif param == 'pwd':
            example = 'password'

        msg = f"The parameter [{param}] has no default value (Its's only needed to provide once)"
        print(msg, f'example >> {example}', sep='\n')
        answer = prompt.query(f'Insert a value to -> {param}:')
    else:
        answer = prompt.query(
            f'[UNKNOWN PARAMETER] Insert a value to -> {param}:')
        answer = f"'{answer}'"  # puts result in single quotes because of SQL interpreter
    return answer