nwo
stringlengths
6
76
sha
stringlengths
40
40
path
stringlengths
5
118
language
stringclasses
1 value
identifier
stringlengths
1
89
parameters
stringlengths
2
5.4k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
51.1k
docstring
stringlengths
1
17.6k
docstring_summary
stringlengths
0
7.02k
docstring_tokens
sequence
function
stringlengths
30
51.1k
function_tokens
sequence
url
stringlengths
85
218
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/sdr.py
python
_tune_max_pipe_size
(pipesize)
Tune the maximum size of pipes
Tune the maximum size of pipes
[ "Tune", "the", "maximum", "size", "of", "pipes" ]
def _tune_max_pipe_size(pipesize): """Tune the maximum size of pipes""" if (not which("sysctl")): logging.error("Couldn't tune max-pipe-size. Please check how to tune " "it in your OS.") return False ret = subprocess.check_output(["sysctl", "fs.pipe-max-size"]) current_max = int(ret.decode().split()[-1]) if (current_max < pipesize): cmd = ["sysctl", "-w", "fs.pipe-max-size=" + str(pipesize)] print( textwrap.fill("The maximum pipe size that is currently " "configured in your OS is of {} bytes, which is " "not sufficient for the receiver application. " "It will be necessary to run the following command " "as root:".format(current_max), width=80)) print("\n" + " ".join(cmd) + "\n") if (not util.ask_yes_or_no("Is that OK?", default="y")): print("Abort") return False res = runner.run(cmd, root=True) return (res.returncode == 0) else: return True
[ "def", "_tune_max_pipe_size", "(", "pipesize", ")", ":", "if", "(", "not", "which", "(", "\"sysctl\"", ")", ")", ":", "logging", ".", "error", "(", "\"Couldn't tune max-pipe-size. Please check how to tune \"", "\"it in your OS.\"", ")", "return", "False", "ret", "=", "subprocess", ".", "check_output", "(", "[", "\"sysctl\"", ",", "\"fs.pipe-max-size\"", "]", ")", "current_max", "=", "int", "(", "ret", ".", "decode", "(", ")", ".", "split", "(", ")", "[", "-", "1", "]", ")", "if", "(", "current_max", "<", "pipesize", ")", ":", "cmd", "=", "[", "\"sysctl\"", ",", "\"-w\"", ",", "\"fs.pipe-max-size=\"", "+", "str", "(", "pipesize", ")", "]", "print", "(", "textwrap", ".", "fill", "(", "\"The maximum pipe size that is currently \"", "\"configured in your OS is of {} bytes, which is \"", "\"not sufficient for the receiver application. \"", "\"It will be necessary to run the following command \"", "\"as root:\"", ".", "format", "(", "current_max", ")", ",", "width", "=", "80", ")", ")", "print", "(", "\"\\n\"", "+", "\" \"", ".", "join", "(", "cmd", ")", "+", "\"\\n\"", ")", "if", "(", "not", "util", ".", "ask_yes_or_no", "(", "\"Is that OK?\"", ",", "default", "=", "\"y\"", ")", ")", ":", "print", "(", "\"Abort\"", ")", "return", "False", "res", "=", "runner", ".", "run", "(", "cmd", ",", "root", "=", "True", ")", "return", "(", "res", ".", "returncode", "==", "0", ")", "else", ":", "return", "True" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/sdr.py#L15-L43
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/sdr.py
python
_get_monitor
(args)
return monitoring.Monitor(args.cfg_dir, logfile=args.log_file, scroll=scrolling, echo=echo, min_interval=args.log_interval, server=args.monitoring_server, port=args.monitoring_port, report=args.report, report_opts=monitoring.get_report_opts(args), utc=args.utc)
Create an object of the Monitor class Args: args : SDR parser arguments sat_name : Satellite name
Create an object of the Monitor class
[ "Create", "an", "object", "of", "the", "Monitor", "class" ]
def _get_monitor(args): """Create an object of the Monitor class Args: args : SDR parser arguments sat_name : Satellite name """ # If debugging leandvb, don't echo the logs to stdout, otherwise the # logs get mixed on the console and it becomes hard to read them. echo = (args.debug_dvbs2 == 0) # Force scrolling logs if tsp is configured to print to stdout scrolling = tsp.prints_to_stdout(args) or args.log_scrolling return monitoring.Monitor(args.cfg_dir, logfile=args.log_file, scroll=scrolling, echo=echo, min_interval=args.log_interval, server=args.monitoring_server, port=args.monitoring_port, report=args.report, report_opts=monitoring.get_report_opts(args), utc=args.utc)
[ "def", "_get_monitor", "(", "args", ")", ":", "# If debugging leandvb, don't echo the logs to stdout, otherwise the", "# logs get mixed on the console and it becomes hard to read them.", "echo", "=", "(", "args", ".", "debug_dvbs2", "==", "0", ")", "# Force scrolling logs if tsp is configured to print to stdout", "scrolling", "=", "tsp", ".", "prints_to_stdout", "(", "args", ")", "or", "args", ".", "log_scrolling", "return", "monitoring", ".", "Monitor", "(", "args", ".", "cfg_dir", ",", "logfile", "=", "args", ".", "log_file", ",", "scroll", "=", "scrolling", ",", "echo", "=", "echo", ",", "min_interval", "=", "args", ".", "log_interval", ",", "server", "=", "args", ".", "monitoring_server", ",", "port", "=", "args", ".", "monitoring_port", ",", "report", "=", "args", ".", "report", ",", "report_opts", "=", "monitoring", ".", "get_report_opts", "(", "args", ")", ",", "utc", "=", "args", ".", "utc", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/sdr.py#L63-L87
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/sdr.py
python
_monitor_demod_info
(info_pipe, monitor)
Monitor leandvb's demodulator information Continuously read the demodulator information printed by leandvb into the descriptor pointed by --fd-info, which is tied to an unnamed pipe file. Then, feed the information into the monitor object. Args: info_pipe : Pipe object pointing to the pipe file that is used as leandvb's --fd-info descriptor monitor : Object of the Monitor class used to handle receiver monitoring and logging
Monitor leandvb's demodulator information
[ "Monitor", "leandvb", "s", "demodulator", "information" ]
def _monitor_demod_info(info_pipe, monitor): """Monitor leandvb's demodulator information Continuously read the demodulator information printed by leandvb into the descriptor pointed by --fd-info, which is tied to an unnamed pipe file. Then, feed the information into the monitor object. Args: info_pipe : Pipe object pointing to the pipe file that is used as leandvb's --fd-info descriptor monitor : Object of the Monitor class used to handle receiver monitoring and logging """ assert (isinstance(info_pipe, util.Pipe)) # "Standard" status format accepted by the Monitor class status = {'lock': (False, None), 'level': None, 'snr': None, 'ber': None} while True: line = info_pipe.readline() if "FRAMELOCK" in line: status['lock'] = (line.split()[-1] == "1", None) for metric in rx_stat_map: if metric in line: val = float(line.split()[-1]) unit = rx_stat_map[metric]['unit'] key = rx_stat_map[metric]['key'] status[key] = (val, unit) # If unlocked, clear the status metrics that depend on receiver locking # (they will show garbage if unlocked). If locked, just make sure that # all the required metrics are filled in the status dictionary. ready = True for metric in rx_stat_map: key = rx_stat_map[metric]['key'] if status['lock'][0]: if key not in status or status[key] is None: ready = False else: if (key in status): del status[key] if (not ready): continue monitor.update(status)
[ "def", "_monitor_demod_info", "(", "info_pipe", ",", "monitor", ")", ":", "assert", "(", "isinstance", "(", "info_pipe", ",", "util", ".", "Pipe", ")", ")", "# \"Standard\" status format accepted by the Monitor class", "status", "=", "{", "'lock'", ":", "(", "False", ",", "None", ")", ",", "'level'", ":", "None", ",", "'snr'", ":", "None", ",", "'ber'", ":", "None", "}", "while", "True", ":", "line", "=", "info_pipe", ".", "readline", "(", ")", "if", "\"FRAMELOCK\"", "in", "line", ":", "status", "[", "'lock'", "]", "=", "(", "line", ".", "split", "(", ")", "[", "-", "1", "]", "==", "\"1\"", ",", "None", ")", "for", "metric", "in", "rx_stat_map", ":", "if", "metric", "in", "line", ":", "val", "=", "float", "(", "line", ".", "split", "(", ")", "[", "-", "1", "]", ")", "unit", "=", "rx_stat_map", "[", "metric", "]", "[", "'unit'", "]", "key", "=", "rx_stat_map", "[", "metric", "]", "[", "'key'", "]", "status", "[", "key", "]", "=", "(", "val", ",", "unit", ")", "# If unlocked, clear the status metrics that depend on receiver locking", "# (they will show garbage if unlocked). If locked, just make sure that", "# all the required metrics are filled in the status dictionary.", "ready", "=", "True", "for", "metric", "in", "rx_stat_map", ":", "key", "=", "rx_stat_map", "[", "metric", "]", "[", "'key'", "]", "if", "status", "[", "'lock'", "]", "[", "0", "]", ":", "if", "key", "not", "in", "status", "or", "status", "[", "key", "]", "is", "None", ":", "ready", "=", "False", "else", ":", "if", "(", "key", "in", "status", ")", ":", "del", "status", "[", "key", "]", "if", "(", "not", "ready", ")", ":", "continue", "monitor", ".", "update", "(", "status", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/sdr.py#L90-L138
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/sdr.py
python
subparser
(subparsers)
return p
Parser for sdr command
Parser for sdr command
[ "Parser", "for", "sdr", "command" ]
def subparser(subparsers): """Parser for sdr command""" p = subparsers.add_parser('sdr', description="Launch SDR receiver", help='Launch SDR receiver', formatter_class=ArgumentDefaultsHelpFormatter) # Monitoring options monitoring.add_to_parser(p) rtl_p = p.add_argument_group('rtl_sdr options') rtl_p.add_argument('--sps', default=2.0, type=float, help='Samples per symbol, or, equivalently, the ' 'target oversampling ratio') rtl_p.add_argument('--rtl-idx', default=0, type=int, help='RTL-SDR device index') rtl_p.add_argument('-g', '--gain', default=40, type=float, help='RTL-SDR Rx gain') rtl_p.add_argument('-f', '--iq-file', default=None, help='File to read IQ samples from instead of reading ' 'from the RTL-SDR in real-time') ldvb_p = p.add_argument_group('leandvb options') ldvb_p.add_argument( '-n', '--n-helpers', default=6, type=int, help='Number of instances of the external LDPC decoder \ to spawn as child processes') ldvb_p.add_argument( '-d', '--debug-dvbs2', action='count', default=0, help="Debug leandvb's DVB-S2 decoding. Use it multiple " "times to increase the debugging level") ldvb_p.add_argument('-v', '--verbose', default=False, action='store_true', help='leandvb in verbose mode') ldvb_p.add_argument('--gui', default=False, action='store_true', help='GUI mode') ldvb_p.add_argument('--derotate', default=0, type=float, help='Frequency offset correction to apply in kHz') ldvb_p.add_argument('--fastlock', default=False, action='store_true', help='leandvb fast lock mode') ldvb_p.add_argument('--rrc-rej', default=30, type=int, help='leandvb RRC rej parameter') ldvb_p.add_argument('-m', '--modcod', choices=defs.modcods.keys(), default='qpsk3/5', metavar='', help="DVB-S2 modulation and coding (MODCOD) scheme. " "Choose from: " + ", ".join(defs.modcods.keys())) ldvb_p.add_argument('--ldpc-dec', default="ext", choices=["int", "ext"], help="LDPC decoder to use (internal or external)") ldvb_p.add_argument('--ldpc-bf', default=100, help='Max number of iterations used by the internal \ LDPC decoder when not using an external LDPC tool') ldvb_p.add_argument('--ldpc-iterations', default=25, help='Max number of iterations used by the external \ LDPC decoder when using an external LDPC tool') ldvb_p.add_argument('--framesizes', type=int, default=1, choices=[0, 1, 2, 3], help="Bitmask of desired frame sizes (1=normal, \ 2=short)") ldvb_p.add_argument('--no-tsp', default=False, action='store_true', help='Feed leandvb output to stdout instead of tsp') ldvb_p.add_argument('--pipe-size', default=32, type=int, help='Size in Mbytes of the input pipe file read by \ leandvb') # TSDuck Options tsp.add_to_parser(p) p.set_defaults(func=run, record=False) subsubparsers = p.add_subparsers(title='subcommands', help='Target sub-command') # IQ recording p2 = subsubparsers.add_parser( 'rec', description="Record IQ samples instead of " "feeding them into leandvb", help='Record IQ samples', formatter_class=ArgumentDefaultsHelpFormatter) p2.add_argument('-f', '--iq-file', default="blocksat.iq", help='File on which to save IQ samples received with ' 'the RTL-SDR.') p2.set_defaults(record=True) return p
[ "def", "subparser", "(", "subparsers", ")", ":", "p", "=", "subparsers", ".", "add_parser", "(", "'sdr'", ",", "description", "=", "\"Launch SDR receiver\"", ",", "help", "=", "'Launch SDR receiver'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "# Monitoring options", "monitoring", ".", "add_to_parser", "(", "p", ")", "rtl_p", "=", "p", ".", "add_argument_group", "(", "'rtl_sdr options'", ")", "rtl_p", ".", "add_argument", "(", "'--sps'", ",", "default", "=", "2.0", ",", "type", "=", "float", ",", "help", "=", "'Samples per symbol, or, equivalently, the '", "'target oversampling ratio'", ")", "rtl_p", ".", "add_argument", "(", "'--rtl-idx'", ",", "default", "=", "0", ",", "type", "=", "int", ",", "help", "=", "'RTL-SDR device index'", ")", "rtl_p", ".", "add_argument", "(", "'-g'", ",", "'--gain'", ",", "default", "=", "40", ",", "type", "=", "float", ",", "help", "=", "'RTL-SDR Rx gain'", ")", "rtl_p", ".", "add_argument", "(", "'-f'", ",", "'--iq-file'", ",", "default", "=", "None", ",", "help", "=", "'File to read IQ samples from instead of reading '", "'from the RTL-SDR in real-time'", ")", "ldvb_p", "=", "p", ".", "add_argument_group", "(", "'leandvb options'", ")", "ldvb_p", ".", "add_argument", "(", "'-n'", ",", "'--n-helpers'", ",", "default", "=", "6", ",", "type", "=", "int", ",", "help", "=", "'Number of instances of the external LDPC decoder \\\n to spawn as child processes'", ")", "ldvb_p", ".", "add_argument", "(", "'-d'", ",", "'--debug-dvbs2'", ",", "action", "=", "'count'", ",", "default", "=", "0", ",", "help", "=", "\"Debug leandvb's DVB-S2 decoding. Use it multiple \"", "\"times to increase the debugging level\"", ")", "ldvb_p", ".", "add_argument", "(", "'-v'", ",", "'--verbose'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'leandvb in verbose mode'", ")", "ldvb_p", ".", "add_argument", "(", "'--gui'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'GUI mode'", ")", "ldvb_p", ".", "add_argument", "(", "'--derotate'", ",", "default", "=", "0", ",", "type", "=", "float", ",", "help", "=", "'Frequency offset correction to apply in kHz'", ")", "ldvb_p", ".", "add_argument", "(", "'--fastlock'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'leandvb fast lock mode'", ")", "ldvb_p", ".", "add_argument", "(", "'--rrc-rej'", ",", "default", "=", "30", ",", "type", "=", "int", ",", "help", "=", "'leandvb RRC rej parameter'", ")", "ldvb_p", ".", "add_argument", "(", "'-m'", ",", "'--modcod'", ",", "choices", "=", "defs", ".", "modcods", ".", "keys", "(", ")", ",", "default", "=", "'qpsk3/5'", ",", "metavar", "=", "''", ",", "help", "=", "\"DVB-S2 modulation and coding (MODCOD) scheme. \"", "\"Choose from: \"", "+", "\", \"", ".", "join", "(", "defs", ".", "modcods", ".", "keys", "(", ")", ")", ")", "ldvb_p", ".", "add_argument", "(", "'--ldpc-dec'", ",", "default", "=", "\"ext\"", ",", "choices", "=", "[", "\"int\"", ",", "\"ext\"", "]", ",", "help", "=", "\"LDPC decoder to use (internal or external)\"", ")", "ldvb_p", ".", "add_argument", "(", "'--ldpc-bf'", ",", "default", "=", "100", ",", "help", "=", "'Max number of iterations used by the internal \\\n LDPC decoder when not using an external LDPC tool'", ")", "ldvb_p", ".", "add_argument", "(", "'--ldpc-iterations'", ",", "default", "=", "25", ",", "help", "=", "'Max number of iterations used by the external \\\n LDPC decoder when using an external LDPC tool'", ")", "ldvb_p", ".", "add_argument", "(", "'--framesizes'", ",", "type", "=", "int", ",", "default", "=", "1", ",", "choices", "=", "[", "0", ",", "1", ",", "2", ",", "3", "]", ",", "help", "=", "\"Bitmask of desired frame sizes (1=normal, \\\n 2=short)\"", ")", "ldvb_p", ".", "add_argument", "(", "'--no-tsp'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'Feed leandvb output to stdout instead of tsp'", ")", "ldvb_p", ".", "add_argument", "(", "'--pipe-size'", ",", "default", "=", "32", ",", "type", "=", "int", ",", "help", "=", "'Size in Mbytes of the input pipe file read by \\\n leandvb'", ")", "# TSDuck Options", "tsp", ".", "add_to_parser", "(", "p", ")", "p", ".", "set_defaults", "(", "func", "=", "run", ",", "record", "=", "False", ")", "subsubparsers", "=", "p", ".", "add_subparsers", "(", "title", "=", "'subcommands'", ",", "help", "=", "'Target sub-command'", ")", "# IQ recording", "p2", "=", "subsubparsers", ".", "add_parser", "(", "'rec'", ",", "description", "=", "\"Record IQ samples instead of \"", "\"feeding them into leandvb\"", ",", "help", "=", "'Record IQ samples'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "p2", ".", "add_argument", "(", "'-f'", ",", "'--iq-file'", ",", "default", "=", "\"blocksat.iq\"", ",", "help", "=", "'File on which to save IQ samples received with '", "'the RTL-SDR.'", ")", "p2", ".", "set_defaults", "(", "record", "=", "True", ")", "return", "p" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/sdr.py#L141-L264
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/rp.py
python
_set_filters
(dvb_ifs)
Disable reverse-path (RP) filtering for the DVB interface There are two layers of RP filters, one specific to the network interface and a higher level that controls the configurations for all network interfaces. This function disables RP filtering on the top layer (for all interfaces) but then enables RP filtering individually on all interfaces, except the DVB-S2 interface of interst. This way, in the end, only the DVB-S2 interface has RP filtering disabled. If the top layer RP filter (the "all" rule) is already disabled, this function disables only the target DVB-S2 interface. This strategy is especially useful when multiple DVB-S2 interfaces are attached to the host. If one of them has already disabled the "all" rule, this function disables only the incoming DVB-S2 interface and doesn't re-enable the RP filters of the other interfaces, otherwise it would end up reactivating the filter for the other DVB-S2 interface(s). Args: dvb_ifs : List of target DVB-S2 network interfaces.
Disable reverse-path (RP) filtering for the DVB interface
[ "Disable", "reverse", "-", "path", "(", "RP", ")", "filtering", "for", "the", "DVB", "interface" ]
def _set_filters(dvb_ifs): """Disable reverse-path (RP) filtering for the DVB interface There are two layers of RP filters, one specific to the network interface and a higher level that controls the configurations for all network interfaces. This function disables RP filtering on the top layer (for all interfaces) but then enables RP filtering individually on all interfaces, except the DVB-S2 interface of interst. This way, in the end, only the DVB-S2 interface has RP filtering disabled. If the top layer RP filter (the "all" rule) is already disabled, this function disables only the target DVB-S2 interface. This strategy is especially useful when multiple DVB-S2 interfaces are attached to the host. If one of them has already disabled the "all" rule, this function disables only the incoming DVB-S2 interface and doesn't re-enable the RP filters of the other interfaces, otherwise it would end up reactivating the filter for the other DVB-S2 interface(s). Args: dvb_ifs : List of target DVB-S2 network interfaces. """ assert (isinstance(dvb_ifs, list)) # If the "all" rule is already disabled, disable only the target DVB-S2 # interface. if (_read_filter("all", nodry=True) == 0): if (not runner.dry): print("RP filter for \"all\" interfaces is already disabled") for dvb_if in dvb_ifs: _rm_filter(dvb_if) # If the "all" rule is enabled, disable it, and manually enable the RP # filtering on all other interfaces. else: # Check interfaces ifs = os.listdir("/proc/sys/net/ipv4/conf/") # Enable all RP filters for interface in ifs: if (interface == "all" or interface == "lo" or interface in dvb_ifs): continue # Enable the RP filter if not enabled already. if (_read_filter(interface, nodry=True) > 0): if (not runner.dry): print("RP filter is already enabled on interface %s" % (interface)) else: _add_filter(interface) # Disable the overall RP filter _rm_filter("all") # And disable RP filtering on the DVB interface for dvb_if in dvb_ifs: _rm_filter(dvb_if)
[ "def", "_set_filters", "(", "dvb_ifs", ")", ":", "assert", "(", "isinstance", "(", "dvb_ifs", ",", "list", ")", ")", "# If the \"all\" rule is already disabled, disable only the target DVB-S2", "# interface.", "if", "(", "_read_filter", "(", "\"all\"", ",", "nodry", "=", "True", ")", "==", "0", ")", ":", "if", "(", "not", "runner", ".", "dry", ")", ":", "print", "(", "\"RP filter for \\\"all\\\" interfaces is already disabled\"", ")", "for", "dvb_if", "in", "dvb_ifs", ":", "_rm_filter", "(", "dvb_if", ")", "# If the \"all\" rule is enabled, disable it, and manually enable the RP", "# filtering on all other interfaces.", "else", ":", "# Check interfaces", "ifs", "=", "os", ".", "listdir", "(", "\"/proc/sys/net/ipv4/conf/\"", ")", "# Enable all RP filters", "for", "interface", "in", "ifs", ":", "if", "(", "interface", "==", "\"all\"", "or", "interface", "==", "\"lo\"", "or", "interface", "in", "dvb_ifs", ")", ":", "continue", "# Enable the RP filter if not enabled already.", "if", "(", "_read_filter", "(", "interface", ",", "nodry", "=", "True", ")", ">", "0", ")", ":", "if", "(", "not", "runner", ".", "dry", ")", ":", "print", "(", "\"RP filter is already enabled on interface %s\"", "%", "(", "interface", ")", ")", "else", ":", "_add_filter", "(", "interface", ")", "# Disable the overall RP filter", "_rm_filter", "(", "\"all\"", ")", "# And disable RP filtering on the DVB interface", "for", "dvb_if", "in", "dvb_ifs", ":", "_rm_filter", "(", "dvb_if", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/rp.py#L43-L101
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/rp.py
python
set_filters
(dvb_ifs, prompt=True, dry=False)
Disable reverse-path (RP) filtering for the DVB interfaces Args: dvb_ifs : list of DVB network interfaces prompt : Whether to prompt user before applying a configuration dry : Dry run mode
Disable reverse-path (RP) filtering for the DVB interfaces
[ "Disable", "reverse", "-", "path", "(", "RP", ")", "filtering", "for", "the", "DVB", "interfaces" ]
def set_filters(dvb_ifs, prompt=True, dry=False): """Disable reverse-path (RP) filtering for the DVB interfaces Args: dvb_ifs : list of DVB network interfaces prompt : Whether to prompt user before applying a configuration dry : Dry run mode """ assert (isinstance(dvb_ifs, list)) runner.set_dry(dry) util.print_header("Reverse Path Filters") # Check if the RP filters are already configured properly rp_filters_set = list() rp_filters_set.append(_read_filter("all", nodry=True) == 0) for dvb_if in dvb_ifs: rp_filters_set.append(_read_filter(dvb_if, nodry=True) == 0) if (all(rp_filters_set)): print("Current RP filtering configurations are already OK") print("Skipping...") return util.fill_print("It will be necessary to reconfigure some reverse path \ (RP) filtering rules applied by the Linux kernel. This is required to \ prevent the filtering of the one-way Blockstream Satellite traffic.") if (runner.dry): util.fill_print("The following command(s) would be executed to \ reconfigure the RP filters:") if (runner.dry or (not prompt) or util.ask_yes_or_no("OK to proceed?")): _set_filters(dvb_ifs) else: print("RP filtering configuration cancelled")
[ "def", "set_filters", "(", "dvb_ifs", ",", "prompt", "=", "True", ",", "dry", "=", "False", ")", ":", "assert", "(", "isinstance", "(", "dvb_ifs", ",", "list", ")", ")", "runner", ".", "set_dry", "(", "dry", ")", "util", ".", "print_header", "(", "\"Reverse Path Filters\"", ")", "# Check if the RP filters are already configured properly", "rp_filters_set", "=", "list", "(", ")", "rp_filters_set", ".", "append", "(", "_read_filter", "(", "\"all\"", ",", "nodry", "=", "True", ")", "==", "0", ")", "for", "dvb_if", "in", "dvb_ifs", ":", "rp_filters_set", ".", "append", "(", "_read_filter", "(", "dvb_if", ",", "nodry", "=", "True", ")", "==", "0", ")", "if", "(", "all", "(", "rp_filters_set", ")", ")", ":", "print", "(", "\"Current RP filtering configurations are already OK\"", ")", "print", "(", "\"Skipping...\"", ")", "return", "util", ".", "fill_print", "(", "\"It will be necessary to reconfigure some reverse path \\\n (RP) filtering rules applied by the Linux kernel. This is required to \\\n prevent the filtering of the one-way Blockstream Satellite traffic.\"", ")", "if", "(", "runner", ".", "dry", ")", ":", "util", ".", "fill_print", "(", "\"The following command(s) would be executed to \\\n reconfigure the RP filters:\"", ")", "if", "(", "runner", ".", "dry", "or", "(", "not", "prompt", ")", "or", "util", ".", "ask_yes_or_no", "(", "\"OK to proceed?\"", ")", ")", ":", "_set_filters", "(", "dvb_ifs", ")", "else", ":", "print", "(", "\"RP filtering configuration cancelled\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/rp.py#L104-L139
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/rp.py
python
subparser
(subparsers)
return p
Parser for rp command
Parser for rp command
[ "Parser", "for", "rp", "command" ]
def subparser(subparsers): """Parser for rp command""" p = subparsers.add_parser('reverse-path', aliases=['rp'], description="Set reverse path filters", help='Set reverse path filters', formatter_class=ArgumentDefaultsHelpFormatter) p.add_argument('-i', '--interface', required=True, help='Network interface') p.add_argument('-y', '--yes', default=False, action='store_true', help="Default to answering Yes to configuration prompts") p.add_argument("--dry-run", action='store_true', default=False, help="Print all commands but do not execute them") p.set_defaults(func=run) return p
[ "def", "subparser", "(", "subparsers", ")", ":", "p", "=", "subparsers", ".", "add_parser", "(", "'reverse-path'", ",", "aliases", "=", "[", "'rp'", "]", ",", "description", "=", "\"Set reverse path filters\"", ",", "help", "=", "'Set reverse path filters'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "p", ".", "add_argument", "(", "'-i'", ",", "'--interface'", ",", "required", "=", "True", ",", "help", "=", "'Network interface'", ")", "p", ".", "add_argument", "(", "'-y'", ",", "'--yes'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "\"Default to answering Yes to configuration prompts\"", ")", "p", ".", "add_argument", "(", "\"--dry-run\"", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "\"Print all commands but do not execute them\"", ")", "p", ".", "set_defaults", "(", "func", "=", "run", ")", "return", "p" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/rp.py#L142-L163
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/rp.py
python
run
(args)
Call function that sets reverse path filters Handles the reverse-path subcommand
Call function that sets reverse path filters
[ "Call", "function", "that", "sets", "reverse", "path", "filters" ]
def run(args): """Call function that sets reverse path filters Handles the reverse-path subcommand """ set_filters([args.interface], prompt=(not args.yes), dry=args.dry_run)
[ "def", "run", "(", "args", ")", ":", "set_filters", "(", "[", "args", ".", "interface", "]", ",", "prompt", "=", "(", "not", "args", ".", "yes", ")", ",", "dry", "=", "args", ".", "dry_run", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/rp.py#L166-L172
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/tsp.py
python
prints_to_stdout
(args)
return args.ts_monitor_bitrate or args.ts_monitor_sequence or \ args.ts_dump
Check if tsp is configured to print to stdout
Check if tsp is configured to print to stdout
[ "Check", "if", "tsp", "is", "configured", "to", "print", "to", "stdout" ]
def prints_to_stdout(args): """Check if tsp is configured to print to stdout""" return args.ts_monitor_bitrate or args.ts_monitor_sequence or \ args.ts_dump
[ "def", "prints_to_stdout", "(", "args", ")", ":", "return", "args", ".", "ts_monitor_bitrate", "or", "args", ".", "ts_monitor_sequence", "or", "args", ".", "ts_dump" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/tsp.py#L173-L176
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/tsp.py
python
Tsp.gen_cmd
(self, args, in_plugin=None)
return True
Generate the tsp command Args: in_plugin : List with input plugin command to be used by tsp. Rerturns: Boolean indicating whether a valid command was generated.
Generate the tsp command
[ "Generate", "the", "tsp", "command" ]
def gen_cmd(self, args, in_plugin=None): """Generate the tsp command Args: in_plugin : List with input plugin command to be used by tsp. Rerturns: Boolean indicating whether a valid command was generated. """ # cache the request for TS dumping self.ts_dump = args.ts_dump self.ts_dump_opts = args.ts_dump_opts self.cmd = cmd = [ "tsp", "--realtime", "--buffer-size-mb", str(args.tsp_buffer_size_mb), "--max-flushed-packets", str(args.tsp_max_flushed_packets), "--max-input-packets", str(args.tsp_max_input_packets) ] if (in_plugin): cmd.extend(in_plugin) if (args.ts_analysis): logger.info("MPEG-TS analysis will be saved on file {}".format( args.ts_analysis)) if (not util.ask_yes_or_no("Proceed?", default="y")): return False cmd.extend(["-P", "analyze", "-o", args.ts_analysis]) if (args.ts_monitor_bitrate): cmd.extend([ "-P", "bitrate_monitor", "-p", str(args.ts_monitor_bitrate), "--min", "0" ]) if (args.ts_monitor_sequence): cmd.extend(["-P", "continuity"]) cmd.extend([ "-P", "mpe", "--pid", "-".join([str(pid) for pid in defs.pids]), "--udp-forward", "--local-address", args.local_address ]) # Output the MPEG TS stream to one of the following: # a) a file; # b) stdout (if using --ts-dump); # c) /dev/null (default). if (args.ts_file is not None): logger.info("MPEG TS output will be saved on file {}".format( args.ts_file)) if (not util.ask_yes_or_no("Proceed?", default="y")): return False cmd.extend(["-O", "file", args.ts_file]) elif (not args.ts_dump): cmd.extend(["-O", "drop"]) return True
[ "def", "gen_cmd", "(", "self", ",", "args", ",", "in_plugin", "=", "None", ")", ":", "# cache the request for TS dumping", "self", ".", "ts_dump", "=", "args", ".", "ts_dump", "self", ".", "ts_dump_opts", "=", "args", ".", "ts_dump_opts", "self", ".", "cmd", "=", "cmd", "=", "[", "\"tsp\"", ",", "\"--realtime\"", ",", "\"--buffer-size-mb\"", ",", "str", "(", "args", ".", "tsp_buffer_size_mb", ")", ",", "\"--max-flushed-packets\"", ",", "str", "(", "args", ".", "tsp_max_flushed_packets", ")", ",", "\"--max-input-packets\"", ",", "str", "(", "args", ".", "tsp_max_input_packets", ")", "]", "if", "(", "in_plugin", ")", ":", "cmd", ".", "extend", "(", "in_plugin", ")", "if", "(", "args", ".", "ts_analysis", ")", ":", "logger", ".", "info", "(", "\"MPEG-TS analysis will be saved on file {}\"", ".", "format", "(", "args", ".", "ts_analysis", ")", ")", "if", "(", "not", "util", ".", "ask_yes_or_no", "(", "\"Proceed?\"", ",", "default", "=", "\"y\"", ")", ")", ":", "return", "False", "cmd", ".", "extend", "(", "[", "\"-P\"", ",", "\"analyze\"", ",", "\"-o\"", ",", "args", ".", "ts_analysis", "]", ")", "if", "(", "args", ".", "ts_monitor_bitrate", ")", ":", "cmd", ".", "extend", "(", "[", "\"-P\"", ",", "\"bitrate_monitor\"", ",", "\"-p\"", ",", "str", "(", "args", ".", "ts_monitor_bitrate", ")", ",", "\"--min\"", ",", "\"0\"", "]", ")", "if", "(", "args", ".", "ts_monitor_sequence", ")", ":", "cmd", ".", "extend", "(", "[", "\"-P\"", ",", "\"continuity\"", "]", ")", "cmd", ".", "extend", "(", "[", "\"-P\"", ",", "\"mpe\"", ",", "\"--pid\"", ",", "\"-\"", ".", "join", "(", "[", "str", "(", "pid", ")", "for", "pid", "in", "defs", ".", "pids", "]", ")", ",", "\"--udp-forward\"", ",", "\"--local-address\"", ",", "args", ".", "local_address", "]", ")", "# Output the MPEG TS stream to one of the following:", "# a) a file;", "# b) stdout (if using --ts-dump);", "# c) /dev/null (default).", "if", "(", "args", ".", "ts_file", "is", "not", "None", ")", ":", "logger", ".", "info", "(", "\"MPEG TS output will be saved on file {}\"", ".", "format", "(", "args", ".", "ts_file", ")", ")", "if", "(", "not", "util", ".", "ask_yes_or_no", "(", "\"Proceed?\"", ",", "default", "=", "\"y\"", ")", ")", ":", "return", "False", "cmd", ".", "extend", "(", "[", "\"-O\"", ",", "\"file\"", ",", "args", ".", "ts_file", "]", ")", "elif", "(", "not", "args", ".", "ts_dump", ")", ":", "cmd", ".", "extend", "(", "[", "\"-O\"", ",", "\"drop\"", "]", ")", "return", "True" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/tsp.py#L82-L140
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/tsp.py
python
Tsp.run
(self, stdin=None)
Run tsp Args: in_plugin : List with input plugin command to be used by tsp. stdin : Stdin to attach to the tsp process. Rerturns: Boolean indicating whether the process is running succesfully.
Run tsp
[ "Run", "tsp" ]
def run(self, stdin=None): """Run tsp Args: in_plugin : List with input plugin command to be used by tsp. stdin : Stdin to attach to the tsp process. Rerturns: Boolean indicating whether the process is running succesfully. """ # Create a .tsduck.lastcheck file on the home directory to skip the # TSDuck version check. Path(os.path.join(util.get_home_dir(), ".tsduck.lastcheck")).touch() # When tsdump is enabled, hook tsp and tspdump through a pipe file (tsp # on the write side and tsdump on the read side) if (self.ts_dump): info_pipe = util.Pipe() stdout = info_pipe.w_fo else: stdout = None self.proc = subprocess.Popen(self.cmd, stdin=stdin, stdout=stdout) if (self.ts_dump): tsdump_cmd = ['tsdump'] tsdump_cmd.extend(self.ts_dump_opts) self.dump_proc = subprocess.Popen(tsdump_cmd, stdin=info_pipe.r_fo)
[ "def", "run", "(", "self", ",", "stdin", "=", "None", ")", ":", "# Create a .tsduck.lastcheck file on the home directory to skip the", "# TSDuck version check.", "Path", "(", "os", ".", "path", ".", "join", "(", "util", ".", "get_home_dir", "(", ")", ",", "\".tsduck.lastcheck\"", ")", ")", ".", "touch", "(", ")", "# When tsdump is enabled, hook tsp and tspdump through a pipe file (tsp", "# on the write side and tsdump on the read side)", "if", "(", "self", ".", "ts_dump", ")", ":", "info_pipe", "=", "util", ".", "Pipe", "(", ")", "stdout", "=", "info_pipe", ".", "w_fo", "else", ":", "stdout", "=", "None", "self", ".", "proc", "=", "subprocess", ".", "Popen", "(", "self", ".", "cmd", ",", "stdin", "=", "stdin", ",", "stdout", "=", "stdout", ")", "if", "(", "self", ".", "ts_dump", ")", ":", "tsdump_cmd", "=", "[", "'tsdump'", "]", "tsdump_cmd", ".", "extend", "(", "self", ".", "ts_dump_opts", ")", "self", ".", "dump_proc", "=", "subprocess", ".", "Popen", "(", "tsdump_cmd", ",", "stdin", "=", "info_pipe", ".", "r_fo", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/tsp.py#L142-L170
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring.py
python
get_report_opts
(args)
return { 'cfg': args.cfg, 'cfg_dir': args.cfg_dir, 'dest_addr': args.report_dest, 'hostname': args.report_hostname, 'tls_cert': args.report_cert, 'tls_key': args.report_key, 'gnupghome': args.report_gnupghome, 'passphrase': args.report_passphrase }
Extract the parser fields needed to construct a Reporter object
Extract the parser fields needed to construct a Reporter object
[ "Extract", "the", "parser", "fields", "needed", "to", "construct", "a", "Reporter", "object" ]
def get_report_opts(args): """Extract the parser fields needed to construct a Reporter object""" return { 'cfg': args.cfg, 'cfg_dir': args.cfg_dir, 'dest_addr': args.report_dest, 'hostname': args.report_hostname, 'tls_cert': args.report_cert, 'tls_key': args.report_key, 'gnupghome': args.report_gnupghome, 'passphrase': args.report_passphrase }
[ "def", "get_report_opts", "(", "args", ")", ":", "return", "{", "'cfg'", ":", "args", ".", "cfg", ",", "'cfg_dir'", ":", "args", ".", "cfg_dir", ",", "'dest_addr'", ":", "args", ".", "report_dest", ",", "'hostname'", ":", "args", ".", "report_hostname", ",", "'tls_cert'", ":", "args", ".", "report_cert", ",", "'tls_key'", ":", "args", ".", "report_key", ",", "'gnupghome'", ":", "args", ".", "report_gnupghome", ",", "'passphrase'", ":", "args", ".", "report_passphrase", "}" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring.py#L18-L29
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring.py
python
add_to_parser
(parser)
Add receiver monitoring options to parser
Add receiver monitoring options to parser
[ "Add", "receiver", "monitoring", "options", "to", "parser" ]
def add_to_parser(parser): """Add receiver monitoring options to parser""" m_p = parser.add_argument_group('receiver logging options') m_p.add_argument( '--log-scrolling', default=False, action='store_true', help='Print receiver logs line-by-line rather than repeatedly on the \ same line') m_p.add_argument('--log-file', default=False, action='store_true', help='Save receiver logs on a file') m_p.add_argument('--log-interval', type=float, default=1.0, help="Logging interval in seconds") ms_p = parser.add_argument_group('receiver monitoring server options') ms_p.add_argument('--monitoring-server', default=False, action='store_true', help='Run HTTP server to monitor the receiver') ms_p.add_argument('--monitoring-port', default=defs.monitor_port, type=int, help='Monitoring server\'s port') r_p = parser.add_argument_group('receiver reporting options') r_p.add_argument('--report', default=False, action='store_true', help='Report receiver metrics to a remote HTTP server') r_p.add_argument( '--report-dest', default=monitoring_api.metric_endpoint, help='Destination address in http://ip:port format. By default, ' 'report to Blockstream\'s Satellite Monitoring API') r_p.add_argument('--report-hostname', help='Reporter\'s hostname') r_p.add_argument( '--report-cert', default=None, help="Certificate for client-side authentication with the destination") r_p.add_argument( '--report-key', default=None, help="Private key for client-side authentication with the destination") r_p.add_argument( '--report-gnupghome', default=".gnupg", help="GnuPG home directory, by default created inside the config " "directory specified via --cfg-dir option. This option is used when " "reporting to Blockstream's Satellite Monitoring API only, where it " "determines the name of the directory (inside --cfg-dir) that holds " "the key for authentication with the API") r_p.add_argument( '--report-passphrase', default=None, help="Passphrase to the private GnuPG key used to sign receiver " "status reports sent to Blockstream's Satellite Monitoring API. If " "undefined (default), the program prompts for this passphrase instead." )
[ "def", "add_to_parser", "(", "parser", ")", ":", "m_p", "=", "parser", ".", "add_argument_group", "(", "'receiver logging options'", ")", "m_p", ".", "add_argument", "(", "'--log-scrolling'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'Print receiver logs line-by-line rather than repeatedly on the \\\n same line'", ")", "m_p", ".", "add_argument", "(", "'--log-file'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'Save receiver logs on a file'", ")", "m_p", ".", "add_argument", "(", "'--log-interval'", ",", "type", "=", "float", ",", "default", "=", "1.0", ",", "help", "=", "\"Logging interval in seconds\"", ")", "ms_p", "=", "parser", ".", "add_argument_group", "(", "'receiver monitoring server options'", ")", "ms_p", ".", "add_argument", "(", "'--monitoring-server'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'Run HTTP server to monitor the receiver'", ")", "ms_p", ".", "add_argument", "(", "'--monitoring-port'", ",", "default", "=", "defs", ".", "monitor_port", ",", "type", "=", "int", ",", "help", "=", "'Monitoring server\\'s port'", ")", "r_p", "=", "parser", ".", "add_argument_group", "(", "'receiver reporting options'", ")", "r_p", ".", "add_argument", "(", "'--report'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'Report receiver metrics to a remote HTTP server'", ")", "r_p", ".", "add_argument", "(", "'--report-dest'", ",", "default", "=", "monitoring_api", ".", "metric_endpoint", ",", "help", "=", "'Destination address in http://ip:port format. By default, '", "'report to Blockstream\\'s Satellite Monitoring API'", ")", "r_p", ".", "add_argument", "(", "'--report-hostname'", ",", "help", "=", "'Reporter\\'s hostname'", ")", "r_p", ".", "add_argument", "(", "'--report-cert'", ",", "default", "=", "None", ",", "help", "=", "\"Certificate for client-side authentication with the destination\"", ")", "r_p", ".", "add_argument", "(", "'--report-key'", ",", "default", "=", "None", ",", "help", "=", "\"Private key for client-side authentication with the destination\"", ")", "r_p", ".", "add_argument", "(", "'--report-gnupghome'", ",", "default", "=", "\".gnupg\"", ",", "help", "=", "\"GnuPG home directory, by default created inside the config \"", "\"directory specified via --cfg-dir option. This option is used when \"", "\"reporting to Blockstream's Satellite Monitoring API only, where it \"", "\"determines the name of the directory (inside --cfg-dir) that holds \"", "\"the key for authentication with the API\"", ")", "r_p", ".", "add_argument", "(", "'--report-passphrase'", ",", "default", "=", "None", ",", "help", "=", "\"Passphrase to the private GnuPG key used to sign receiver \"", "\"status reports sent to Blockstream's Satellite Monitoring API. If \"", "\"undefined (default), the program prompts for this passphrase instead.\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring.py#L378-L439
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring.py
python
Reporter.__init__
(self, cfg, cfg_dir, dest_addr, hostname=None, tls_cert=None, tls_key=None, gnupghome=None, passphrase=None)
Reporter Constructor Args: cfg : User configuration cfg_dir : Configuration directory dest_addr : Remote server address hostname : Hostname used to identify the reports tls_cert : Optional client side certificate for TLS authentication tls_key : Key associated with the client side certificate gnupghome : GnuPG home directory used when reporting to Blockstream's monitoring API passphrase : Passphrase to the private key used when reporting to Blockstream's monitoring API. If None, it will be obtained by prompting the user.
Reporter Constructor
[ "Reporter", "Constructor" ]
def __init__(self, cfg, cfg_dir, dest_addr, hostname=None, tls_cert=None, tls_key=None, gnupghome=None, passphrase=None): """Reporter Constructor Args: cfg : User configuration cfg_dir : Configuration directory dest_addr : Remote server address hostname : Hostname used to identify the reports tls_cert : Optional client side certificate for TLS authentication tls_key : Key associated with the client side certificate gnupghome : GnuPG home directory used when reporting to Blockstream's monitoring API passphrase : Passphrase to the private key used when reporting to Blockstream's monitoring API. If None, it will be obtained by prompting the user. """ info = config.read_cfg_file(cfg, cfg_dir) assert (info is not None) # Validate the satellite satellite = info['sat']['alias'] assert (satellite is not None), "Reporting satellite undefined" assert (satellite in sats), "Invalid satellite" self.satellite = satellite # Destination address, hostname, and client side cert self.dest_addr = dest_addr self.hostname = hostname self.tls_cert = tls_cert self.tls_key = tls_key # If the report destination address corresponds to Blockstream's # Monitoring API (the default), create the object to handle the # interaction with this API (e.g., registration). if (dest_addr == monitoring_api.metric_endpoint): self.bs_monitoring = monitoring_api.BsMonitoring( cfg, cfg_dir, gnupghome, passphrase) else: self.bs_monitoring = None logger.info("Reporting Rx status to {} ".format(self.dest_addr))
[ "def", "__init__", "(", "self", ",", "cfg", ",", "cfg_dir", ",", "dest_addr", ",", "hostname", "=", "None", ",", "tls_cert", "=", "None", ",", "tls_key", "=", "None", ",", "gnupghome", "=", "None", ",", "passphrase", "=", "None", ")", ":", "info", "=", "config", ".", "read_cfg_file", "(", "cfg", ",", "cfg_dir", ")", "assert", "(", "info", "is", "not", "None", ")", "# Validate the satellite", "satellite", "=", "info", "[", "'sat'", "]", "[", "'alias'", "]", "assert", "(", "satellite", "is", "not", "None", ")", ",", "\"Reporting satellite undefined\"", "assert", "(", "satellite", "in", "sats", ")", ",", "\"Invalid satellite\"", "self", ".", "satellite", "=", "satellite", "# Destination address, hostname, and client side cert", "self", ".", "dest_addr", "=", "dest_addr", "self", ".", "hostname", "=", "hostname", "self", ".", "tls_cert", "=", "tls_cert", "self", ".", "tls_key", "=", "tls_key", "# If the report destination address corresponds to Blockstream's", "# Monitoring API (the default), create the object to handle the", "# interaction with this API (e.g., registration).", "if", "(", "dest_addr", "==", "monitoring_api", ".", "metric_endpoint", ")", ":", "self", ".", "bs_monitoring", "=", "monitoring_api", ".", "BsMonitoring", "(", "cfg", ",", "cfg_dir", ",", "gnupghome", ",", "passphrase", ")", "else", ":", "self", ".", "bs_monitoring", "=", "None", "logger", ".", "info", "(", "\"Reporting Rx status to {} \"", ".", "format", "(", "self", ".", "dest_addr", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring.py#L38-L87
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring.py
python
Reporter.send
(self, metrics)
Save measurement on database Args: metrics : Dictionary with receiver metrics to send over the report
Save measurement on database
[ "Save", "measurement", "on", "database" ]
def send(self, metrics): """Save measurement on database Args: metrics : Dictionary with receiver metrics to send over the report """ # When the receiver is not registered with the monitoring API, the # sign-up procedure runs. However, this procedure can only work if the # receiver is locked, given that it requires reception of a validation # code sent exclusively over satellite. Hence, the registration routine # (running on a thread) waits until a threading event is set below to # indicate the Rx lock: if (self.bs_monitoring and not self.bs_monitoring.registered): if ('lock' in metrics and metrics['lock']): self.bs_monitoring.rx_lock_event.set() # If the registration procedure has already stopped and failed, do # not proceed. Reporting would otherwise fail anyway, given that # the monitoring server does not accept reports from non-registered # receivers. Just warn the user and stop right here. if (self.bs_monitoring.registration_failure): print() logger.error("Report failed: registration incomplete " "(relaunch receiver and try again)") # Don't send reports to the monitoring API until the receiver is # properly registered and verified return data = {} data.update(metrics) # When reporting to Blockstream's Monitoring API, sign every set of # reported data using the local GPG key and don't send the satellite # nor the hostname on the requests. This information is already # associated with the account registered with the Monitoring API. In # contrast, when reporting to a general-purpose server, do include the # satellite and hostname information if defined. if (self.bs_monitoring is None): data["satellite"] = self.satellite, if (self.hostname): data['hostname'] = self.hostname else: self.bs_monitoring.sign_report(data) logger.debug("Report {} to {}".format(data, self.dest_addr)) try: r = requests.post(self.dest_addr, json=data, cert=(self.tls_cert, self.tls_key)) if (r.status_code != requests.codes.ok): print() logger.error("Report failed: " + r.text) except requests.exceptions.ConnectionError as e: print() logger.error("Report failed: " + str(e))
[ "def", "send", "(", "self", ",", "metrics", ")", ":", "# When the receiver is not registered with the monitoring API, the", "# sign-up procedure runs. However, this procedure can only work if the", "# receiver is locked, given that it requires reception of a validation", "# code sent exclusively over satellite. Hence, the registration routine", "# (running on a thread) waits until a threading event is set below to", "# indicate the Rx lock:", "if", "(", "self", ".", "bs_monitoring", "and", "not", "self", ".", "bs_monitoring", ".", "registered", ")", ":", "if", "(", "'lock'", "in", "metrics", "and", "metrics", "[", "'lock'", "]", ")", ":", "self", ".", "bs_monitoring", ".", "rx_lock_event", ".", "set", "(", ")", "# If the registration procedure has already stopped and failed, do", "# not proceed. Reporting would otherwise fail anyway, given that", "# the monitoring server does not accept reports from non-registered", "# receivers. Just warn the user and stop right here.", "if", "(", "self", ".", "bs_monitoring", ".", "registration_failure", ")", ":", "print", "(", ")", "logger", ".", "error", "(", "\"Report failed: registration incomplete \"", "\"(relaunch receiver and try again)\"", ")", "# Don't send reports to the monitoring API until the receiver is", "# properly registered and verified", "return", "data", "=", "{", "}", "data", ".", "update", "(", "metrics", ")", "# When reporting to Blockstream's Monitoring API, sign every set of", "# reported data using the local GPG key and don't send the satellite", "# nor the hostname on the requests. This information is already", "# associated with the account registered with the Monitoring API. In", "# contrast, when reporting to a general-purpose server, do include the", "# satellite and hostname information if defined.", "if", "(", "self", ".", "bs_monitoring", "is", "None", ")", ":", "data", "[", "\"satellite\"", "]", "=", "self", ".", "satellite", ",", "if", "(", "self", ".", "hostname", ")", ":", "data", "[", "'hostname'", "]", "=", "self", ".", "hostname", "else", ":", "self", ".", "bs_monitoring", ".", "sign_report", "(", "data", ")", "logger", ".", "debug", "(", "\"Report {} to {}\"", ".", "format", "(", "data", ",", "self", ".", "dest_addr", ")", ")", "try", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "dest_addr", ",", "json", "=", "data", ",", "cert", "=", "(", "self", ".", "tls_cert", ",", "self", ".", "tls_key", ")", ")", "if", "(", "r", ".", "status_code", "!=", "requests", ".", "codes", ".", "ok", ")", ":", "print", "(", ")", "logger", ".", "error", "(", "\"Report failed: \"", "+", "r", ".", "text", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "e", ":", "print", "(", ")", "logger", ".", "error", "(", "\"Report failed: \"", "+", "str", "(", "e", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring.py#L89-L145
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring.py
python
Monitor.__init__
(self, cfg_dir, logfile=False, scroll=False, echo=True, min_interval=1.0, server=False, port=defs.monitor_port, report=False, report_opts={}, utc=True)
Monitor Constructor Args: cfg_dir : Configuration directory where logs are saved logfile : Whether to dump logs into a file scroll : Whether to print logs with scrolling or continuously overwrite the same line echo : Whether to echo (print) every update to receiver metrics to stdout. min_interval : Minimum interval in seconds between logs echoed or saved. server : Launch server to reply the receiver status via HTTP. port : Server's HTTP port, if enabled. report : Whether to report the receiver status over HTTP to a remote address. report_opts : Reporter options. utc : Whether to print logs in UTC time.
Monitor Constructor
[ "Monitor", "Constructor" ]
def __init__(self, cfg_dir, logfile=False, scroll=False, echo=True, min_interval=1.0, server=False, port=defs.monitor_port, report=False, report_opts={}, utc=True): """Monitor Constructor Args: cfg_dir : Configuration directory where logs are saved logfile : Whether to dump logs into a file scroll : Whether to print logs with scrolling or continuously overwrite the same line echo : Whether to echo (print) every update to receiver metrics to stdout. min_interval : Minimum interval in seconds between logs echoed or saved. server : Launch server to reply the receiver status via HTTP. port : Server's HTTP port, if enabled. report : Whether to report the receiver status over HTTP to a remote address. report_opts : Reporter options. utc : Whether to print logs in UTC time. """ self.cfg_dir = cfg_dir self.logfile = None self.scroll = scroll self.echo = echo self.min_interval = min_interval self.report = report self.utc = utc if (logfile): self._setup_logfile() # Supported receiver metrics, with their labels and printing formats self._metrics = { 'lock': { 'label': 'Lock', 'format_str': '' }, 'level': { 'label': 'Level', 'format_str': '.2f' }, 'snr': { 'label': 'SNR', 'format_str': '.2f' }, 'ber': { 'label': 'BER', 'format_str': '.2e' }, 'quality': { 'label': 'Signal Quality', 'format_str': '.1f' }, 'pkt_err': { 'label': 'Packet Errors', 'format_str': 'd' } } self.stats = {} # Reporter sessions if (report): self.reporter = Reporter(**report_opts) # State self.t_last_print = time.time() # Launch HTTP server on a daemon thread if (server): self.sever_thread = threading.Thread(target=self._run_server, args=(port, ), daemon=True) self.sever_thread.start()
[ "def", "__init__", "(", "self", ",", "cfg_dir", ",", "logfile", "=", "False", ",", "scroll", "=", "False", ",", "echo", "=", "True", ",", "min_interval", "=", "1.0", ",", "server", "=", "False", ",", "port", "=", "defs", ".", "monitor_port", ",", "report", "=", "False", ",", "report_opts", "=", "{", "}", ",", "utc", "=", "True", ")", ":", "self", ".", "cfg_dir", "=", "cfg_dir", "self", ".", "logfile", "=", "None", "self", ".", "scroll", "=", "scroll", "self", ".", "echo", "=", "echo", "self", ".", "min_interval", "=", "min_interval", "self", ".", "report", "=", "report", "self", ".", "utc", "=", "utc", "if", "(", "logfile", ")", ":", "self", ".", "_setup_logfile", "(", ")", "# Supported receiver metrics, with their labels and printing formats", "self", ".", "_metrics", "=", "{", "'lock'", ":", "{", "'label'", ":", "'Lock'", ",", "'format_str'", ":", "''", "}", ",", "'level'", ":", "{", "'label'", ":", "'Level'", ",", "'format_str'", ":", "'.2f'", "}", ",", "'snr'", ":", "{", "'label'", ":", "'SNR'", ",", "'format_str'", ":", "'.2f'", "}", ",", "'ber'", ":", "{", "'label'", ":", "'BER'", ",", "'format_str'", ":", "'.2e'", "}", ",", "'quality'", ":", "{", "'label'", ":", "'Signal Quality'", ",", "'format_str'", ":", "'.1f'", "}", ",", "'pkt_err'", ":", "{", "'label'", ":", "'Packet Errors'", ",", "'format_str'", ":", "'d'", "}", "}", "self", ".", "stats", "=", "{", "}", "# Reporter sessions", "if", "(", "report", ")", ":", "self", ".", "reporter", "=", "Reporter", "(", "*", "*", "report_opts", ")", "# State", "self", ".", "t_last_print", "=", "time", ".", "time", "(", ")", "# Launch HTTP server on a daemon thread", "if", "(", "server", ")", ":", "self", ".", "sever_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_run_server", ",", "args", "=", "(", "port", ",", ")", ",", "daemon", "=", "True", ")", "self", ".", "sever_thread", ".", "start", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring.py#L172-L253
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring.py
python
Monitor._run_server
(self, port)
Run HTTP server with access to the Monitor object
Run HTTP server with access to the Monitor object
[ "Run", "HTTP", "server", "with", "access", "to", "the", "Monitor", "object" ]
def _run_server(self, port): """Run HTTP server with access to the Monitor object""" server_address = ('', port) Server.monitor = self self.httpd = HTTPServer(server_address, Server) self.httpd.serve_forever()
[ "def", "_run_server", "(", "self", ",", "port", ")", ":", "server_address", "=", "(", "''", ",", "port", ")", "Server", ".", "monitor", "=", "self", "self", ".", "httpd", "=", "HTTPServer", "(", "server_address", ",", "Server", ")", "self", ".", "httpd", ".", "serve_forever", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring.py#L255-L260
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring.py
python
Monitor.__str__
(self)
return string
Return string containing the receiver stats
Return string containing the receiver stats
[ "Return", "string", "containing", "the", "receiver", "stats" ]
def __str__(self): """Return string containing the receiver stats""" if (self.utc): timestamp = time.gmtime() else: timestamp = time.localtime() t_now = time.strftime("%Y-%m-%d %H:%M:%S", timestamp) string = "{} ".format(t_now) for key in self._metrics.keys(): if key in self.stats: val = self.stats[key] # Label=Value string += " {} = {:{fmt_str}}".format( self._metrics[key]['label'], val[0], fmt_str=self._metrics[key]['format_str'], ) # Unit if (not math.isnan(val[0]) and val[1]): string += val[1] string += ";" return string
[ "def", "__str__", "(", "self", ")", ":", "if", "(", "self", ".", "utc", ")", ":", "timestamp", "=", "time", ".", "gmtime", "(", ")", "else", ":", "timestamp", "=", "time", ".", "localtime", "(", ")", "t_now", "=", "time", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ",", "timestamp", ")", "string", "=", "\"{} \"", ".", "format", "(", "t_now", ")", "for", "key", "in", "self", ".", "_metrics", ".", "keys", "(", ")", ":", "if", "key", "in", "self", ".", "stats", ":", "val", "=", "self", ".", "stats", "[", "key", "]", "# Label=Value", "string", "+=", "\" {} = {:{fmt_str}}\"", ".", "format", "(", "self", ".", "_metrics", "[", "key", "]", "[", "'label'", "]", ",", "val", "[", "0", "]", ",", "fmt_str", "=", "self", ".", "_metrics", "[", "key", "]", "[", "'format_str'", "]", ",", ")", "# Unit", "if", "(", "not", "math", ".", "isnan", "(", "val", "[", "0", "]", ")", "and", "val", "[", "1", "]", ")", ":", "string", "+=", "val", "[", "1", "]", "string", "+=", "\";\"", "return", "string" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring.py#L262-L287
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring.py
python
Monitor._setup_logfile
(self)
Setup directory and file for logs
Setup directory and file for logs
[ "Setup", "directory", "and", "file", "for", "logs" ]
def _setup_logfile(self): """Setup directory and file for logs""" log_dir = os.path.join(self.cfg_dir, "logs") if not os.path.exists(log_dir): os.makedirs(log_dir) name = time.strftime("%Y%m%d-%H%M%S") + ".log" self.logfile = os.path.join(log_dir, name) logger.info("Saving logs at {}".format(self.logfile))
[ "def", "_setup_logfile", "(", "self", ")", ":", "log_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cfg_dir", ",", "\"logs\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "log_dir", ")", ":", "os", ".", "makedirs", "(", "log_dir", ")", "name", "=", "time", ".", "strftime", "(", "\"%Y%m%d-%H%M%S\"", ")", "+", "\".log\"", "self", ".", "logfile", "=", "os", ".", "path", ".", "join", "(", "log_dir", ",", "name", ")", "logger", ".", "info", "(", "\"Saving logs at {}\"", ".", "format", "(", "self", ".", "logfile", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring.py#L289-L297
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring.py
python
Monitor.get_stats
(self, strip_unit=True)
return res
Get dictionary with the receiver stats Args: strip unit : Return the values directly, instead of tuples containing the value and its unit.
Get dictionary with the receiver stats
[ "Get", "dictionary", "with", "the", "receiver", "stats" ]
def get_stats(self, strip_unit=True): """Get dictionary with the receiver stats Args: strip unit : Return the values directly, instead of tuples containing the value and its unit. """ if (not strip_unit): res = self.stats.copy() else: res = {} for key, val in self.stats.items(): res[key] = val[0] return res
[ "def", "get_stats", "(", "self", ",", "strip_unit", "=", "True", ")", ":", "if", "(", "not", "strip_unit", ")", ":", "res", "=", "self", ".", "stats", ".", "copy", "(", ")", "else", ":", "res", "=", "{", "}", "for", "key", ",", "val", "in", "self", ".", "stats", ".", "items", "(", ")", ":", "res", "[", "key", "]", "=", "val", "[", "0", "]", "return", "res" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring.py#L299-L314
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring.py
python
Monitor.update
(self, data)
Update the receiver stats kept internally Args: data : Dictionary of tuples corresponding to the receiver metrics. Each tuple should consist of the value and its unit.
Update the receiver stats kept internally
[ "Update", "the", "receiver", "stats", "kept", "internally" ]
def update(self, data): """Update the receiver stats kept internally Args: data : Dictionary of tuples corresponding to the receiver metrics. Each tuple should consist of the value and its unit. """ # The input should be a dictionary of tuples assert (isinstance(data, dict)) assert (all([isinstance(x, tuple) for x in data.values()])) # All keys in the input dictionary must be supported receiver metrics assert (all([k in self._metrics for k in data.keys()])) # Copy all the data self.stats = data # Is it time to log a new line? t_now = time.time() if (t_now - self.t_last_print) < self.min_interval: return self.t_last_print = t_now # Append metrics to log file if (self.logfile): with open(self.logfile, 'a') as fd: fd.write(str(self) + "\n") # Report over HTTP to a remote address if (self.report): self.reporter.send(self.get_stats()) # If the reporter object is configured to report to the Monitoring # API but, at this point, it is still waiting for registration to # complete, don't log the status to the console yet. Otherwise, the # user would likely miss the logs indicating completion of the # registration procedure. On the other hand, if a log file is # enabled, it is OK to log into it throughout the registration. # # Besides, if the reporter is configured to report to the # Monitoring API and the registration is not complete yet, the # above call does not really send the report yet. Nevertheless, it # is still required. Refer to the implementation. # # As soon as the registration procedure ends (as indicated by the # "registration_running" flag), console logs are reactivated, even # if the registration fails. if (self.reporter.bs_monitoring is not None and not self.reporter.bs_monitoring.registered and self.reporter.bs_monitoring.registration_running): return # Print to console if (self.echo): print_end = '\n' if self.scroll else '\r' if (not self.scroll): sys.stdout.write("\033[K") print(str(self), end=print_end)
[ "def", "update", "(", "self", ",", "data", ")", ":", "# The input should be a dictionary of tuples", "assert", "(", "isinstance", "(", "data", ",", "dict", ")", ")", "assert", "(", "all", "(", "[", "isinstance", "(", "x", ",", "tuple", ")", "for", "x", "in", "data", ".", "values", "(", ")", "]", ")", ")", "# All keys in the input dictionary must be supported receiver metrics", "assert", "(", "all", "(", "[", "k", "in", "self", ".", "_metrics", "for", "k", "in", "data", ".", "keys", "(", ")", "]", ")", ")", "# Copy all the data", "self", ".", "stats", "=", "data", "# Is it time to log a new line?", "t_now", "=", "time", ".", "time", "(", ")", "if", "(", "t_now", "-", "self", ".", "t_last_print", ")", "<", "self", ".", "min_interval", ":", "return", "self", ".", "t_last_print", "=", "t_now", "# Append metrics to log file", "if", "(", "self", ".", "logfile", ")", ":", "with", "open", "(", "self", ".", "logfile", ",", "'a'", ")", "as", "fd", ":", "fd", ".", "write", "(", "str", "(", "self", ")", "+", "\"\\n\"", ")", "# Report over HTTP to a remote address", "if", "(", "self", ".", "report", ")", ":", "self", ".", "reporter", ".", "send", "(", "self", ".", "get_stats", "(", ")", ")", "# If the reporter object is configured to report to the Monitoring", "# API but, at this point, it is still waiting for registration to", "# complete, don't log the status to the console yet. Otherwise, the", "# user would likely miss the logs indicating completion of the", "# registration procedure. On the other hand, if a log file is", "# enabled, it is OK to log into it throughout the registration.", "#", "# Besides, if the reporter is configured to report to the", "# Monitoring API and the registration is not complete yet, the", "# above call does not really send the report yet. Nevertheless, it", "# is still required. Refer to the implementation.", "#", "# As soon as the registration procedure ends (as indicated by the", "# \"registration_running\" flag), console logs are reactivated, even", "# if the registration fails.", "if", "(", "self", ".", "reporter", ".", "bs_monitoring", "is", "not", "None", "and", "not", "self", ".", "reporter", ".", "bs_monitoring", ".", "registered", "and", "self", ".", "reporter", ".", "bs_monitoring", ".", "registration_running", ")", ":", "return", "# Print to console", "if", "(", "self", ".", "echo", ")", ":", "print_end", "=", "'\\n'", "if", "self", ".", "scroll", "else", "'\\r'", "if", "(", "not", "self", ".", "scroll", ")", ":", "sys", ".", "stdout", ".", "write", "(", "\"\\033[K\"", ")", "print", "(", "str", "(", "self", ")", ",", "end", "=", "print_end", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring.py#L316-L375
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/upnp.py
python
parse_http_header
(header, header_key)
Parse HTTP header value Parse the value of a specific header from a RAW HTTP response. :param header: String containing the RAW HTTP response and headers :type header: str :param header_key: The header name of which to extract a value from :type header_key: str :return: The value of the header :rtype: str
Parse HTTP header value
[ "Parse", "HTTP", "header", "value" ]
def parse_http_header(header, header_key): """Parse HTTP header value Parse the value of a specific header from a RAW HTTP response. :param header: String containing the RAW HTTP response and headers :type header: str :param header_key: The header name of which to extract a value from :type header_key: str :return: The value of the header :rtype: str """ split_headers = header.split('\r\n') for entry in split_headers: header = entry.strip().split(':', 1) if header[0].strip().lower() == header_key.strip().lower(): return ''.join(header[1::]).split()[0]
[ "def", "parse_http_header", "(", "header", ",", "header_key", ")", ":", "split_headers", "=", "header", ".", "split", "(", "'\\r\\n'", ")", "for", "entry", "in", "split_headers", ":", "header", "=", "entry", ".", "strip", "(", ")", ".", "split", "(", "':'", ",", "1", ")", "if", "header", "[", "0", "]", ".", "strip", "(", ")", ".", "lower", "(", ")", "==", "header_key", ".", "strip", "(", ")", ".", "lower", "(", ")", ":", "return", "''", ".", "join", "(", "header", "[", "1", ":", ":", "]", ")", ".", "split", "(", ")", "[", "0", "]" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/upnp.py#L44-L63
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/upnp.py
python
make_http_request
(url, data=None, headers=None)
return urllib.request.urlopen(request)
Helper function for making HTTP requests Helper function for making HTTP requests using urllib. :param url: The URL to which a request should be made :type url: str :param data: Provide data for the request. Request method will be set to POST if data is provided :type data: str :param headers: Provide headers to send with the request :type headers: dict :return: A urllib.Request.urlopen object :rtype: urllib.Request.urlopen
Helper function for making HTTP requests
[ "Helper", "function", "for", "making", "HTTP", "requests" ]
def make_http_request(url, data=None, headers=None): """Helper function for making HTTP requests Helper function for making HTTP requests using urllib. :param url: The URL to which a request should be made :type url: str :param data: Provide data for the request. Request method will be set to POST if data is provided :type data: str :param headers: Provide headers to send with the request :type headers: dict :return: A urllib.Request.urlopen object :rtype: urllib.Request.urlopen """ if not headers: headers = {} # If data is provided the request method will automatically be set to POST # by urllib request = urllib.request.Request(url, data=data, headers=headers) return urllib.request.urlopen(request)
[ "def", "make_http_request", "(", "url", ",", "data", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "not", "headers", ":", "headers", "=", "{", "}", "# If data is provided the request method will automatically be set to POST", "# by urllib", "request", "=", "urllib", ".", "request", ".", "Request", "(", "url", ",", "data", "=", "data", ",", "headers", "=", "headers", ")", "return", "urllib", ".", "request", ".", "urlopen", "(", "request", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/upnp.py#L66-L88
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/upnp.py
python
_device_description_required
(func)
return wrapper
Decorator for checking whether the device description is available on a device.
Decorator for checking whether the device description is available on a device.
[ "Decorator", "for", "checking", "whether", "the", "device", "description", "is", "available", "on", "a", "device", "." ]
def _device_description_required(func): """Decorator for checking whether the device description is available on a device. """ @wraps(func) def wrapper(device, *args, **kwargs): if device.description is None: raise NotRetrievedError( 'No device description retrieved for this device.') elif device.description == NotAvailableError: return return func(device, *args, **kwargs) return wrapper
[ "def", "_device_description_required", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "device", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "device", ".", "description", "is", "None", ":", "raise", "NotRetrievedError", "(", "'No device description retrieved for this device.'", ")", "elif", "device", ".", "description", "==", "NotAvailableError", ":", "return", "return", "func", "(", "device", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/upnp.py#L91-L105
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/upnp.py
python
_get_if_index
(ifname, fd)
return int(struct.unpack('16si', res)[1])
Get the index corresponding to interface ifname used by socket fd
Get the index corresponding to interface ifname used by socket fd
[ "Get", "the", "index", "corresponding", "to", "interface", "ifname", "used", "by", "socket", "fd" ]
def _get_if_index(ifname, fd): """Get the index corresponding to interface ifname used by socket fd""" ifreq = struct.pack('16si', ifname.encode(), 0) res = fcntl.ioctl(fd, SIOCGIFINDEX, ifreq) return int(struct.unpack('16si', res)[1])
[ "def", "_get_if_index", "(", "ifname", ",", "fd", ")", ":", "ifreq", "=", "struct", ".", "pack", "(", "'16si'", ",", "ifname", ".", "encode", "(", ")", ",", "0", ")", "res", "=", "fcntl", ".", "ioctl", "(", "fd", ",", "SIOCGIFINDEX", ",", "ifreq", ")", "return", "int", "(", "struct", ".", "unpack", "(", "'16si'", ",", "res", ")", "[", "1", "]", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/upnp.py#L108-L112
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/upnp.py
python
SSDPDevice.get_friendly_name
(self)
return self.friendly_name
Get the friendly name for the device Gets the device's friendly name :return: Friendly name of the device :rtype: str
Get the friendly name for the device
[ "Get", "the", "friendly", "name", "for", "the", "device" ]
def get_friendly_name(self): """Get the friendly name for the device Gets the device's friendly name :return: Friendly name of the device :rtype: str """ return self.friendly_name
[ "def", "get_friendly_name", "(", "self", ")", ":", "return", "self", ".", "friendly_name" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/upnp.py#L141-L150
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/upnp.py
python
SSDPHeader.__init__
(self, **headers)
Example M-SEARCH header: ------------------------------------------------------------------------ M-SEARCH * HTTP/1.1 SSDP method for search requests HOST: 239.255.255.250:1900 SSDP multicast address and port (REQUIRED) MAN: "ssdp:discover" HTTP Extension Framework scope (REQUIRED) MX: 2 Maximum wait time in seconds (REQUIRED) ST: upnp:rootdevice Search target (REQUIRED) ------------------------------------------------------------------------
Example M-SEARCH header: ------------------------------------------------------------------------ M-SEARCH * HTTP/1.1 SSDP method for search requests HOST: 239.255.255.250:1900 SSDP multicast address and port (REQUIRED) MAN: "ssdp:discover" HTTP Extension Framework scope (REQUIRED) MX: 2 Maximum wait time in seconds (REQUIRED) ST: upnp:rootdevice Search target (REQUIRED) ------------------------------------------------------------------------
[ "Example", "M", "-", "SEARCH", "header", ":", "------------------------------------------------------------------------", "M", "-", "SEARCH", "*", "HTTP", "/", "1", ".", "1", "SSDP", "method", "for", "search", "requests", "HOST", ":", "239", ".", "255", ".", "255", ".", "250", ":", "1900", "SSDP", "multicast", "address", "and", "port", "(", "REQUIRED", ")", "MAN", ":", "ssdp", ":", "discover", "HTTP", "Extension", "Framework", "scope", "(", "REQUIRED", ")", "MX", ":", "2", "Maximum", "wait", "time", "in", "seconds", "(", "REQUIRED", ")", "ST", ":", "upnp", ":", "rootdevice", "Search", "target", "(", "REQUIRED", ")", "------------------------------------------------------------------------" ]
def __init__(self, **headers): """ Example M-SEARCH header: ------------------------------------------------------------------------ M-SEARCH * HTTP/1.1 SSDP method for search requests HOST: 239.255.255.250:1900 SSDP multicast address and port (REQUIRED) MAN: "ssdp:discover" HTTP Extension Framework scope (REQUIRED) MX: 2 Maximum wait time in seconds (REQUIRED) ST: upnp:rootdevice Search target (REQUIRED) ------------------------------------------------------------------------ """ self.headers = {} self.set_headers(**headers) self._available_methods = ['M-SEARCH'] self.method = None self.host = self.headers.get('HOST') self.man = self.headers.get('MAN') self.mx = self.headers.get('MX') self.st = self.headers.get('ST')
[ "def", "__init__", "(", "self", ",", "*", "*", "headers", ")", ":", "self", ".", "headers", "=", "{", "}", "self", ".", "set_headers", "(", "*", "*", "headers", ")", "self", ".", "_available_methods", "=", "[", "'M-SEARCH'", "]", "self", ".", "method", "=", "None", "self", ".", "host", "=", "self", ".", "headers", ".", "get", "(", "'HOST'", ")", "self", ".", "man", "=", "self", ".", "headers", ".", "get", "(", "'MAN'", ")", "self", ".", "mx", "=", "self", ".", "headers", ".", "get", "(", "'MX'", ")", "self", ".", "st", "=", "self", ".", "headers", ".", "get", "(", "'ST'", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/upnp.py#L202-L222
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/upnp.py
python
SSDPRequest.m_search
(self, discover_delay=2, st='ssdp:all', **headers)
Perform an M-SEARCH SSDP request Send an SSDP M-SEARCH request for finding UPnP devices on the network. :param discover_delay: Device discovery delay in seconds :type discover_delay: int :param st: Specify device Search Target :type st: str :param headers: Specify M-SEARCH specific headers :type headers: str :return: List of device that replied :rtype: list
Perform an M-SEARCH SSDP request
[ "Perform", "an", "M", "-", "SEARCH", "SSDP", "request" ]
def m_search(self, discover_delay=2, st='ssdp:all', **headers): """Perform an M-SEARCH SSDP request Send an SSDP M-SEARCH request for finding UPnP devices on the network. :param discover_delay: Device discovery delay in seconds :type discover_delay: int :param st: Specify device Search Target :type st: str :param headers: Specify M-SEARCH specific headers :type headers: str :return: List of device that replied :rtype: list """ self.set_method('M-SEARCH') self.set_header('MAN', '"ssdp:discover"') self.set_header('MX', discover_delay) self.set_header('ST', st) self.set_headers(**headers) self.socket.settimeout(discover_delay) devices = self._send_request(self._get_raw_request()) for device in devices: yield device
[ "def", "m_search", "(", "self", ",", "discover_delay", "=", "2", ",", "st", "=", "'ssdp:all'", ",", "*", "*", "headers", ")", ":", "self", ".", "set_method", "(", "'M-SEARCH'", ")", "self", ".", "set_header", "(", "'MAN'", ",", "'\"ssdp:discover\"'", ")", "self", ".", "set_header", "(", "'MX'", ",", "discover_delay", ")", "self", ".", "set_header", "(", "'ST'", ",", "st", ")", "self", ".", "set_headers", "(", "*", "*", "headers", ")", "self", ".", "socket", ".", "settimeout", "(", "discover_delay", ")", "devices", "=", "self", ".", "_send_request", "(", "self", ".", "_get_raw_request", "(", ")", ")", "for", "device", "in", "devices", ":", "yield", "device" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/upnp.py#L297-L324
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/upnp.py
python
SSDPRequest._get_raw_request
(self)
return final_request_data
Get raw request data to send to server
Get raw request data to send to server
[ "Get", "raw", "request", "data", "to", "send", "to", "server" ]
def _get_raw_request(self): """Get raw request data to send to server""" final_request_data = '' if self.method is not None: ssdp_start_line = '{} * HTTP/1.1'.format(self.method) else: ssdp_start_line = 'HTTP/1.1 200 OK' final_request_data += '{}\r\n'.format(ssdp_start_line) for header, value in self.headers.items(): final_request_data += '{}: {}\r\n'.format(header, value) final_request_data += '\r\n' return final_request_data
[ "def", "_get_raw_request", "(", "self", ")", ":", "final_request_data", "=", "''", "if", "self", ".", "method", "is", "not", "None", ":", "ssdp_start_line", "=", "'{} * HTTP/1.1'", ".", "format", "(", "self", ".", "method", ")", "else", ":", "ssdp_start_line", "=", "'HTTP/1.1 200 OK'", "final_request_data", "+=", "'{}\\r\\n'", ".", "format", "(", "ssdp_start_line", ")", "for", "header", ",", "value", "in", "self", ".", "headers", ".", "items", "(", ")", ":", "final_request_data", "+=", "'{}: {}\\r\\n'", ".", "format", "(", "header", ",", "value", ")", "final_request_data", "+=", "'\\r\\n'", "return", "final_request_data" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/upnp.py#L326-L343
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/upnp.py
python
UPnP.discover
(self, delay=2, **headers)
return self.discovered_devices
Find UPnP devices on the network Find available UPnP devices on the network by sending an M-SEARCH request. :param delay: Discovery delay, amount of time in seconds to wait for a reply from devices :type delay: int :param headers: Optional headers for the request :return: List of discovered devices :rtype: list
Find UPnP devices on the network
[ "Find", "UPnP", "devices", "on", "the", "network" ]
def discover(self, delay=2, **headers): """Find UPnP devices on the network Find available UPnP devices on the network by sending an M-SEARCH request. :param delay: Discovery delay, amount of time in seconds to wait for a reply from devices :type delay: int :param headers: Optional headers for the request :return: List of discovered devices :rtype: list """ discovered_devices = [] for device in self.ssdp.m_search(discover_delay=delay, st='upnp:rootdevice', **headers): discovered_devices.append(device) self.discovered_devices = discovered_devices return self.discovered_devices
[ "def", "discover", "(", "self", ",", "delay", "=", "2", ",", "*", "*", "headers", ")", ":", "discovered_devices", "=", "[", "]", "for", "device", "in", "self", ".", "ssdp", ".", "m_search", "(", "discover_delay", "=", "delay", ",", "st", "=", "'upnp:rootdevice'", ",", "*", "*", "headers", ")", ":", "discovered_devices", ".", "append", "(", "device", ")", "self", ".", "discovered_devices", "=", "discovered_devices", "return", "self", ".", "discovered_devices" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/upnp.py#L379-L401
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_cfg_satellite
()
return sat
Configure satellite covering the user
Configure satellite covering the user
[ "Configure", "satellite", "covering", "the", "user" ]
def _cfg_satellite(): """Configure satellite covering the user""" os.system('clear') util.print_header("Satellite") help_msg = "Not sure? Check the coverage map at:\n" \ "https://blockstream.com/satellite/#satellite_network-coverage" question = "Which satellite below covers your location?" sat = util.ask_multiple_choice( defs.satellites, question, "Satellite", lambda sat: '{} ({})'.format(sat['name'], sat['alias']), help_msg) return sat
[ "def", "_cfg_satellite", "(", ")", ":", "os", ".", "system", "(", "'clear'", ")", "util", ".", "print_header", "(", "\"Satellite\"", ")", "help_msg", "=", "\"Not sure? Check the coverage map at:\\n\"", "\"https://blockstream.com/satellite/#satellite_network-coverage\"", "question", "=", "\"Which satellite below covers your location?\"", "sat", "=", "util", ".", "ask_multiple_choice", "(", "defs", ".", "satellites", ",", "question", ",", "\"Satellite\"", ",", "lambda", "sat", ":", "'{} ({})'", ".", "format", "(", "sat", "[", "'name'", "]", ",", "sat", "[", "'alias'", "]", ")", ",", "help_msg", ")", "return", "sat" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L17-L29
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_get_rx_marketing_name
(rx)
return model
Get the marketed receiver name (including satellite kit name)
Get the marketed receiver name (including satellite kit name)
[ "Get", "the", "marketed", "receiver", "name", "(", "including", "satellite", "kit", "name", ")" ]
def _get_rx_marketing_name(rx): """Get the marketed receiver name (including satellite kit name)""" model = (rx['vendor'] + " " + rx['model']).strip() if model == "Novra S400": model += " (pro kit)" # append elif model == "TBS 5927": model += " (basic kit)" # append elif model == "Selfsat IP22": model = "Blockstream Base Station" # overwrite elif model == "RTL-SDR": model += " software-defined" return model
[ "def", "_get_rx_marketing_name", "(", "rx", ")", ":", "model", "=", "(", "rx", "[", "'vendor'", "]", "+", "\" \"", "+", "rx", "[", "'model'", "]", ")", ".", "strip", "(", ")", "if", "model", "==", "\"Novra S400\"", ":", "model", "+=", "\" (pro kit)\"", "# append", "elif", "model", "==", "\"TBS 5927\"", ":", "model", "+=", "\" (basic kit)\"", "# append", "elif", "model", "==", "\"Selfsat IP22\"", ":", "model", "=", "\"Blockstream Base Station\"", "# overwrite", "elif", "model", "==", "\"RTL-SDR\"", ":", "model", "+=", "\" software-defined\"", "return", "model" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L32-L43
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_get_antenna_name
(x)
return s
Get antenna name for the configuration menu
Get antenna name for the configuration menu
[ "Get", "antenna", "name", "for", "the", "configuration", "menu" ]
def _get_antenna_name(x): """Get antenna name for the configuration menu""" if x['type'] == 'dish': s = 'Satellite Dish ({})'.format(x['label']) elif x['type'] == 'sat-ip': s = 'Blockstream Base Station (Legacy Output)' else: s = 'Blockstream Flat-Panel Antenna' return s
[ "def", "_get_antenna_name", "(", "x", ")", ":", "if", "x", "[", "'type'", "]", "==", "'dish'", ":", "s", "=", "'Satellite Dish ({})'", ".", "format", "(", "x", "[", "'label'", "]", ")", "elif", "x", "[", "'type'", "]", "==", "'sat-ip'", ":", "s", "=", "'Blockstream Base Station (Legacy Output)'", "else", ":", "s", "=", "'Blockstream Flat-Panel Antenna'", "return", "s" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L46-L54
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_ask_antenna
()
return antenna
Configure antenna
Configure antenna
[ "Configure", "antenna" ]
def _ask_antenna(): """Configure antenna""" os.system('clear') util.print_header("Antenna") question = "What kind of antenna are you using?" antenna = util.ask_multiple_choice(defs.antennas, question, "Antenna", _get_antenna_name, none_option=True, none_str="Other") if (antenna is None): size = util.typed_input("Enter size in cm", "Please enter an integer number in cm", in_type=int) antenna = {'label': "custom", 'type': 'dish', 'size': size} return antenna
[ "def", "_ask_antenna", "(", ")", ":", "os", ".", "system", "(", "'clear'", ")", "util", ".", "print_header", "(", "\"Antenna\"", ")", "question", "=", "\"What kind of antenna are you using?\"", "antenna", "=", "util", ".", "ask_multiple_choice", "(", "defs", ".", "antennas", ",", "question", ",", "\"Antenna\"", ",", "_get_antenna_name", ",", "none_option", "=", "True", ",", "none_str", "=", "\"Other\"", ")", "if", "(", "antenna", "is", "None", ")", ":", "size", "=", "util", ".", "typed_input", "(", "\"Enter size in cm\"", ",", "\"Please enter an integer number in cm\"", ",", "in_type", "=", "int", ")", "antenna", "=", "{", "'label'", ":", "\"custom\"", ",", "'type'", ":", "'dish'", ",", "'size'", ":", "size", "}", "return", "antenna" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L57-L76
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_cfg_rx_setup
()
return setup
Configure Rx setup - which receiver user is using
Configure Rx setup - which receiver user is using
[ "Configure", "Rx", "setup", "-", "which", "receiver", "user", "is", "using" ]
def _cfg_rx_setup(): """Configure Rx setup - which receiver user is using """ os.system('clear') util.print_header("Receiver") # Receiver question = "Select your DVB-S2 receiver:" setup = util.ask_multiple_choice( defs.demods, question, "Receiver", lambda x: '{} receiver'.format(_get_rx_marketing_name(x))) # Network interface connected to the standalone receiver if (setup['type'] == defs.standalone_setup_type): try: devices = os.listdir('/sys/class/net/') except FileNotFoundError: devices = None pass question = "Which network interface is connected to the receiver?" if (devices is not None): netdev = util.ask_multiple_choice(devices, question, "Interface", lambda x: '{}'.format(x)) else: netdev = input(question + " ") setup['netdev'] = netdev.strip() custom_ip = util.ask_yes_or_no( "Have you manually assigned a custom IP address to the receiver?", default="n") if (custom_ip): ipv4_addr = util.typed_input("Which IPv4 address?", in_type=IPv4Address) setup["rx_ip"] = str(ipv4_addr) else: setup["rx_ip"] = defs.default_standalone_ip_addr # Define the Sat-IP antenna directly without asking the user if (setup['type'] == defs.sat_ip_setup_type): # NOTE: this works as long as there is a single Sat-IP antenna in the # list. In the future, if other Sat-IP antennas are included, change to # a multiple-choice prompt. for antenna in defs.antennas: if antenna['type'] == 'sat-ip': setup['antenna'] = antenna return setup # We should have returned in the preceding line. raise RuntimeError("Failed to find antenna of {} receiver".format( defs.sat_ip_setup_type)) # Antenna setup['antenna'] = _ask_antenna() return setup
[ "def", "_cfg_rx_setup", "(", ")", ":", "os", ".", "system", "(", "'clear'", ")", "util", ".", "print_header", "(", "\"Receiver\"", ")", "# Receiver", "question", "=", "\"Select your DVB-S2 receiver:\"", "setup", "=", "util", ".", "ask_multiple_choice", "(", "defs", ".", "demods", ",", "question", ",", "\"Receiver\"", ",", "lambda", "x", ":", "'{} receiver'", ".", "format", "(", "_get_rx_marketing_name", "(", "x", ")", ")", ")", "# Network interface connected to the standalone receiver", "if", "(", "setup", "[", "'type'", "]", "==", "defs", ".", "standalone_setup_type", ")", ":", "try", ":", "devices", "=", "os", ".", "listdir", "(", "'/sys/class/net/'", ")", "except", "FileNotFoundError", ":", "devices", "=", "None", "pass", "question", "=", "\"Which network interface is connected to the receiver?\"", "if", "(", "devices", "is", "not", "None", ")", ":", "netdev", "=", "util", ".", "ask_multiple_choice", "(", "devices", ",", "question", ",", "\"Interface\"", ",", "lambda", "x", ":", "'{}'", ".", "format", "(", "x", ")", ")", "else", ":", "netdev", "=", "input", "(", "question", "+", "\" \"", ")", "setup", "[", "'netdev'", "]", "=", "netdev", ".", "strip", "(", ")", "custom_ip", "=", "util", ".", "ask_yes_or_no", "(", "\"Have you manually assigned a custom IP address to the receiver?\"", ",", "default", "=", "\"n\"", ")", "if", "(", "custom_ip", ")", ":", "ipv4_addr", "=", "util", ".", "typed_input", "(", "\"Which IPv4 address?\"", ",", "in_type", "=", "IPv4Address", ")", "setup", "[", "\"rx_ip\"", "]", "=", "str", "(", "ipv4_addr", ")", "else", ":", "setup", "[", "\"rx_ip\"", "]", "=", "defs", ".", "default_standalone_ip_addr", "# Define the Sat-IP antenna directly without asking the user", "if", "(", "setup", "[", "'type'", "]", "==", "defs", ".", "sat_ip_setup_type", ")", ":", "# NOTE: this works as long as there is a single Sat-IP antenna in the", "# list. In the future, if other Sat-IP antennas are included, change to", "# a multiple-choice prompt.", "for", "antenna", "in", "defs", ".", "antennas", ":", "if", "antenna", "[", "'type'", "]", "==", "'sat-ip'", ":", "setup", "[", "'antenna'", "]", "=", "antenna", "return", "setup", "# We should have returned in the preceding line.", "raise", "RuntimeError", "(", "\"Failed to find antenna of {} receiver\"", ".", "format", "(", "defs", ".", "sat_ip_setup_type", ")", ")", "# Antenna", "setup", "[", "'antenna'", "]", "=", "_ask_antenna", "(", ")", "return", "setup" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L79-L133
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_ask_lnb_freq_range
()
return in_range
Prompt the user for the LNB's input frequency range
Prompt the user for the LNB's input frequency range
[ "Prompt", "the", "user", "for", "the", "LNB", "s", "input", "frequency", "range" ]
def _ask_lnb_freq_range(): """Prompt the user for the LNB's input frequency range""" in_range = [] while (True): while (len(in_range) != 2): try: resp = input( "Inform the two extreme frequencies (in MHz) of " "your LNB's frequency range, separated by comma: ") in_range = [float(x) for x in resp.split(",")] except ValueError: continue if (in_range[1] < in_range[0]): in_range = [] print("Please, provide the lowest frequency first, followed by " "the highest.") continue if (in_range[0] < 3000 or in_range[1] < 3000): in_range = [] print("Please, provide the frequencies in MHz.") continue break return in_range
[ "def", "_ask_lnb_freq_range", "(", ")", ":", "in_range", "=", "[", "]", "while", "(", "True", ")", ":", "while", "(", "len", "(", "in_range", ")", "!=", "2", ")", ":", "try", ":", "resp", "=", "input", "(", "\"Inform the two extreme frequencies (in MHz) of \"", "\"your LNB's frequency range, separated by comma: \"", ")", "in_range", "=", "[", "float", "(", "x", ")", "for", "x", "in", "resp", ".", "split", "(", "\",\"", ")", "]", "except", "ValueError", ":", "continue", "if", "(", "in_range", "[", "1", "]", "<", "in_range", "[", "0", "]", ")", ":", "in_range", "=", "[", "]", "print", "(", "\"Please, provide the lowest frequency first, followed by \"", "\"the highest.\"", ")", "continue", "if", "(", "in_range", "[", "0", "]", "<", "3000", "or", "in_range", "[", "1", "]", "<", "3000", ")", ":", "in_range", "=", "[", "]", "print", "(", "\"Please, provide the frequencies in MHz.\"", ")", "continue", "break", "return", "in_range" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L136-L162
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_ask_lnb_lo
(single_lo=True)
return lo_freq
Prompt the user for the LNB's LO frequencies
Prompt the user for the LNB's LO frequencies
[ "Prompt", "the", "user", "for", "the", "LNB", "s", "LO", "frequencies" ]
def _ask_lnb_lo(single_lo=True): """Prompt the user for the LNB's LO frequencies""" if (single_lo): while (True): lo_freq = util.typed_input("LNB LO frequency in MHz", in_type=float) if (lo_freq < 3000): print("Please, provide the frequencies in MHz.") continue break return lo_freq lo_freq = [] while (True): while (len(lo_freq) != 2): try: resp = input("Inform the two LO frequencies in MHz, separated " "by comma: ") lo_freq = [float(x) for x in resp.split(",")] except ValueError: continue if (lo_freq[1] < lo_freq[0]): lo_freq = [] print("Please, provide the low LO frequency first, followed by " "the high LO frequency.") continue if (lo_freq[0] < 3000 or lo_freq[1] < 3000): lo_freq = [] print("Please, provide the frequencies in MHz.") continue break return lo_freq
[ "def", "_ask_lnb_lo", "(", "single_lo", "=", "True", ")", ":", "if", "(", "single_lo", ")", ":", "while", "(", "True", ")", ":", "lo_freq", "=", "util", ".", "typed_input", "(", "\"LNB LO frequency in MHz\"", ",", "in_type", "=", "float", ")", "if", "(", "lo_freq", "<", "3000", ")", ":", "print", "(", "\"Please, provide the frequencies in MHz.\"", ")", "continue", "break", "return", "lo_freq", "lo_freq", "=", "[", "]", "while", "(", "True", ")", ":", "while", "(", "len", "(", "lo_freq", ")", "!=", "2", ")", ":", "try", ":", "resp", "=", "input", "(", "\"Inform the two LO frequencies in MHz, separated \"", "\"by comma: \"", ")", "lo_freq", "=", "[", "float", "(", "x", ")", "for", "x", "in", "resp", ".", "split", "(", "\",\"", ")", "]", "except", "ValueError", ":", "continue", "if", "(", "lo_freq", "[", "1", "]", "<", "lo_freq", "[", "0", "]", ")", ":", "lo_freq", "=", "[", "]", "print", "(", "\"Please, provide the low LO frequency first, followed by \"", "\"the high LO frequency.\"", ")", "continue", "if", "(", "lo_freq", "[", "0", "]", "<", "3000", "or", "lo_freq", "[", "1", "]", "<", "3000", ")", ":", "lo_freq", "=", "[", "]", "print", "(", "\"Please, provide the frequencies in MHz.\"", ")", "continue", "break", "return", "lo_freq" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L165-L202
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_cfg_custom_lnb
(sat)
return { 'vendor': "", 'model': "", 'in_range': custom_lnb_in_range, 'lo_freq': custom_lnb_lo_freq, 'universal': custom_lnb_universal, 'band': custom_lnb_band, 'pol': pol['id'] }
Configure custom LNB based on user-entered specs Args: sat : user's satellite info
Configure custom LNB based on user-entered specs
[ "Configure", "custom", "LNB", "based", "on", "user", "-", "entered", "specs" ]
def _cfg_custom_lnb(sat): """Configure custom LNB based on user-entered specs Args: sat : user's satellite info """ print("\nPlease, inform the specifications of your LNB:") bands = ["C", "Ku"] question = "Frequency band:" custom_lnb_band = util.ask_multiple_choice(bands, question, "Band", lambda x: '{}'.format(x)) if (sat['band'].lower() != custom_lnb_band.lower()): logging.error("You must use a %s band LNB to receive from %s" % (sat['band'], sat['name'])) sys.exit(1) if (custom_lnb_band == "Ku"): custom_lnb_universal = util.ask_yes_or_no( "Is it a Universal Ku band LNB?") if (custom_lnb_universal): # Input frequency range print() util.fill_print("""A Universal Ku band LNB typically covers an input frequency range from 10.7 to 12.75 GHz.""") if (util.ask_yes_or_no("Does your LNB cover this input range " "from 10.7 to 12.75 GHz?")): custom_lnb_in_range = [10700.0, 12750.0] else: custom_lnb_in_range = _ask_lnb_freq_range() # LO print() util.fill_print("""A Universal Ku band LNB has two LO (local oscillator) frequencies. Typically the two frequencies are 9750 MHz and 10600 MHz.""") if (util.ask_yes_or_no("Does your LNB have LO frequencies 9750 " "MHz and 10600 MHz?")): custom_lnb_lo_freq = [9750.0, 10600.0] else: custom_lnb_lo_freq = _ask_lnb_lo(single_lo=False) else: # Non-universal Ku-band LNB custom_lnb_in_range = _ask_lnb_freq_range() custom_lnb_lo_freq = _ask_lnb_lo() else: # C-band LNB custom_lnb_universal = False custom_lnb_in_range = _ask_lnb_freq_range() custom_lnb_lo_freq = _ask_lnb_lo() # Polarization question = "Choose the LNB polarization:" options = [{ 'id': "Dual", 'text': "Dual polarization (horizontal and vertical)" }, { 'id': "H", 'text': "Horizontal" }, { 'id': "V", 'text': "Vertical" }] pol = util.ask_multiple_choice(options, question, "Polarization", lambda x: '{}'.format(x['text'])) return { 'vendor': "", 'model': "", 'in_range': custom_lnb_in_range, 'lo_freq': custom_lnb_lo_freq, 'universal': custom_lnb_universal, 'band': custom_lnb_band, 'pol': pol['id'] }
[ "def", "_cfg_custom_lnb", "(", "sat", ")", ":", "print", "(", "\"\\nPlease, inform the specifications of your LNB:\"", ")", "bands", "=", "[", "\"C\"", ",", "\"Ku\"", "]", "question", "=", "\"Frequency band:\"", "custom_lnb_band", "=", "util", ".", "ask_multiple_choice", "(", "bands", ",", "question", ",", "\"Band\"", ",", "lambda", "x", ":", "'{}'", ".", "format", "(", "x", ")", ")", "if", "(", "sat", "[", "'band'", "]", ".", "lower", "(", ")", "!=", "custom_lnb_band", ".", "lower", "(", ")", ")", ":", "logging", ".", "error", "(", "\"You must use a %s band LNB to receive from %s\"", "%", "(", "sat", "[", "'band'", "]", ",", "sat", "[", "'name'", "]", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "(", "custom_lnb_band", "==", "\"Ku\"", ")", ":", "custom_lnb_universal", "=", "util", ".", "ask_yes_or_no", "(", "\"Is it a Universal Ku band LNB?\"", ")", "if", "(", "custom_lnb_universal", ")", ":", "# Input frequency range", "print", "(", ")", "util", ".", "fill_print", "(", "\"\"\"A Universal Ku band LNB typically covers an\n input frequency range from 10.7 to 12.75 GHz.\"\"\"", ")", "if", "(", "util", ".", "ask_yes_or_no", "(", "\"Does your LNB cover this input range \"", "\"from 10.7 to 12.75 GHz?\"", ")", ")", ":", "custom_lnb_in_range", "=", "[", "10700.0", ",", "12750.0", "]", "else", ":", "custom_lnb_in_range", "=", "_ask_lnb_freq_range", "(", ")", "# LO", "print", "(", ")", "util", ".", "fill_print", "(", "\"\"\"A Universal Ku band LNB has two LO (local\n oscillator) frequencies. Typically the two frequencies are 9750\n MHz and 10600 MHz.\"\"\"", ")", "if", "(", "util", ".", "ask_yes_or_no", "(", "\"Does your LNB have LO frequencies 9750 \"", "\"MHz and 10600 MHz?\"", ")", ")", ":", "custom_lnb_lo_freq", "=", "[", "9750.0", ",", "10600.0", "]", "else", ":", "custom_lnb_lo_freq", "=", "_ask_lnb_lo", "(", "single_lo", "=", "False", ")", "else", ":", "# Non-universal Ku-band LNB", "custom_lnb_in_range", "=", "_ask_lnb_freq_range", "(", ")", "custom_lnb_lo_freq", "=", "_ask_lnb_lo", "(", ")", "else", ":", "# C-band LNB", "custom_lnb_universal", "=", "False", "custom_lnb_in_range", "=", "_ask_lnb_freq_range", "(", ")", "custom_lnb_lo_freq", "=", "_ask_lnb_lo", "(", ")", "# Polarization", "question", "=", "\"Choose the LNB polarization:\"", "options", "=", "[", "{", "'id'", ":", "\"Dual\"", ",", "'text'", ":", "\"Dual polarization (horizontal and vertical)\"", "}", ",", "{", "'id'", ":", "\"H\"", ",", "'text'", ":", "\"Horizontal\"", "}", ",", "{", "'id'", ":", "\"V\"", ",", "'text'", ":", "\"Vertical\"", "}", "]", "pol", "=", "util", ".", "ask_multiple_choice", "(", "options", ",", "question", ",", "\"Polarization\"", ",", "lambda", "x", ":", "'{}'", ".", "format", "(", "x", "[", "'text'", "]", ")", ")", "return", "{", "'vendor'", ":", "\"\"", ",", "'model'", ":", "\"\"", ",", "'in_range'", ":", "custom_lnb_in_range", ",", "'lo_freq'", ":", "custom_lnb_lo_freq", ",", "'universal'", ":", "custom_lnb_universal", ",", "'band'", ":", "custom_lnb_band", ",", "'pol'", ":", "pol", "[", "'id'", "]", "}" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L205-L283
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_sat_freq_in_lnb_range
(sat, lnb)
return sat['dl_freq'] > lnb['in_range'][0] and \ sat['dl_freq'] < lnb['in_range'][1]
Check if the satellite signal is within the LNB input range
Check if the satellite signal is within the LNB input range
[ "Check", "if", "the", "satellite", "signal", "is", "within", "the", "LNB", "input", "range" ]
def _sat_freq_in_lnb_range(sat, lnb): """Check if the satellite signal is within the LNB input range""" return sat['dl_freq'] > lnb['in_range'][0] and \ sat['dl_freq'] < lnb['in_range'][1]
[ "def", "_sat_freq_in_lnb_range", "(", "sat", ",", "lnb", ")", ":", "return", "sat", "[", "'dl_freq'", "]", ">", "lnb", "[", "'in_range'", "]", "[", "0", "]", "and", "sat", "[", "'dl_freq'", "]", "<", "lnb", "[", "'in_range'", "]", "[", "1", "]" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L286-L289
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_ask_lnb
(sat)
return lnb
Ask the user's LNB
Ask the user's LNB
[ "Ask", "the", "user", "s", "LNB" ]
def _ask_lnb(sat): """Ask the user's LNB""" question = "Please, inform your LNB model:" lnb_options = [ lnb for lnb in defs.lnbs if _sat_freq_in_lnb_range(sat, lnb) and lnb['vendor'] != 'Selfsat' ] lnb = util.ask_multiple_choice( lnb_options, question, "LNB", lambda x: "{} {} {}".format( x['vendor'], x['model'], "(Universal Ku band LNBF)" if x['universal'] else ""), none_option=True, none_str="Other") if (lnb is None): lnb = _cfg_custom_lnb(sat) return lnb
[ "def", "_ask_lnb", "(", "sat", ")", ":", "question", "=", "\"Please, inform your LNB model:\"", "lnb_options", "=", "[", "lnb", "for", "lnb", "in", "defs", ".", "lnbs", "if", "_sat_freq_in_lnb_range", "(", "sat", ",", "lnb", ")", "and", "lnb", "[", "'vendor'", "]", "!=", "'Selfsat'", "]", "lnb", "=", "util", ".", "ask_multiple_choice", "(", "lnb_options", ",", "question", ",", "\"LNB\"", ",", "lambda", "x", ":", "\"{} {} {}\"", ".", "format", "(", "x", "[", "'vendor'", "]", ",", "x", "[", "'model'", "]", ",", "\"(Universal Ku band LNBF)\"", "if", "x", "[", "'universal'", "]", "else", "\"\"", ")", ",", "none_option", "=", "True", ",", "none_str", "=", "\"Other\"", ")", "if", "(", "lnb", "is", "None", ")", ":", "lnb", "=", "_cfg_custom_lnb", "(", "sat", ")", "return", "lnb" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L292-L312
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_ask_psu_voltage
(question)
return voltage
Prompt for the power inserter model or voltage
Prompt for the power inserter model or voltage
[ "Prompt", "for", "the", "power", "inserter", "model", "or", "voltage" ]
def _ask_psu_voltage(question): """Prompt for the power inserter model or voltage""" psu = util.ask_multiple_choice(defs.psus, question, "Power inserter", lambda x: "{}".format(x['model']), none_option=True, none_str="No - another model") if (psu is None): voltage = util.typed_input("What is the voltage supplied to the " "LNB by your power inserter?") else: voltage = psu["voltage"] return voltage
[ "def", "_ask_psu_voltage", "(", "question", ")", ":", "psu", "=", "util", ".", "ask_multiple_choice", "(", "defs", ".", "psus", ",", "question", ",", "\"Power inserter\"", ",", "lambda", "x", ":", "\"{}\"", ".", "format", "(", "x", "[", "'model'", "]", ")", ",", "none_option", "=", "True", ",", "none_str", "=", "\"No - another model\"", ")", "if", "(", "psu", "is", "None", ")", ":", "voltage", "=", "util", ".", "typed_input", "(", "\"What is the voltage supplied to the \"", "\"LNB by your power inserter?\"", ")", "else", ":", "voltage", "=", "psu", "[", "\"voltage\"", "]", "return", "voltage" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L315-L329
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_cfg_lnb
(sat, setup)
return lnb
Configure LNB - either from preset or from custom specs Configure also the LNB power supply, if applicable. Args: sat : user's satellite info setup : user's setup info
Configure LNB - either from preset or from custom specs
[ "Configure", "LNB", "-", "either", "from", "preset", "or", "from", "custom", "specs" ]
def _cfg_lnb(sat, setup): """Configure LNB - either from preset or from custom specs Configure also the LNB power supply, if applicable. Args: sat : user's satellite info setup : user's setup info """ # For flat-panel and Sat-IP antennas, the LNB is the integrated one if (setup['antenna']['type'] in ['flat', 'sat-ip']): for lnb in defs.lnbs: if lnb['vendor'] == 'Selfsat': lnb["v1_pointed"] = False return lnb os.system('clear') util.print_header("LNB") lnb = _ask_lnb(sat) if (not _sat_freq_in_lnb_range(sat, lnb)): logging.warning("Your LNB's input frequency range does not cover the " "frequency of {} ({} MHz)".format( sat['name'], sat['dl_freq'])) if not util.ask_yes_or_no("Continue anyway?", default="n"): logging.error("Invalid LNB") sys.exit(1) if (sat['band'].lower() != lnb['band'].lower()): logging.error("The LNB you chose cannot operate " + "in %s band (band of satellite %s)" % (sat['band'], sat['alias'])) sys.exit(1) # When configuring a non-SDR receiver with a dual polarization LNB, we must # know whether the LNB was pointed before on an SDR setup in order to # define the polarization on channels.conf. When configuring an SDR # receiver, collect the power inserter voltage too for future use. if ((lnb['pol'].lower() == "dual" and setup['type'] != defs.sdr_setup_type) or setup['type'] == defs.sdr_setup_type): os.system('clear') util.print_header("Power Supply") if (lnb['pol'].lower() == "dual" and setup['type'] != defs.sdr_setup_type): prev_sdr_setup = util.ask_yes_or_no( "Are you reusing an LNB that is already pointed and that was used " "before by an SDR receiver?", default='n', help_msg="NOTE: this information is helpful to determine the " "polarization required for the LNB.") lnb["v1_pointed"] = prev_sdr_setup if (prev_sdr_setup): print() question = ( "In the pre-existing SDR setup, did you use one of the " "LNB power inserters below?") lnb["v1_psu_voltage"] = _ask_psu_voltage(question) elif (setup['type'] == defs.sdr_setup_type): question = ("Are you using one of the LNB power inserters below?") lnb["psu_voltage"] = _ask_psu_voltage(question) return lnb
[ "def", "_cfg_lnb", "(", "sat", ",", "setup", ")", ":", "# For flat-panel and Sat-IP antennas, the LNB is the integrated one", "if", "(", "setup", "[", "'antenna'", "]", "[", "'type'", "]", "in", "[", "'flat'", ",", "'sat-ip'", "]", ")", ":", "for", "lnb", "in", "defs", ".", "lnbs", ":", "if", "lnb", "[", "'vendor'", "]", "==", "'Selfsat'", ":", "lnb", "[", "\"v1_pointed\"", "]", "=", "False", "return", "lnb", "os", ".", "system", "(", "'clear'", ")", "util", ".", "print_header", "(", "\"LNB\"", ")", "lnb", "=", "_ask_lnb", "(", "sat", ")", "if", "(", "not", "_sat_freq_in_lnb_range", "(", "sat", ",", "lnb", ")", ")", ":", "logging", ".", "warning", "(", "\"Your LNB's input frequency range does not cover the \"", "\"frequency of {} ({} MHz)\"", ".", "format", "(", "sat", "[", "'name'", "]", ",", "sat", "[", "'dl_freq'", "]", ")", ")", "if", "not", "util", ".", "ask_yes_or_no", "(", "\"Continue anyway?\"", ",", "default", "=", "\"n\"", ")", ":", "logging", ".", "error", "(", "\"Invalid LNB\"", ")", "sys", ".", "exit", "(", "1", ")", "if", "(", "sat", "[", "'band'", "]", ".", "lower", "(", ")", "!=", "lnb", "[", "'band'", "]", ".", "lower", "(", ")", ")", ":", "logging", ".", "error", "(", "\"The LNB you chose cannot operate \"", "+", "\"in %s band (band of satellite %s)\"", "%", "(", "sat", "[", "'band'", "]", ",", "sat", "[", "'alias'", "]", ")", ")", "sys", ".", "exit", "(", "1", ")", "# When configuring a non-SDR receiver with a dual polarization LNB, we must", "# know whether the LNB was pointed before on an SDR setup in order to", "# define the polarization on channels.conf. When configuring an SDR", "# receiver, collect the power inserter voltage too for future use.", "if", "(", "(", "lnb", "[", "'pol'", "]", ".", "lower", "(", ")", "==", "\"dual\"", "and", "setup", "[", "'type'", "]", "!=", "defs", ".", "sdr_setup_type", ")", "or", "setup", "[", "'type'", "]", "==", "defs", ".", "sdr_setup_type", ")", ":", "os", ".", "system", "(", "'clear'", ")", "util", ".", "print_header", "(", "\"Power Supply\"", ")", "if", "(", "lnb", "[", "'pol'", "]", ".", "lower", "(", ")", "==", "\"dual\"", "and", "setup", "[", "'type'", "]", "!=", "defs", ".", "sdr_setup_type", ")", ":", "prev_sdr_setup", "=", "util", ".", "ask_yes_or_no", "(", "\"Are you reusing an LNB that is already pointed and that was used \"", "\"before by an SDR receiver?\"", ",", "default", "=", "'n'", ",", "help_msg", "=", "\"NOTE: this information is helpful to determine the \"", "\"polarization required for the LNB.\"", ")", "lnb", "[", "\"v1_pointed\"", "]", "=", "prev_sdr_setup", "if", "(", "prev_sdr_setup", ")", ":", "print", "(", ")", "question", "=", "(", "\"In the pre-existing SDR setup, did you use one of the \"", "\"LNB power inserters below?\"", ")", "lnb", "[", "\"v1_psu_voltage\"", "]", "=", "_ask_psu_voltage", "(", "question", ")", "elif", "(", "setup", "[", "'type'", "]", "==", "defs", ".", "sdr_setup_type", ")", ":", "question", "=", "(", "\"Are you using one of the LNB power inserters below?\"", ")", "lnb", "[", "\"psu_voltage\"", "]", "=", "_ask_psu_voltage", "(", "question", ")", "return", "lnb" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L332-L398
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_cfg_frequencies
(sat, lnb, setup)
return {'dl': sat['dl_freq'], 'lo': lo_freq, 'l_band': if_freq}
Print summary of frequencies Inform the downlink RF frequency, the LNB LO frequency and the L-band frequency to be configured in the receiver. Args: sat : user's satellite info lnb : user's LNB info
Print summary of frequencies
[ "Print", "summary", "of", "frequencies" ]
def _cfg_frequencies(sat, lnb, setup): """Print summary of frequencies Inform the downlink RF frequency, the LNB LO frequency and the L-band frequency to be configured in the receiver. Args: sat : user's satellite info lnb : user's LNB info """ getcontext().prec = 8 if (sat['band'].lower() == "ku"): if (lnb['universal']): assert(isinstance(lnb['lo_freq'], list)), \ "A Universal LNB must have a list with two LO frequencies" assert(len(lnb['lo_freq']) == 2), \ "A Universal LNB must have two LO frequencies" if (sat['dl_freq'] > defs.ku_band_thresh): lo_freq = lnb['lo_freq'][1] else: lo_freq = lnb['lo_freq'][0] else: lo_freq = lnb['lo_freq'] if_freq = float(Decimal(sat['dl_freq']) - Decimal(lo_freq)) elif (sat['band'].lower() == "c"): lo_freq = lnb['lo_freq'] if_freq = float(Decimal(lo_freq) - Decimal(sat['dl_freq'])) else: raise ValueError("Unknown satellite band") if (if_freq < setup['tun_range'][0] or if_freq > setup['tun_range'][1]): logging.error("Your LNB yields an L-band frequency that is out of " "the tuning range of the {} receiver.".format( _get_rx_marketing_name(setup))) sys.exit(1) return {'dl': sat['dl_freq'], 'lo': lo_freq, 'l_band': if_freq}
[ "def", "_cfg_frequencies", "(", "sat", ",", "lnb", ",", "setup", ")", ":", "getcontext", "(", ")", ".", "prec", "=", "8", "if", "(", "sat", "[", "'band'", "]", ".", "lower", "(", ")", "==", "\"ku\"", ")", ":", "if", "(", "lnb", "[", "'universal'", "]", ")", ":", "assert", "(", "isinstance", "(", "lnb", "[", "'lo_freq'", "]", ",", "list", ")", ")", ",", "\"A Universal LNB must have a list with two LO frequencies\"", "assert", "(", "len", "(", "lnb", "[", "'lo_freq'", "]", ")", "==", "2", ")", ",", "\"A Universal LNB must have two LO frequencies\"", "if", "(", "sat", "[", "'dl_freq'", "]", ">", "defs", ".", "ku_band_thresh", ")", ":", "lo_freq", "=", "lnb", "[", "'lo_freq'", "]", "[", "1", "]", "else", ":", "lo_freq", "=", "lnb", "[", "'lo_freq'", "]", "[", "0", "]", "else", ":", "lo_freq", "=", "lnb", "[", "'lo_freq'", "]", "if_freq", "=", "float", "(", "Decimal", "(", "sat", "[", "'dl_freq'", "]", ")", "-", "Decimal", "(", "lo_freq", ")", ")", "elif", "(", "sat", "[", "'band'", "]", ".", "lower", "(", ")", "==", "\"c\"", ")", ":", "lo_freq", "=", "lnb", "[", "'lo_freq'", "]", "if_freq", "=", "float", "(", "Decimal", "(", "lo_freq", ")", "-", "Decimal", "(", "sat", "[", "'dl_freq'", "]", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown satellite band\"", ")", "if", "(", "if_freq", "<", "setup", "[", "'tun_range'", "]", "[", "0", "]", "or", "if_freq", ">", "setup", "[", "'tun_range'", "]", "[", "1", "]", ")", ":", "logging", ".", "error", "(", "\"Your LNB yields an L-band frequency that is out of \"", "\"the tuning range of the {} receiver.\"", ".", "format", "(", "_get_rx_marketing_name", "(", "setup", ")", ")", ")", "sys", ".", "exit", "(", "1", ")", "return", "{", "'dl'", ":", "sat", "[", "'dl_freq'", "]", ",", "'lo'", ":", "lo_freq", ",", "'l_band'", ":", "if_freq", "}" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L401-L442
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_cfg_chan_conf
(info, chan_file)
Generate the channels.conf file
Generate the channels.conf file
[ "Generate", "the", "channels", ".", "conf", "file" ]
def _cfg_chan_conf(info, chan_file): """Generate the channels.conf file""" util.print_header("Channel Configuration") print( textwrap.fill("This step will generate the channel configuration " "file that is required when launching the USB " "receiver in Linux.") + "\n") if (os.path.isfile(chan_file)): print("Found previous %s file:" % (chan_file)) if (not util.ask_yes_or_no("Remove and regenerate file?")): print("Configuration aborted.") return else: os.remove(chan_file) with open(chan_file, 'w') as f: f.write('[blocksat-ch]\n') f.write('\tDELIVERY_SYSTEM = DVBS2\n') f.write('\tFREQUENCY = %u\n' % (int(info['sat']['dl_freq'] * 1000))) if (info['lnb']['pol'].lower() == "dual" and 'v1_pointed' in info['lnb'] and info['lnb']['v1_pointed']): # If a dual-polarization LNB is already pointed for Blocksat v1, # then we must use the polarization that the LNB was pointed to # originally, regardless of the satellite signal's polarization. In # v1, what mattered the most was the power supply voltage, which # determined the polarization of the dual polarization LNBs. If the # power supply provides voltage >= 18 (often the case), then the # LNB necessarily operates currently with horizontal polarization. # Thus, on channels.conf we must use the same polarization in order # for the DVB adapter to supply the 18VDC voltage. if (info['lnb']["v1_psu_voltage"] >= 16): # 16VDC threshold f.write('\tPOLARIZATION = HORIZONTAL\n') else: f.write('\tPOLARIZATION = VERTICAL\n') else: if (info['sat']['pol'] == 'V'): f.write('\tPOLARIZATION = VERTICAL\n') else: f.write('\tPOLARIZATION = HORIZONTAL\n') f.write('\tSYMBOL_RATE = {}\n'.format( defs.sym_rate[info['sat']['alias']])) f.write('\tINVERSION = AUTO\n') f.write('\tMODULATION = QPSK\n') pids = "+".join([str(x) for x in defs.pids]) f.write('\tVIDEO_PID = {}\n'.format(pids)) print("File \"%s\" saved." % (chan_file)) with open(chan_file, 'r') as f: logging.debug(f.read())
[ "def", "_cfg_chan_conf", "(", "info", ",", "chan_file", ")", ":", "util", ".", "print_header", "(", "\"Channel Configuration\"", ")", "print", "(", "textwrap", ".", "fill", "(", "\"This step will generate the channel configuration \"", "\"file that is required when launching the USB \"", "\"receiver in Linux.\"", ")", "+", "\"\\n\"", ")", "if", "(", "os", ".", "path", ".", "isfile", "(", "chan_file", ")", ")", ":", "print", "(", "\"Found previous %s file:\"", "%", "(", "chan_file", ")", ")", "if", "(", "not", "util", ".", "ask_yes_or_no", "(", "\"Remove and regenerate file?\"", ")", ")", ":", "print", "(", "\"Configuration aborted.\"", ")", "return", "else", ":", "os", ".", "remove", "(", "chan_file", ")", "with", "open", "(", "chan_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "'[blocksat-ch]\\n'", ")", "f", ".", "write", "(", "'\\tDELIVERY_SYSTEM = DVBS2\\n'", ")", "f", ".", "write", "(", "'\\tFREQUENCY = %u\\n'", "%", "(", "int", "(", "info", "[", "'sat'", "]", "[", "'dl_freq'", "]", "*", "1000", ")", ")", ")", "if", "(", "info", "[", "'lnb'", "]", "[", "'pol'", "]", ".", "lower", "(", ")", "==", "\"dual\"", "and", "'v1_pointed'", "in", "info", "[", "'lnb'", "]", "and", "info", "[", "'lnb'", "]", "[", "'v1_pointed'", "]", ")", ":", "# If a dual-polarization LNB is already pointed for Blocksat v1,", "# then we must use the polarization that the LNB was pointed to", "# originally, regardless of the satellite signal's polarization. In", "# v1, what mattered the most was the power supply voltage, which", "# determined the polarization of the dual polarization LNBs. If the", "# power supply provides voltage >= 18 (often the case), then the", "# LNB necessarily operates currently with horizontal polarization.", "# Thus, on channels.conf we must use the same polarization in order", "# for the DVB adapter to supply the 18VDC voltage.", "if", "(", "info", "[", "'lnb'", "]", "[", "\"v1_psu_voltage\"", "]", ">=", "16", ")", ":", "# 16VDC threshold", "f", ".", "write", "(", "'\\tPOLARIZATION = HORIZONTAL\\n'", ")", "else", ":", "f", ".", "write", "(", "'\\tPOLARIZATION = VERTICAL\\n'", ")", "else", ":", "if", "(", "info", "[", "'sat'", "]", "[", "'pol'", "]", "==", "'V'", ")", ":", "f", ".", "write", "(", "'\\tPOLARIZATION = VERTICAL\\n'", ")", "else", ":", "f", ".", "write", "(", "'\\tPOLARIZATION = HORIZONTAL\\n'", ")", "f", ".", "write", "(", "'\\tSYMBOL_RATE = {}\\n'", ".", "format", "(", "defs", ".", "sym_rate", "[", "info", "[", "'sat'", "]", "[", "'alias'", "]", "]", ")", ")", "f", ".", "write", "(", "'\\tINVERSION = AUTO\\n'", ")", "f", ".", "write", "(", "'\\tMODULATION = QPSK\\n'", ")", "pids", "=", "\"+\"", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "defs", ".", "pids", "]", ")", "f", ".", "write", "(", "'\\tVIDEO_PID = {}\\n'", ".", "format", "(", "pids", ")", ")", "print", "(", "\"File \\\"%s\\\" saved.\"", "%", "(", "chan_file", ")", ")", "with", "open", "(", "chan_file", ",", "'r'", ")", "as", "f", ":", "logging", ".", "debug", "(", "f", ".", "read", "(", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L445-L498
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_parse_chan_conf
(chan_file)
return chan_conf
Convert channel.conf file contents to dictionary
Convert channel.conf file contents to dictionary
[ "Convert", "channel", ".", "conf", "file", "contents", "to", "dictionary" ]
def _parse_chan_conf(chan_file): """Convert channel.conf file contents to dictionary""" chan_conf = {} with open(chan_file, 'r') as f: lines = f.read().splitlines() for line in lines[1:]: key, val = line.split('=') chan_conf[key.strip()] = val.strip() return chan_conf
[ "def", "_parse_chan_conf", "(", "chan_file", ")", ":", "chan_conf", "=", "{", "}", "with", "open", "(", "chan_file", ",", "'r'", ")", "as", "f", ":", "lines", "=", "f", ".", "read", "(", ")", ".", "splitlines", "(", ")", "for", "line", "in", "lines", "[", "1", ":", "]", ":", "key", ",", "val", "=", "line", ".", "split", "(", "'='", ")", "chan_conf", "[", "key", ".", "strip", "(", ")", "]", "=", "val", ".", "strip", "(", ")", "return", "chan_conf" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L501-L509
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_cfg_file_name
(cfg_name, directory)
return os.path.join(directory, json_file)
Get the name of the configuration JSON file
Get the name of the configuration JSON file
[ "Get", "the", "name", "of", "the", "configuration", "JSON", "file" ]
def _cfg_file_name(cfg_name, directory): """Get the name of the configuration JSON file""" # Remove paths basename = os.path.basename(cfg_name) # Remove extension noext = os.path.splitext(basename)[0] # Add JSON extension json_file = noext + ".json" return os.path.join(directory, json_file)
[ "def", "_cfg_file_name", "(", "cfg_name", ",", "directory", ")", ":", "# Remove paths", "basename", "=", "os", ".", "path", ".", "basename", "(", "cfg_name", ")", "# Remove extension", "noext", "=", "os", ".", "path", ".", "splitext", "(", "basename", ")", "[", "0", "]", "# Add JSON extension", "json_file", "=", "noext", "+", "\".json\"", "return", "os", ".", "path", ".", "join", "(", "directory", ",", "json_file", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L512-L520
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_read_cfg_file
(cfg_file)
Read configuration file
Read configuration file
[ "Read", "configuration", "file" ]
def _read_cfg_file(cfg_file): """Read configuration file""" if (os.path.isfile(cfg_file)): with open(cfg_file) as fd: info = json.load(fd) return info
[ "def", "_read_cfg_file", "(", "cfg_file", ")", ":", "if", "(", "os", ".", "path", ".", "isfile", "(", "cfg_file", ")", ")", ":", "with", "open", "(", "cfg_file", ")", "as", "fd", ":", "info", "=", "json", ".", "load", "(", "fd", ")", "return", "info" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L523-L529
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_write_cfg_file
(cfg_file, user_info)
Write configuration file
Write configuration file
[ "Write", "configuration", "file" ]
def _write_cfg_file(cfg_file, user_info): """Write configuration file""" with open(cfg_file, 'w') as fd: json.dump(user_info, fd)
[ "def", "_write_cfg_file", "(", "cfg_file", ",", "user_info", ")", ":", "with", "open", "(", "cfg_file", ",", "'w'", ")", "as", "fd", ":", "json", ".", "dump", "(", "user_info", ",", "fd", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L532-L535
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
_rst_cfg_file
(cfg_file)
return True
Reset a previous configuration file in case it exists
Reset a previous configuration file in case it exists
[ "Reset", "a", "previous", "configuration", "file", "in", "case", "it", "exists" ]
def _rst_cfg_file(cfg_file): """Reset a previous configuration file in case it exists""" info = _read_cfg_file(cfg_file) if (info is not None): print("Found previous configuration:") pprint(info, width=80, compact=False) if (util.ask_yes_or_no("Reset?")): os.remove(cfg_file) else: print("Configuration aborted.") return False return True
[ "def", "_rst_cfg_file", "(", "cfg_file", ")", ":", "info", "=", "_read_cfg_file", "(", "cfg_file", ")", "if", "(", "info", "is", "not", "None", ")", ":", "print", "(", "\"Found previous configuration:\"", ")", "pprint", "(", "info", ",", "width", "=", "80", ",", "compact", "=", "False", ")", "if", "(", "util", ".", "ask_yes_or_no", "(", "\"Reset?\"", ")", ")", ":", "os", ".", "remove", "(", "cfg_file", ")", "else", ":", "print", "(", "\"Configuration aborted.\"", ")", "return", "False", "return", "True" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L538-L550
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
read_cfg_file
(cfg_name, directory)
return info
Read configuration file If not available, run configuration helper.
Read configuration file
[ "Read", "configuration", "file" ]
def read_cfg_file(cfg_name, directory): """Read configuration file If not available, run configuration helper. """ cfg_file = _cfg_file_name(cfg_name, directory) info = _read_cfg_file(cfg_file) while (info is None): print("Missing {} configuration file".format(cfg_file)) if (util.ask_yes_or_no("Run configuration helper now?")): configure(Namespace(cfg_dir=directory, cfg=cfg_name)) else: print("Abort") return info = _read_cfg_file(cfg_file) return info
[ "def", "read_cfg_file", "(", "cfg_name", ",", "directory", ")", ":", "cfg_file", "=", "_cfg_file_name", "(", "cfg_name", ",", "directory", ")", "info", "=", "_read_cfg_file", "(", "cfg_file", ")", "while", "(", "info", "is", "None", ")", ":", "print", "(", "\"Missing {} configuration file\"", ".", "format", "(", "cfg_file", ")", ")", "if", "(", "util", ".", "ask_yes_or_no", "(", "\"Run configuration helper now?\"", ")", ")", ":", "configure", "(", "Namespace", "(", "cfg_dir", "=", "directory", ",", "cfg", "=", "cfg_name", ")", ")", "else", ":", "print", "(", "\"Abort\"", ")", "return", "info", "=", "_read_cfg_file", "(", "cfg_file", ")", "return", "info" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L553-L572
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
write_cfg_file
(cfg_name, directory, user_info)
Write configuration file
Write configuration file
[ "Write", "configuration", "file" ]
def write_cfg_file(cfg_name, directory, user_info): """Write configuration file""" cfg_file = _cfg_file_name(cfg_name, directory) _write_cfg_file(cfg_file, user_info)
[ "def", "write_cfg_file", "(", "cfg_name", ",", "directory", ",", "user_info", ")", ":", "cfg_file", "=", "_cfg_file_name", "(", "cfg_name", ",", "directory", ")", "_write_cfg_file", "(", "cfg_file", ",", "user_info", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L575-L578
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
get_rx_model
(user_info)
return (user_info['setup']['vendor'] + " " + user_info['setup']['model']).strip()
Return string with the receiver vendor and model Note: this function differs from _get_rx_marketing_name(). The latter includes the satellite kit name. In contrast, this function returns the raw vendeor-model string.
Return string with the receiver vendor and model
[ "Return", "string", "with", "the", "receiver", "vendor", "and", "model" ]
def get_rx_model(user_info): """Return string with the receiver vendor and model Note: this function differs from _get_rx_marketing_name(). The latter includes the satellite kit name. In contrast, this function returns the raw vendeor-model string. """ return (user_info['setup']['vendor'] + " " + user_info['setup']['model']).strip()
[ "def", "get_rx_model", "(", "user_info", ")", ":", "return", "(", "user_info", "[", "'setup'", "]", "[", "'vendor'", "]", "+", "\" \"", "+", "user_info", "[", "'setup'", "]", "[", "'model'", "]", ")", ".", "strip", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L581-L590
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
get_antenna_model
(user_info)
return antenna
Return string with the antenna model
Return string with the antenna model
[ "Return", "string", "with", "the", "antenna", "model" ]
def get_antenna_model(user_info): """Return string with the antenna model""" antenna_info = user_info['setup']['antenna'] antenna_type = antenna_info.get('type') if (antenna_type == 'dish' or antenna_info['label'] == 'custom'): dish_size = antenna_info['size'] if (dish_size >= 100): antenna = "{:g}m dish".format(dish_size / 100) else: antenna = "{:g}cm dish".format(dish_size) else: return antenna_info['label'] return antenna
[ "def", "get_antenna_model", "(", "user_info", ")", ":", "antenna_info", "=", "user_info", "[", "'setup'", "]", "[", "'antenna'", "]", "antenna_type", "=", "antenna_info", ".", "get", "(", "'type'", ")", "if", "(", "antenna_type", "==", "'dish'", "or", "antenna_info", "[", "'label'", "]", "==", "'custom'", ")", ":", "dish_size", "=", "antenna_info", "[", "'size'", "]", "if", "(", "dish_size", ">=", "100", ")", ":", "antenna", "=", "\"{:g}m dish\"", ".", "format", "(", "dish_size", "/", "100", ")", "else", ":", "antenna", "=", "\"{:g}cm dish\"", ".", "format", "(", "dish_size", ")", "else", ":", "return", "antenna_info", "[", "'label'", "]", "return", "antenna" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L593-L607
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
get_lnb_model
(user_info)
return lnb
Return string with the LNB model
Return string with the LNB model
[ "Return", "string", "with", "the", "LNB", "model" ]
def get_lnb_model(user_info): """Return string with the LNB model""" lnb_info = user_info['lnb'] if (lnb_info['vendor'] == "" and lnb_info['model'] == ""): if (lnb_info['universal']): lnb = "Custom Universal LNB" else: lnb = "Custom {}-band LNB".format(lnb_info['band']) else: lnb = "{} {}".format(lnb_info['vendor'], lnb_info['model']) return lnb
[ "def", "get_lnb_model", "(", "user_info", ")", ":", "lnb_info", "=", "user_info", "[", "'lnb'", "]", "if", "(", "lnb_info", "[", "'vendor'", "]", "==", "\"\"", "and", "lnb_info", "[", "'model'", "]", "==", "\"\"", ")", ":", "if", "(", "lnb_info", "[", "'universal'", "]", ")", ":", "lnb", "=", "\"Custom Universal LNB\"", "else", ":", "lnb", "=", "\"Custom {}-band LNB\"", ".", "format", "(", "lnb_info", "[", "'band'", "]", ")", "else", ":", "lnb", "=", "\"{} {}\"", ".", "format", "(", "lnb_info", "[", "'vendor'", "]", ",", "lnb_info", "[", "'model'", "]", ")", "return", "lnb" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L610-L620
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
get_net_if
(user_info)
return interface
Get the network interface used by the given setup
Get the network interface used by the given setup
[ "Get", "the", "network", "interface", "used", "by", "the", "given", "setup" ]
def get_net_if(user_info): """Get the network interface used by the given setup""" if (user_info is None): raise ValueError("Failed to read local configuration") setup_type = user_info['setup']['type'] if (setup_type in [defs.sdr_setup_type, defs.sat_ip_setup_type]): interface = "lo" elif (setup_type == defs.linux_usb_setup_type): if ('adapter' not in user_info['setup']): interface = "dvb0_0" logger.warning("Could not find the dvbnet interface name. " "Is the {} receiver running?".format( get_rx_model(user_info))) logger.warning("Assuming interface name {}.".format(interface)) else: adapter = user_info['setup']['adapter'] interface = "dvb{}_0".format(adapter) elif (setup_type == defs.standalone_setup_type): interface = user_info['setup']['netdev'] else: raise ValueError("Unknown setup type") return interface
[ "def", "get_net_if", "(", "user_info", ")", ":", "if", "(", "user_info", "is", "None", ")", ":", "raise", "ValueError", "(", "\"Failed to read local configuration\"", ")", "setup_type", "=", "user_info", "[", "'setup'", "]", "[", "'type'", "]", "if", "(", "setup_type", "in", "[", "defs", ".", "sdr_setup_type", ",", "defs", ".", "sat_ip_setup_type", "]", ")", ":", "interface", "=", "\"lo\"", "elif", "(", "setup_type", "==", "defs", ".", "linux_usb_setup_type", ")", ":", "if", "(", "'adapter'", "not", "in", "user_info", "[", "'setup'", "]", ")", ":", "interface", "=", "\"dvb0_0\"", "logger", ".", "warning", "(", "\"Could not find the dvbnet interface name. \"", "\"Is the {} receiver running?\"", ".", "format", "(", "get_rx_model", "(", "user_info", ")", ")", ")", "logger", ".", "warning", "(", "\"Assuming interface name {}.\"", ".", "format", "(", "interface", ")", ")", "else", ":", "adapter", "=", "user_info", "[", "'setup'", "]", "[", "'adapter'", "]", "interface", "=", "\"dvb{}_0\"", ".", "format", "(", "adapter", ")", "elif", "(", "setup_type", "==", "defs", ".", "standalone_setup_type", ")", ":", "interface", "=", "user_info", "[", "'setup'", "]", "[", "'netdev'", "]", "else", ":", "raise", "ValueError", "(", "\"Unknown setup type\"", ")", "return", "interface" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L623-L646
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
subparser
(subparsers)
return p
Argument parser of config command
Argument parser of config command
[ "Argument", "parser", "of", "config", "command" ]
def subparser(subparsers): """Argument parser of config command""" p = subparsers.add_parser('config', aliases=['cfg'], description="Configure Blocksat Rx setup", help='Define receiver and Bitcoin Satellite \ configurations', formatter_class=ArgumentDefaultsHelpFormatter) p.set_defaults(func=configure) subsubparsers = p.add_subparsers(title='subcommands', help='Target sub-command') p2 = subsubparsers.add_parser( 'show', description="Display the local configuration", help='Display the local configuration', formatter_class=ArgumentDefaultsHelpFormatter) p2.set_defaults(func=show) p3 = subsubparsers.add_parser( 'channel', description="Configure the channels file used by the USB receiver", help='Configure the channels file used by the USB receiver', formatter_class=ArgumentDefaultsHelpFormatter) p3.set_defaults(func=channel) return p
[ "def", "subparser", "(", "subparsers", ")", ":", "p", "=", "subparsers", ".", "add_parser", "(", "'config'", ",", "aliases", "=", "[", "'cfg'", "]", ",", "description", "=", "\"Configure Blocksat Rx setup\"", ",", "help", "=", "'Define receiver and Bitcoin Satellite \\\n configurations'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "p", ".", "set_defaults", "(", "func", "=", "configure", ")", "subsubparsers", "=", "p", ".", "add_subparsers", "(", "title", "=", "'subcommands'", ",", "help", "=", "'Target sub-command'", ")", "p2", "=", "subsubparsers", ".", "add_parser", "(", "'show'", ",", "description", "=", "\"Display the local configuration\"", ",", "help", "=", "'Display the local configuration'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "p2", ".", "set_defaults", "(", "func", "=", "show", ")", "p3", "=", "subsubparsers", ".", "add_parser", "(", "'channel'", ",", "description", "=", "\"Configure the channels file used by the USB receiver\"", ",", "help", "=", "'Configure the channels file used by the USB receiver'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "p3", ".", "set_defaults", "(", "func", "=", "channel", ")", "return", "p" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L649-L674
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
configure
(args)
Configure Blocksat Receiver setup
Configure Blocksat Receiver setup
[ "Configure", "Blocksat", "Receiver", "setup" ]
def configure(args): """Configure Blocksat Receiver setup """ cfg_file = _cfg_file_name(args.cfg, args.cfg_dir) rst_ok = _rst_cfg_file(cfg_file) if (not rst_ok): return try: user_sat = _cfg_satellite() user_setup = _cfg_rx_setup() user_lnb = _cfg_lnb(user_sat, user_setup) user_freqs = _cfg_frequencies(user_sat, user_lnb, user_setup) except KeyboardInterrupt: print("\nAbort") sys.exit(1) user_info = { 'sat': user_sat, 'setup': user_setup, 'lnb': user_lnb, 'freqs': user_freqs } logging.debug(pformat(user_info)) if not os.path.exists(args.cfg_dir): os.makedirs(args.cfg_dir) # Channel configuration file if (user_setup['type'] == defs.linux_usb_setup_type): chan_file = os.path.join(args.cfg_dir, args.cfg + "-channel.conf") _cfg_chan_conf(user_info, chan_file) user_info['setup']['channel'] = chan_file # Create the JSON configuration file _write_cfg_file(cfg_file, user_info) os.system('clear') util.print_header("JSON configuration file") print("Saved configurations on %s" % (cfg_file)) util.print_header("Next Steps") print(textwrap.fill("Please check setup instructions by running:")) print(""" blocksat-cli instructions """)
[ "def", "configure", "(", "args", ")", ":", "cfg_file", "=", "_cfg_file_name", "(", "args", ".", "cfg", ",", "args", ".", "cfg_dir", ")", "rst_ok", "=", "_rst_cfg_file", "(", "cfg_file", ")", "if", "(", "not", "rst_ok", ")", ":", "return", "try", ":", "user_sat", "=", "_cfg_satellite", "(", ")", "user_setup", "=", "_cfg_rx_setup", "(", ")", "user_lnb", "=", "_cfg_lnb", "(", "user_sat", ",", "user_setup", ")", "user_freqs", "=", "_cfg_frequencies", "(", "user_sat", ",", "user_lnb", ",", "user_setup", ")", "except", "KeyboardInterrupt", ":", "print", "(", "\"\\nAbort\"", ")", "sys", ".", "exit", "(", "1", ")", "user_info", "=", "{", "'sat'", ":", "user_sat", ",", "'setup'", ":", "user_setup", ",", "'lnb'", ":", "user_lnb", ",", "'freqs'", ":", "user_freqs", "}", "logging", ".", "debug", "(", "pformat", "(", "user_info", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "args", ".", "cfg_dir", ")", ":", "os", ".", "makedirs", "(", "args", ".", "cfg_dir", ")", "# Channel configuration file", "if", "(", "user_setup", "[", "'type'", "]", "==", "defs", ".", "linux_usb_setup_type", ")", ":", "chan_file", "=", "os", ".", "path", ".", "join", "(", "args", ".", "cfg_dir", ",", "args", ".", "cfg", "+", "\"-channel.conf\"", ")", "_cfg_chan_conf", "(", "user_info", ",", "chan_file", ")", "user_info", "[", "'setup'", "]", "[", "'channel'", "]", "=", "chan_file", "# Create the JSON configuration file", "_write_cfg_file", "(", "cfg_file", ",", "user_info", ")", "os", ".", "system", "(", "'clear'", ")", "util", ".", "print_header", "(", "\"JSON configuration file\"", ")", "print", "(", "\"Saved configurations on %s\"", "%", "(", "cfg_file", ")", ")", "util", ".", "print_header", "(", "\"Next Steps\"", ")", "print", "(", "textwrap", ".", "fill", "(", "\"Please check setup instructions by running:\"", ")", ")", "print", "(", "\"\"\"\n blocksat-cli instructions\n \"\"\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L677-L725
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
show
(args)
Print the local configuration
Print the local configuration
[ "Print", "the", "local", "configuration" ]
def show(args): """Print the local configuration""" info = read_cfg_file(args.cfg, args.cfg_dir) if (info is None): return print("| {:30s} | {:25s} |".format("Receiver", _get_rx_marketing_name(info['setup']))) print("| {:30s} | {:25s} |".format("LNB", get_lnb_model(info))) print("| {:30s} | {:25s} |".format("Antenna", get_antenna_model(info))) pr_cfgs = { 'freqs': { 'dl': ("Downlink frequency", "MHz", None), 'lo': ("LNB LO frequency", "MHz", None), 'l_band': ("Receiver L-band frequency", "MHz", None) }, 'sat': { 'name': ("Satellite name", "", None), 'band': ("Signal band", "", None), 'pol': ("Signal polarization", "", lambda x: "Horizontal" if x == "H" else "vertical"), } } for category in pr_cfgs: for key, pr_cfg in pr_cfgs[category].items(): label = pr_cfg[0] unit = pr_cfg[1] val = info[category][key] # Transform the value if a callback is defined if (pr_cfg[2] is not None): val = pr_cfg[2](val) print("| {:30s} | {:25s} |".format(label, str(val) + " " + unit))
[ "def", "show", "(", "args", ")", ":", "info", "=", "read_cfg_file", "(", "args", ".", "cfg", ",", "args", ".", "cfg_dir", ")", "if", "(", "info", "is", "None", ")", ":", "return", "print", "(", "\"| {:30s} | {:25s} |\"", ".", "format", "(", "\"Receiver\"", ",", "_get_rx_marketing_name", "(", "info", "[", "'setup'", "]", ")", ")", ")", "print", "(", "\"| {:30s} | {:25s} |\"", ".", "format", "(", "\"LNB\"", ",", "get_lnb_model", "(", "info", ")", ")", ")", "print", "(", "\"| {:30s} | {:25s} |\"", ".", "format", "(", "\"Antenna\"", ",", "get_antenna_model", "(", "info", ")", ")", ")", "pr_cfgs", "=", "{", "'freqs'", ":", "{", "'dl'", ":", "(", "\"Downlink frequency\"", ",", "\"MHz\"", ",", "None", ")", ",", "'lo'", ":", "(", "\"LNB LO frequency\"", ",", "\"MHz\"", ",", "None", ")", ",", "'l_band'", ":", "(", "\"Receiver L-band frequency\"", ",", "\"MHz\"", ",", "None", ")", "}", ",", "'sat'", ":", "{", "'name'", ":", "(", "\"Satellite name\"", ",", "\"\"", ",", "None", ")", ",", "'band'", ":", "(", "\"Signal band\"", ",", "\"\"", ",", "None", ")", ",", "'pol'", ":", "(", "\"Signal polarization\"", ",", "\"\"", ",", "lambda", "x", ":", "\"Horizontal\"", "if", "x", "==", "\"H\"", "else", "\"vertical\"", ")", ",", "}", "}", "for", "category", "in", "pr_cfgs", ":", "for", "key", ",", "pr_cfg", "in", "pr_cfgs", "[", "category", "]", ".", "items", "(", ")", ":", "label", "=", "pr_cfg", "[", "0", "]", "unit", "=", "pr_cfg", "[", "1", "]", "val", "=", "info", "[", "category", "]", "[", "key", "]", "# Transform the value if a callback is defined", "if", "(", "pr_cfg", "[", "2", "]", "is", "not", "None", ")", ":", "val", "=", "pr_cfg", "[", "2", "]", "(", "val", ")", "print", "(", "\"| {:30s} | {:25s} |\"", ".", "format", "(", "label", ",", "str", "(", "val", ")", "+", "\" \"", "+", "unit", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L728-L758
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/config.py
python
channel
(args)
Configure the channels.conf file directly
Configure the channels.conf file directly
[ "Configure", "the", "channels", ".", "conf", "file", "directly" ]
def channel(args): """Configure the channels.conf file directly""" user_info = read_cfg_file(args.cfg, args.cfg_dir) if (user_info is None): return # Channel configuration file if (user_info['setup']['type'] != defs.linux_usb_setup_type): raise TypeError("Invalid command for {} receivers".format( user_info['setup']['type'])) chan_file = os.path.join(args.cfg_dir, args.cfg + "-channel.conf") _cfg_chan_conf(user_info, chan_file) # Overwrite the channels.conf path in case it is changing from a previous # version of the CLI when the conf file name was not bound to the cfg name user_info['setup']['channel'] = chan_file write_cfg_file(args.cfg, args.cfg_dir, user_info)
[ "def", "channel", "(", "args", ")", ":", "user_info", "=", "read_cfg_file", "(", "args", ".", "cfg", ",", "args", ".", "cfg_dir", ")", "if", "(", "user_info", "is", "None", ")", ":", "return", "# Channel configuration file", "if", "(", "user_info", "[", "'setup'", "]", "[", "'type'", "]", "!=", "defs", ".", "linux_usb_setup_type", ")", ":", "raise", "TypeError", "(", "\"Invalid command for {} receivers\"", ".", "format", "(", "user_info", "[", "'setup'", "]", "[", "'type'", "]", ")", ")", "chan_file", "=", "os", ".", "path", ".", "join", "(", "args", ".", "cfg_dir", ",", "args", ".", "cfg", "+", "\"-channel.conf\"", ")", "_cfg_chan_conf", "(", "user_info", ",", "chan_file", ")", "# Overwrite the channels.conf path in case it is changing from a previous", "# version of the CLI when the conf file name was not bound to the cfg name", "user_info", "[", "'setup'", "]", "[", "'channel'", "]", "=", "chan_file", "write_cfg_file", "(", "args", ".", "cfg", ",", "args", ".", "cfg_dir", ",", "user_info", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/config.py#L761-L778
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/instructions.py
python
_print_s400_instructions
(info)
Print instructions for configuration of the Novra S400
Print instructions for configuration of the Novra S400
[ "Print", "instructions", "for", "configuration", "of", "the", "Novra", "S400" ]
def _print_s400_instructions(info): """Print instructions for configuration of the Novra S400 """ util.print_header("Novra S400") _print(""" The Novra S400 is a standalone receiver, which will receive data from satellite and output IP packets to the host over the network. Hence, you will need to configure both the S400 and the host. """) util.print_sub_header("Connections") _print("The Novra S400 can be connected as follows:") print(("LNB ----> S400 (RF1 Interface) -- " "S400 (LAN 1 Interface) ----> Host / Network\n")) _item("Connect the LNB directly to interface RF1 of the S400 using a " "coaxial cable (an RG6 cable is recommended).") _item("Connect the S400's LAN1 interface to your computer or network.") util.prompt_for_enter() util.print_sub_header("Network Connection") _print("Next, make sure the S400 receiver is reachable by the host.") _print("First, configure your host's network interface to the same subnet " "as the S400. By default, the S400 is configured with IP address " "192.168.1.2 on LAN1 and 192.168.2.2 on LAN2. Hence, if you " "connect to LAN1, make sure your host's network interface has IP " "address 192.168.1.x, where \"x\" could be any number higher than " "2. For example, you could configure your host's network interface " "with IP address 192.168.1.3.") _print("After that, open the browser and access 192.168.1.2 (or " "192.168.2.2 if connected to LAN 2). The web management console " "should open up successfully.") print() util.prompt_for_enter() util.print_sub_header("Software Requirements") _print("Next, install all software pre-requisites on your host. Run:") print(" blocksat-cli deps install\n") _print(""" NOTE: this command supports the apt, dnf, and yum package managers.""") util.prompt_for_enter() util.print_sub_header("Receiver and Host Configuration") print("Now, configure the S400 receiver and the host by running:") print("\n blocksat-cli standalone cfg\n") _print("""If you would like to review the changes that will be made to the host before applying them, first run the command in dry-run mode:""") print(" blocksat-cli standalone cfg --dry-run\n\n") util.prompt_for_enter() util.print_sub_header("Monitoring") print("Finally, you can monitor your receiver by running:") print("\n blocksat-cli standalone monitor\n\n") util.prompt_for_enter()
[ "def", "_print_s400_instructions", "(", "info", ")", ":", "util", ".", "print_header", "(", "\"Novra S400\"", ")", "_print", "(", "\"\"\"\n The Novra S400 is a standalone receiver, which will receive data from\n satellite and output IP packets to the host over the network. Hence, you\n will need to configure both the S400 and the host.\n \"\"\"", ")", "util", ".", "print_sub_header", "(", "\"Connections\"", ")", "_print", "(", "\"The Novra S400 can be connected as follows:\"", ")", "print", "(", "(", "\"LNB ----> S400 (RF1 Interface) -- \"", "\"S400 (LAN 1 Interface) ----> Host / Network\\n\"", ")", ")", "_item", "(", "\"Connect the LNB directly to interface RF1 of the S400 using a \"", "\"coaxial cable (an RG6 cable is recommended).\"", ")", "_item", "(", "\"Connect the S400's LAN1 interface to your computer or network.\"", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Network Connection\"", ")", "_print", "(", "\"Next, make sure the S400 receiver is reachable by the host.\"", ")", "_print", "(", "\"First, configure your host's network interface to the same subnet \"", "\"as the S400. By default, the S400 is configured with IP address \"", "\"192.168.1.2 on LAN1 and 192.168.2.2 on LAN2. Hence, if you \"", "\"connect to LAN1, make sure your host's network interface has IP \"", "\"address 192.168.1.x, where \\\"x\\\" could be any number higher than \"", "\"2. For example, you could configure your host's network interface \"", "\"with IP address 192.168.1.3.\"", ")", "_print", "(", "\"After that, open the browser and access 192.168.1.2 (or \"", "\"192.168.2.2 if connected to LAN 2). The web management console \"", "\"should open up successfully.\"", ")", "print", "(", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Software Requirements\"", ")", "_print", "(", "\"Next, install all software pre-requisites on your host. Run:\"", ")", "print", "(", "\" blocksat-cli deps install\\n\"", ")", "_print", "(", "\"\"\"\n NOTE: this command supports the apt, dnf, and yum package managers.\"\"\"", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Receiver and Host Configuration\"", ")", "print", "(", "\"Now, configure the S400 receiver and the host by running:\"", ")", "print", "(", "\"\\n blocksat-cli standalone cfg\\n\"", ")", "_print", "(", "\"\"\"If you would like to review the changes that will be made to the\n host before applying them, first run the command in dry-run mode:\"\"\"", ")", "print", "(", "\" blocksat-cli standalone cfg --dry-run\\n\\n\"", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Monitoring\"", ")", "print", "(", "\"Finally, you can monitor your receiver by running:\"", ")", "print", "(", "\"\\n blocksat-cli standalone monitor\\n\\n\"", ")", "util", ".", "prompt_for_enter", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/instructions.py#L20-L94
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/instructions.py
python
_print_usb_rx_instructions
(info)
Print instructions for runnning with a Linux USB receiver
Print instructions for runnning with a Linux USB receiver
[ "Print", "instructions", "for", "runnning", "with", "a", "Linux", "USB", "receiver" ]
def _print_usb_rx_instructions(info): """Print instructions for runnning with a Linux USB receiver """ name = (info['setup']['vendor'] + " " + info['setup']['model']).strip() util.print_header(name) _print(""" The {0} is a USB receiver, which will receive data from satellite and will output data to the host over USB. The host, in turn, is responsible for configuring the receiver using specific DVB-S2 tools. Hence, next, you need to prepare the host for driving the {0}. """.format(name)) util.print_sub_header("Hardware Connections") print("The {} should be connected as follows:\n".format(name)) print(("LNB ----> {0} (LNB Interface) -- " "{0} (USB Interface) ----> Host\n".format(name))) _item("Connect the LNB directly to \"LNB IN\" of the {} using a coaxial" " cable (an RG6 cable is recommended).".format(name)) _item("Connect the {}'s USB interface to your computer.".format(name)) util.prompt_for_enter() util.print_sub_header("Drivers") _print(""" Before anything else, note that specific device drivers are required in order to use the {0}. Please, do note that driver installation can cause corruptions and, therefore, it is safer and **strongly recommended** to use a virtual machine for running the {0}. If you do so, please note that all commands recommended in the remainder of this page are supposed to be executed in the virtual machine. """.format(name)) _print("Next, install the drivers for the {0} by running:".format(name)) print(""" blocksat-cli deps tbs-drivers """) print("Once the script completes the installation, reboot the virtual " "machine.") util.prompt_for_enter() util.print_sub_header("Host Requirements") print( "Now, install all pre-requisites (in the virtual machine) by running:") print(""" blocksat-cli deps install """) _print(""" NOTE: this command supports the apt, dnf, and yum package managers. For other package managers, refer to the instructions at:""") print(defs.user_guide_url + "doc/tbs.html") util.prompt_for_enter() util.print_sub_header("Configure the Host") _print( """Next, you need to create and configure the network interfaces that will output the IP traffic received via the TBS5927. You can apply all configurations by running the following command:""") print("\n blocksat-cli usb config\n") _print("""If you would like to review the changes that will be made before applying them, first run the command in dry-run mode: """) print("\n blocksat-cli usb config --dry-run\n") _print(""" Note this command will define arbitrary IP addresses to the interfaces. If you need (or want) to define specific IP addresses instead, for example to avoid IP address conflicts, use command-line argument `--ip`. """) _print( """Furthermore, note that this configuration is not persistent across reboots. After a reboot, you need to run `blocksat-cli usb config` again.""") util.prompt_for_enter() util.print_sub_header("Launch") print("Finally, start the receiver by running:") print("\n blocksat-cli usb launch\n") util.prompt_for_enter()
[ "def", "_print_usb_rx_instructions", "(", "info", ")", ":", "name", "=", "(", "info", "[", "'setup'", "]", "[", "'vendor'", "]", "+", "\" \"", "+", "info", "[", "'setup'", "]", "[", "'model'", "]", ")", ".", "strip", "(", ")", "util", ".", "print_header", "(", "name", ")", "_print", "(", "\"\"\"\n The {0} is a USB receiver, which will receive data from satellite and will\n output data to the host over USB. The host, in turn, is responsible for\n configuring the receiver using specific DVB-S2 tools. Hence, next, you need\n to prepare the host for driving the {0}.\n \"\"\"", ".", "format", "(", "name", ")", ")", "util", ".", "print_sub_header", "(", "\"Hardware Connections\"", ")", "print", "(", "\"The {} should be connected as follows:\\n\"", ".", "format", "(", "name", ")", ")", "print", "(", "(", "\"LNB ----> {0} (LNB Interface) -- \"", "\"{0} (USB Interface) ----> Host\\n\"", ".", "format", "(", "name", ")", ")", ")", "_item", "(", "\"Connect the LNB directly to \\\"LNB IN\\\" of the {} using a coaxial\"", "\" cable (an RG6 cable is recommended).\"", ".", "format", "(", "name", ")", ")", "_item", "(", "\"Connect the {}'s USB interface to your computer.\"", ".", "format", "(", "name", ")", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Drivers\"", ")", "_print", "(", "\"\"\"\n Before anything else, note that specific device drivers are required in\n order to use the {0}. Please, do note that driver installation can cause\n corruptions and, therefore, it is safer and **strongly recommended** to use\n a virtual machine for running the {0}. If you do so, please note that all\n commands recommended in the remainder of this page are supposed to be\n executed in the virtual machine.\n \"\"\"", ".", "format", "(", "name", ")", ")", "_print", "(", "\"Next, install the drivers for the {0} by running:\"", ".", "format", "(", "name", ")", ")", "print", "(", "\"\"\"\n blocksat-cli deps tbs-drivers\n \"\"\"", ")", "print", "(", "\"Once the script completes the installation, reboot the virtual \"", "\"machine.\"", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Host Requirements\"", ")", "print", "(", "\"Now, install all pre-requisites (in the virtual machine) by running:\"", ")", "print", "(", "\"\"\"\n blocksat-cli deps install\n \"\"\"", ")", "_print", "(", "\"\"\"\n NOTE: this command supports the apt, dnf, and yum package managers. For\n other package managers, refer to the instructions at:\"\"\"", ")", "print", "(", "defs", ".", "user_guide_url", "+", "\"doc/tbs.html\"", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Configure the Host\"", ")", "_print", "(", "\"\"\"Next, you need to create and configure the network interfaces that\n will output the IP traffic received via the TBS5927. You can apply all\n configurations by running the following command:\"\"\"", ")", "print", "(", "\"\\n blocksat-cli usb config\\n\"", ")", "_print", "(", "\"\"\"If you would like to review the changes that will be made before\n applying them, first run the command in dry-run mode:\n \"\"\"", ")", "print", "(", "\"\\n blocksat-cli usb config --dry-run\\n\"", ")", "_print", "(", "\"\"\"\n Note this command will define arbitrary IP addresses to the interfaces. If\n you need (or want) to define specific IP addresses instead, for example to\n avoid IP address conflicts, use command-line argument `--ip`.\n \"\"\"", ")", "_print", "(", "\"\"\"Furthermore, note that this configuration is not persistent across\n reboots. After a reboot, you need to run `blocksat-cli usb config`\n again.\"\"\"", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Launch\"", ")", "print", "(", "\"Finally, start the receiver by running:\"", ")", "print", "(", "\"\\n blocksat-cli usb launch\\n\"", ")", "util", ".", "prompt_for_enter", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/instructions.py#L97-L197
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/instructions.py
python
_print_sdr_instructions
(info)
Print instruction for configuration of an SDR setup
Print instruction for configuration of an SDR setup
[ "Print", "instruction", "for", "configuration", "of", "an", "SDR", "setup" ]
def _print_sdr_instructions(info): """Print instruction for configuration of an SDR setup """ util.print_header("SDR Setup") util.print_sub_header("Connections") print("The SDR setup is connected as follows:\n") print("LNB ----> Power Supply ----> RTL-SDR ----> Host\n") _item("Connect the RTL-SDR USB dongle to your host PC.") _item("Connect the **non-powered** port of the power supply (labeled as " "\"Signal to IRD\") to the RTL-SDR using an SMA cable and an " "SMA-to-F adapter.") _item("Connect the **powered** port (labeled \"Signal to SWM\") of the " "power supply to the LNB using a coaxial cable (an RG6 cable is " "recommended).") print() _print("IMPORTANT: Do NOT connect the powered port of the power supply " "to the SDR interface. Permanent damage may occur to your SDR " "and/or your computer.") util.prompt_for_enter() util.print_sub_header("Software Requirements") print("The SDR-based setup relies on the applications listed below:\n") _item("leandvb: a software-based DVB-S2 receiver application.") _item("rtl_sdr: reads samples taken by the RTL-SDR and feeds them into " "leandvb.") _item("TSDuck: unpacks the output of leandvb and produces " "IP packets to be fed to Bitcoin Satellite.") _item("Gqrx: useful for spectrum visualization during antenna pointing.") print("\nTo install them, run:") print(""" blocksat-cli deps install """) _print(""" NOTE: This command supports the two most recent Ubuntu LTS, Fedora, and CentOS releases. In case you are using another Linux distribution or version, please refer to the manual compilation and installation instructions at:""") print(defs.user_guide_url + "doc/sdr.html") util.prompt_for_enter() util.print_sub_header("Configuration") _print( "Next, you can generate the configurations that are needed for gqrx " "by running:") print(" blocksat-cli gqrx-conf") util.prompt_for_enter() util.print_sub_header("Running") _print( "You should now be ready to launch the SDR receiver. You can run it " "by executing:") print(" blocksat-cli sdr\n") print("Or, in GUI mode:\n") print(" blocksat-cli sdr --gui\n") util.prompt_for_enter()
[ "def", "_print_sdr_instructions", "(", "info", ")", ":", "util", ".", "print_header", "(", "\"SDR Setup\"", ")", "util", ".", "print_sub_header", "(", "\"Connections\"", ")", "print", "(", "\"The SDR setup is connected as follows:\\n\"", ")", "print", "(", "\"LNB ----> Power Supply ----> RTL-SDR ----> Host\\n\"", ")", "_item", "(", "\"Connect the RTL-SDR USB dongle to your host PC.\"", ")", "_item", "(", "\"Connect the **non-powered** port of the power supply (labeled as \"", "\"\\\"Signal to IRD\\\") to the RTL-SDR using an SMA cable and an \"", "\"SMA-to-F adapter.\"", ")", "_item", "(", "\"Connect the **powered** port (labeled \\\"Signal to SWM\\\") of the \"", "\"power supply to the LNB using a coaxial cable (an RG6 cable is \"", "\"recommended).\"", ")", "print", "(", ")", "_print", "(", "\"IMPORTANT: Do NOT connect the powered port of the power supply \"", "\"to the SDR interface. Permanent damage may occur to your SDR \"", "\"and/or your computer.\"", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Software Requirements\"", ")", "print", "(", "\"The SDR-based setup relies on the applications listed below:\\n\"", ")", "_item", "(", "\"leandvb: a software-based DVB-S2 receiver application.\"", ")", "_item", "(", "\"rtl_sdr: reads samples taken by the RTL-SDR and feeds them into \"", "\"leandvb.\"", ")", "_item", "(", "\"TSDuck: unpacks the output of leandvb and produces \"", "\"IP packets to be fed to Bitcoin Satellite.\"", ")", "_item", "(", "\"Gqrx: useful for spectrum visualization during antenna pointing.\"", ")", "print", "(", "\"\\nTo install them, run:\"", ")", "print", "(", "\"\"\"\n blocksat-cli deps install\n \"\"\"", ")", "_print", "(", "\"\"\"\n NOTE: This command supports the two most recent Ubuntu LTS, Fedora, and\n CentOS releases. In case you are using another Linux distribution or\n version, please refer to the manual compilation and installation\n instructions at:\"\"\"", ")", "print", "(", "defs", ".", "user_guide_url", "+", "\"doc/sdr.html\"", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Configuration\"", ")", "_print", "(", "\"Next, you can generate the configurations that are needed for gqrx \"", "\"by running:\"", ")", "print", "(", "\" blocksat-cli gqrx-conf\"", ")", "util", ".", "prompt_for_enter", "(", ")", "util", ".", "print_sub_header", "(", "\"Running\"", ")", "_print", "(", "\"You should now be ready to launch the SDR receiver. You can run it \"", "\"by executing:\"", ")", "print", "(", "\" blocksat-cli sdr\\n\"", ")", "print", "(", "\"Or, in GUI mode:\\n\"", ")", "print", "(", "\" blocksat-cli sdr --gui\\n\"", ")", "util", ".", "prompt_for_enter", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/instructions.py#L200-L271
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/instructions.py
python
_print_freq_info
(info)
Print summary of frequencies of interest
Print summary of frequencies of interest
[ "Print", "summary", "of", "frequencies", "of", "interest" ]
def _print_freq_info(info): """Print summary of frequencies of interest""" sat = info['sat'] setup = info['setup'] lnb = info['lnb'] lo_freq = info['freqs']['lo'] l_freq = info['freqs']['l_band'] util.print_header("Frequencies") print("For your information, your setup relies on the following " "frequencies:\n") print("| Downlink %2s band frequency | %8.2f MHz |" % (sat['band'], sat['dl_freq'])) print("| LNB local oscillator (LO) frequency | %8.2f MHz |" % (lo_freq)) print("| Receiver L-band frequency | %7.2f MHz |" % (l_freq)) print() if (lnb['universal'] and (setup['type'] == defs.sdr_setup_type)): if (sat['dl_freq'] > defs.ku_band_thresh): print("NOTE regarding Universal LNB:\n") print( textwrap.fill( ("The DL frequency of {} is in Ku high " "band (> {:.1f} MHz). Hence, you need to use " "the higher frequency LO ({:.1f} MHz) of your " "Universal LNB. This requires a 22 kHz tone " "to be sent to the LNB.").format(sat['alias'], defs.ku_band_thresh, lo_freq))) print() print( textwrap.fill(("With a software-defined setup, you will " "need to place a 22 kHz tone generator " "inline between the LNB and the power " "inserter. Typically the tone generator " "uses power from the power inserter while " "delivering the tone directly to the " "LNB."))) util.prompt_for_enter()
[ "def", "_print_freq_info", "(", "info", ")", ":", "sat", "=", "info", "[", "'sat'", "]", "setup", "=", "info", "[", "'setup'", "]", "lnb", "=", "info", "[", "'lnb'", "]", "lo_freq", "=", "info", "[", "'freqs'", "]", "[", "'lo'", "]", "l_freq", "=", "info", "[", "'freqs'", "]", "[", "'l_band'", "]", "util", ".", "print_header", "(", "\"Frequencies\"", ")", "print", "(", "\"For your information, your setup relies on the following \"", "\"frequencies:\\n\"", ")", "print", "(", "\"| Downlink %2s band frequency | %8.2f MHz |\"", "%", "(", "sat", "[", "'band'", "]", ",", "sat", "[", "'dl_freq'", "]", ")", ")", "print", "(", "\"| LNB local oscillator (LO) frequency | %8.2f MHz |\"", "%", "(", "lo_freq", ")", ")", "print", "(", "\"| Receiver L-band frequency | %7.2f MHz |\"", "%", "(", "l_freq", ")", ")", "print", "(", ")", "if", "(", "lnb", "[", "'universal'", "]", "and", "(", "setup", "[", "'type'", "]", "==", "defs", ".", "sdr_setup_type", ")", ")", ":", "if", "(", "sat", "[", "'dl_freq'", "]", ">", "defs", ".", "ku_band_thresh", ")", ":", "print", "(", "\"NOTE regarding Universal LNB:\\n\"", ")", "print", "(", "textwrap", ".", "fill", "(", "(", "\"The DL frequency of {} is in Ku high \"", "\"band (> {:.1f} MHz). Hence, you need to use \"", "\"the higher frequency LO ({:.1f} MHz) of your \"", "\"Universal LNB. This requires a 22 kHz tone \"", "\"to be sent to the LNB.\"", ")", ".", "format", "(", "sat", "[", "'alias'", "]", ",", "defs", ".", "ku_band_thresh", ",", "lo_freq", ")", ")", ")", "print", "(", ")", "print", "(", "textwrap", ".", "fill", "(", "(", "\"With a software-defined setup, you will \"", "\"need to place a 22 kHz tone generator \"", "\"inline between the LNB and the power \"", "\"inserter. Typically the tone generator \"", "\"uses power from the power inserter while \"", "\"delivering the tone directly to the \"", "\"LNB.\"", ")", ")", ")", "util", ".", "prompt_for_enter", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/instructions.py#L328-L369
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/instructions.py
python
_print_lnb_info
(info)
Print important waraning based on LNB choice
Print important waraning based on LNB choice
[ "Print", "important", "waraning", "based", "on", "LNB", "choice" ]
def _print_lnb_info(info): """Print important waraning based on LNB choice""" lnb = info['lnb'] sat = info['sat'] setup = info['setup'] if ((lnb['pol'] != "Dual") and (lnb['pol'] != sat['pol'])): util.print_header("LNB Information") lnb_pol = "Vertical" if lnb['pol'] == "V" else "Horizontal" logging.warning( textwrap.fill( "Your LNB has {} polarization and the signal from {} has the " "opposite polarization.".format(lnb_pol, sat['name']))) util.prompt_for_enter() if ((lnb['pol'] == "Dual") and (setup['type'] == defs.sdr_setup_type)): util.print_header("LNB Information") logging.warning( textwrap.fill( "Your LNB has dual polarization. Check the voltage of your " "power supply in order to discover the polarization on which " "your LNB will operate.")) util.prompt_for_enter()
[ "def", "_print_lnb_info", "(", "info", ")", ":", "lnb", "=", "info", "[", "'lnb'", "]", "sat", "=", "info", "[", "'sat'", "]", "setup", "=", "info", "[", "'setup'", "]", "if", "(", "(", "lnb", "[", "'pol'", "]", "!=", "\"Dual\"", ")", "and", "(", "lnb", "[", "'pol'", "]", "!=", "sat", "[", "'pol'", "]", ")", ")", ":", "util", ".", "print_header", "(", "\"LNB Information\"", ")", "lnb_pol", "=", "\"Vertical\"", "if", "lnb", "[", "'pol'", "]", "==", "\"V\"", "else", "\"Horizontal\"", "logging", ".", "warning", "(", "textwrap", ".", "fill", "(", "\"Your LNB has {} polarization and the signal from {} has the \"", "\"opposite polarization.\"", ".", "format", "(", "lnb_pol", ",", "sat", "[", "'name'", "]", ")", ")", ")", "util", ".", "prompt_for_enter", "(", ")", "if", "(", "(", "lnb", "[", "'pol'", "]", "==", "\"Dual\"", ")", "and", "(", "setup", "[", "'type'", "]", "==", "defs", ".", "sdr_setup_type", ")", ")", ":", "util", ".", "print_header", "(", "\"LNB Information\"", ")", "logging", ".", "warning", "(", "textwrap", ".", "fill", "(", "\"Your LNB has dual polarization. Check the voltage of your \"", "\"power supply in order to discover the polarization on which \"", "\"your LNB will operate.\"", ")", ")", "util", ".", "prompt_for_enter", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/instructions.py#L372-L394
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/instructions.py
python
subparser
(subparsers)
return p
Argument parser of instructions command
Argument parser of instructions command
[ "Argument", "parser", "of", "instructions", "command" ]
def subparser(subparsers): """Argument parser of instructions command""" p = subparsers.add_parser('instructions', description="Instructions for Blocksat Rx setup", help='Read instructions for the receiver setup', formatter_class=ArgumentDefaultsHelpFormatter) p.set_defaults(func=show) return p
[ "def", "subparser", "(", "subparsers", ")", ":", "p", "=", "subparsers", ".", "add_parser", "(", "'instructions'", ",", "description", "=", "\"Instructions for Blocksat Rx setup\"", ",", "help", "=", "'Read instructions for the receiver setup'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "p", ".", "set_defaults", "(", "func", "=", "show", ")", "return", "p" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/instructions.py#L426-L433
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/instructions.py
python
show
(args)
Show instructions
Show instructions
[ "Show", "instructions" ]
def show(args): """Show instructions""" info = config.read_cfg_file(args.cfg, args.cfg_dir) if (info is None): return os.system('clear') _print_lnb_info(info) if (info['setup']['type'] == defs.standalone_setup_type): _print_s400_instructions(info) elif (info['setup']['type'] == defs.sdr_setup_type): _print_sdr_instructions(info) elif (info['setup']['type'] == defs.linux_usb_setup_type): _print_usb_rx_instructions(info) elif (info['setup']['type'] == defs.sat_ip_setup_type): _print_sat_ip_instructions(info) _print_next_steps()
[ "def", "show", "(", "args", ")", ":", "info", "=", "config", ".", "read_cfg_file", "(", "args", ".", "cfg", ",", "args", ".", "cfg_dir", ")", "if", "(", "info", "is", "None", ")", ":", "return", "os", ".", "system", "(", "'clear'", ")", "_print_lnb_info", "(", "info", ")", "if", "(", "info", "[", "'setup'", "]", "[", "'type'", "]", "==", "defs", ".", "standalone_setup_type", ")", ":", "_print_s400_instructions", "(", "info", ")", "elif", "(", "info", "[", "'setup'", "]", "[", "'type'", "]", "==", "defs", ".", "sdr_setup_type", ")", ":", "_print_sdr_instructions", "(", "info", ")", "elif", "(", "info", "[", "'setup'", "]", "[", "'type'", "]", "==", "defs", ".", "linux_usb_setup_type", ")", ":", "_print_usb_rx_instructions", "(", "info", ")", "elif", "(", "info", "[", "'setup'", "]", "[", "'type'", "]", "==", "defs", ".", "sat_ip_setup_type", ")", ":", "_print_sat_ip_instructions", "(", "info", ")", "_print_next_steps", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/instructions.py#L436-L455
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/main.py
python
main
()
Main - parse command-line arguments and call subcommands
Main - parse command-line arguments and call subcommands
[ "Main", "-", "parse", "command", "-", "line", "arguments", "and", "call", "subcommands" ]
def main(): """Main - parse command-line arguments and call subcommands """ default_cfg_dir = os.path.join(util.get_home_dir(), ".blocksat") parser = ArgumentParser( prog="blocksat-cli", description="Blockstream Satellite Command-Line Interface", formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('-d', '--debug', action='store_true', help='Set debug mode') parser.add_argument('--cfg', default="config", help="Target configuration set") parser.add_argument('--cfg-dir', default=default_cfg_dir, help="Directory to use for configuration files") parser.add_argument('--utc', action='store_true', help="Print log timestamps in UTC") parser.add_argument('-v', '--version', action='version', version='%(prog)s {}'.format(__version__)) subparsers = parser.add_subparsers(title='subcommands', help='Target sub-command', dest='subcommand') config.subparser(subparsers) instructions.subparser(subparsers) dependencies.subparser(subparsers) usb.subparser(subparsers) standalone.subparser(subparsers) rp.subparser(subparsers) firewall.subparser(subparsers) gqrx.subparser(subparsers) bitcoin.subparser(subparsers) sdr.subparser(subparsers) api.subparser(subparsers) satip.subparser(subparsers) args = parser.parse_args() # Filter commands that are Linux-only if (args.subcommand not in ["cfg", "instructions", "api", "btc"]): assert(platform.system() == 'Linux'), \ "Command {} is currently Linux-only".format(args.subcommand) # Logging logging_fmt = '%(asctime)s %(levelname)-8s %(name)s %(message)s' if \ args.debug else '%(asctime)s %(levelname)-8s %(message)s' logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO, format=logging_fmt, datefmt='%Y-%m-%d %H:%M:%S') if (args.utc): logging.Formatter.converter = time.gmtime logging.debug('[Debug Mode]') # Check CLI updates update.check_cli_updates(args, __version__) if hasattr(args, 'func'): args.func(args) else: parser.print_help()
[ "def", "main", "(", ")", ":", "default_cfg_dir", "=", "os", ".", "path", ".", "join", "(", "util", ".", "get_home_dir", "(", ")", ",", "\".blocksat\"", ")", "parser", "=", "ArgumentParser", "(", "prog", "=", "\"blocksat-cli\"", ",", "description", "=", "\"Blockstream Satellite Command-Line Interface\"", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Set debug mode'", ")", "parser", ".", "add_argument", "(", "'--cfg'", ",", "default", "=", "\"config\"", ",", "help", "=", "\"Target configuration set\"", ")", "parser", ".", "add_argument", "(", "'--cfg-dir'", ",", "default", "=", "default_cfg_dir", ",", "help", "=", "\"Directory to use for configuration files\"", ")", "parser", ".", "add_argument", "(", "'--utc'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"Print log timestamps in UTC\"", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "'%(prog)s {}'", ".", "format", "(", "__version__", ")", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", "title", "=", "'subcommands'", ",", "help", "=", "'Target sub-command'", ",", "dest", "=", "'subcommand'", ")", "config", ".", "subparser", "(", "subparsers", ")", "instructions", ".", "subparser", "(", "subparsers", ")", "dependencies", ".", "subparser", "(", "subparsers", ")", "usb", ".", "subparser", "(", "subparsers", ")", "standalone", ".", "subparser", "(", "subparsers", ")", "rp", ".", "subparser", "(", "subparsers", ")", "firewall", ".", "subparser", "(", "subparsers", ")", "gqrx", ".", "subparser", "(", "subparsers", ")", "bitcoin", ".", "subparser", "(", "subparsers", ")", "sdr", ".", "subparser", "(", "subparsers", ")", "api", ".", "subparser", "(", "subparsers", ")", "satip", ".", "subparser", "(", "subparsers", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "# Filter commands that are Linux-only", "if", "(", "args", ".", "subcommand", "not", "in", "[", "\"cfg\"", ",", "\"instructions\"", ",", "\"api\"", ",", "\"btc\"", "]", ")", ":", "assert", "(", "platform", ".", "system", "(", ")", "==", "'Linux'", ")", ",", "\"Command {} is currently Linux-only\"", ".", "format", "(", "args", ".", "subcommand", ")", "# Logging", "logging_fmt", "=", "'%(asctime)s %(levelname)-8s %(name)s %(message)s'", "if", "args", ".", "debug", "else", "'%(asctime)s %(levelname)-8s %(message)s'", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", "if", "args", ".", "debug", "else", "logging", ".", "INFO", ",", "format", "=", "logging_fmt", ",", "datefmt", "=", "'%Y-%m-%d %H:%M:%S'", ")", "if", "(", "args", ".", "utc", ")", ":", "logging", ".", "Formatter", ".", "converter", "=", "time", ".", "gmtime", "logging", ".", "debug", "(", "'[Debug Mode]'", ")", "# Check CLI updates", "update", ".", "check_cli_updates", "(", "args", ",", "__version__", ")", "if", "hasattr", "(", "args", ",", "'func'", ")", ":", "args", ".", "func", "(", "args", ")", "else", ":", "parser", ".", "print_help", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/main.py#L16-L83
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/gqrx.py
python
configure
(args)
Configure GQRX
Configure GQRX
[ "Configure", "GQRX" ]
def configure(args): """Configure GQRX""" info = config.read_cfg_file(args.cfg, args.cfg_dir) if (info is None): return util.print_header("Gqrx Conf Generator") if args.path is None: home = os.path.expanduser("~") path = os.path.join(home, ".config", "gqrx") else: path = args.path conf_file = "default.conf" abs_path = os.path.join(path, conf_file) default_gains = r'@Variant(\0\0\0\b\0\0\0\x2\0\0\0\x6\0L\0N\0\x41\0\0' + \ r'\0\x2\0\0\x1\x92\0\0\0\x4\0I\0\x46\0\0\0\x2\0\0\0\xcc)' cfg = """ [General] configversion=2 [fft] averaging=80 db_ranges_locked=true pandapter_min_db=-90 waterfall_min_db=-90 [input] bandwidth=1000000 device="rtl=0" frequency={} gains={} lnb_lo={} sample_rate=2400000 [receiver] demod=0 """.format( int(info['freqs']['dl'] * 1e6), default_gains, int(info['freqs']['lo'] * 1e6), ) print("Save {} at {}/".format(conf_file, path)) if (not util.ask_yes_or_no("Proceed?")): print("Aborted") return if not os.path.exists(path): os.makedirs(path) if os.path.exists(abs_path): if (not util.ask_yes_or_no("File already exists. Overwrite?")): print("Aborted") return with open(abs_path, "w") as file: file.write(textwrap.dedent(cfg)) print("Saved")
[ "def", "configure", "(", "args", ")", ":", "info", "=", "config", ".", "read_cfg_file", "(", "args", ".", "cfg", ",", "args", ".", "cfg_dir", ")", "if", "(", "info", "is", "None", ")", ":", "return", "util", ".", "print_header", "(", "\"Gqrx Conf Generator\"", ")", "if", "args", ".", "path", "is", "None", ":", "home", "=", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "path", "=", "os", ".", "path", ".", "join", "(", "home", ",", "\".config\"", ",", "\"gqrx\"", ")", "else", ":", "path", "=", "args", ".", "path", "conf_file", "=", "\"default.conf\"", "abs_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "conf_file", ")", "default_gains", "=", "r'@Variant(\\0\\0\\0\\b\\0\\0\\0\\x2\\0\\0\\0\\x6\\0L\\0N\\0\\x41\\0\\0'", "+", "r'\\0\\x2\\0\\0\\x1\\x92\\0\\0\\0\\x4\\0I\\0\\x46\\0\\0\\0\\x2\\0\\0\\0\\xcc)'", "cfg", "=", "\"\"\"\n [General]\n configversion=2\n\n [fft]\n averaging=80\n db_ranges_locked=true\n pandapter_min_db=-90\n waterfall_min_db=-90\n\n [input]\n bandwidth=1000000\n device=\"rtl=0\"\n frequency={}\n gains={}\n lnb_lo={}\n sample_rate=2400000\n\n [receiver]\n demod=0\n \"\"\"", ".", "format", "(", "int", "(", "info", "[", "'freqs'", "]", "[", "'dl'", "]", "*", "1e6", ")", ",", "default_gains", ",", "int", "(", "info", "[", "'freqs'", "]", "[", "'lo'", "]", "*", "1e6", ")", ",", ")", "print", "(", "\"Save {} at {}/\"", ".", "format", "(", "conf_file", ",", "path", ")", ")", "if", "(", "not", "util", ".", "ask_yes_or_no", "(", "\"Proceed?\"", ")", ")", ":", "print", "(", "\"Aborted\"", ")", "return", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "abs_path", ")", ":", "if", "(", "not", "util", ".", "ask_yes_or_no", "(", "\"File already exists. Overwrite?\"", ")", ")", ":", "print", "(", "\"Aborted\"", ")", "return", "with", "open", "(", "abs_path", ",", "\"w\"", ")", "as", "file", ":", "file", ".", "write", "(", "textwrap", ".", "dedent", "(", "cfg", ")", ")", "print", "(", "\"Saved\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/gqrx.py#L24-L88
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring_api.py
python
BsMonitoring._setup_registered
(self)
Setup for a receiver that is already registered If already registered, confirm that the registered GPG key is available in the keyring and prompt for the GPG private key passphrase required to sign report data
Setup for a receiver that is already registered
[ "Setup", "for", "a", "receiver", "that", "is", "already", "registered" ]
def _setup_registered(self): """Setup for a receiver that is already registered If already registered, confirm that the registered GPG key is available in the keyring and prompt for the GPG private key passphrase required to sign report data """ fingerprint = self.user_info['monitoring']['fingerprint'] matching_keys = self.gpg.gpg.list_keys(True, keys=fingerprint) if (len(matching_keys) == 0): logger.error("Could not find key {} in the local " "keyring.".format(fingerprint)) try_again = util.ask_yes_or_no( "Reset the Monitoring API credentials and try registering " "with a new key?", default="n") if (try_again): self._delete_credentials() self._register() else: raise RuntimeError("Monitoring configuration failed") # Return regardless. If the key is not available, don't bother # about the password. return self.gpg.prompt_passphrase('Please enter your GPG passphrase to ' 'sign receiver reports: ')
[ "def", "_setup_registered", "(", "self", ")", ":", "fingerprint", "=", "self", ".", "user_info", "[", "'monitoring'", "]", "[", "'fingerprint'", "]", "matching_keys", "=", "self", ".", "gpg", ".", "gpg", ".", "list_keys", "(", "True", ",", "keys", "=", "fingerprint", ")", "if", "(", "len", "(", "matching_keys", ")", "==", "0", ")", ":", "logger", ".", "error", "(", "\"Could not find key {} in the local \"", "\"keyring.\"", ".", "format", "(", "fingerprint", ")", ")", "try_again", "=", "util", ".", "ask_yes_or_no", "(", "\"Reset the Monitoring API credentials and try registering \"", "\"with a new key?\"", ",", "default", "=", "\"n\"", ")", "if", "(", "try_again", ")", ":", "self", ".", "_delete_credentials", "(", ")", "self", ".", "_register", "(", ")", "else", ":", "raise", "RuntimeError", "(", "\"Monitoring configuration failed\"", ")", "# Return regardless. If the key is not available, don't bother", "# about the password.", "return", "self", ".", "gpg", ".", "prompt_passphrase", "(", "'Please enter your GPG passphrase to '", "'sign receiver reports: '", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring_api.py#L132-L159
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring_api.py
python
BsMonitoring._delete_credentials
(self)
Remove the registration info from the local config file
Remove the registration info from the local config file
[ "Remove", "the", "registration", "info", "from", "the", "local", "config", "file" ]
def _delete_credentials(self): """Remove the registration info from the local config file""" self.user_info.pop('monitoring') config.write_cfg_file(self.cfg, self.cfg_dir, self.user_info) self.registered = False
[ "def", "_delete_credentials", "(", "self", ")", ":", "self", ".", "user_info", ".", "pop", "(", "'monitoring'", ")", "config", ".", "write_cfg_file", "(", "self", ".", "cfg", ",", "self", ".", "cfg_dir", ",", "self", ".", "user_info", ")", "self", ".", "registered", "=", "False" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring_api.py#L161-L165
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring_api.py
python
BsMonitoring._save_credentials
(self, uuid, fingerprint)
Record the successful registration locally on the JSON config
Record the successful registration locally on the JSON config
[ "Record", "the", "successful", "registration", "locally", "on", "the", "JSON", "config" ]
def _save_credentials(self, uuid, fingerprint): """Record the successful registration locally on the JSON config""" self.user_info['monitoring'] = { 'registered': True, 'uuid': uuid, 'fingerprint': fingerprint } config.write_cfg_file(self.cfg, self.cfg_dir, self.user_info) self.registered = True
[ "def", "_save_credentials", "(", "self", ",", "uuid", ",", "fingerprint", ")", ":", "self", ".", "user_info", "[", "'monitoring'", "]", "=", "{", "'registered'", ":", "True", ",", "'uuid'", ":", "uuid", ",", "'fingerprint'", ":", "fingerprint", "}", "config", ".", "write_cfg_file", "(", "self", ".", "cfg", ",", "self", ".", "cfg_dir", ",", "self", ".", "user_info", ")", "self", ".", "registered", "=", "True" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring_api.py#L167-L175
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring_api.py
python
BsMonitoring._register
(self)
Run the registration procedure The procedure is divided in two steps: 1) Interaction with the user; 2) Interaction with the API. This method implements step 1, where it sets up a GPG keyring, collects the user address, and prepares the request parameters for registering with the monitoring API. In the end, it dispatches step 2 on a thread. Note step 2 has to run on a thread because it needs the receiver lock first. By running on a thread, the main (parent) thread can proceed to initializing the receiver.
Run the registration procedure
[ "Run", "the", "registration", "procedure" ]
def _register(self): """Run the registration procedure The procedure is divided in two steps: 1) Interaction with the user; 2) Interaction with the API. This method implements step 1, where it sets up a GPG keyring, collects the user address, and prepares the request parameters for registering with the monitoring API. In the end, it dispatches step 2 on a thread. Note step 2 has to run on a thread because it needs the receiver lock first. By running on a thread, the main (parent) thread can proceed to initializing the receiver. """ self.registration_running = True self.registration_failure = False # Save some state on the local cache cache = Cache(self.cfg_dir) # Show the explainer when running the registration for the first time # for this configuration if (cache.get(self.cfg + '.monitoring.explainer') is None): _register_explainer() # Cache flag indicating that the explainer has been shown already cache.set(self.cfg + '.monitoring.explainer', True) cache.save() # Create a GPG keyring and a keypair if necessary api.config_keyring(self.gpg) # Make sure the GPG passphrase is available. The passphrase can be # collected on key creation for a new keyring. On the other hand, it # wouldn't be available yet at this point for a pre-existing keyring. if (self.gpg.passphrase is None): util.fill_print("Please inform your GPG passphrase to decode the " "encrypted verification code sent over satellite") self.gpg.prompt_passphrase("GPG passphrase: ") os.system('clear') # Get the user's location util.fill_print( "Please inform you city, state (if applicable), and country:") confirmed = False while (not confirmed): # City (required) city = util.string_input("City") # State (optional) state = input("State: ") if (len(state) > 0): address = "{}, {}".format(city, state) else: address = city # Country (required) country = util.string_input("Country") # Wait until the user confirms the full address address += ", {}".format(country) confirmed = util.ask_yes_or_no("\"{}\"?".format(address)) os.system('clear') # Registration parameters fingerprint = self.gpg.get_default_priv_key()['fingerprint'] pubkey = self.gpg.gpg.export_keys(fingerprint) satellite = self.user_info['sat']['alias'] rx_type = config.get_rx_model(self.user_info) antenna = config.get_antenna_model(self.user_info) lnb = config.get_lnb_model(self.user_info) # Run step 2 on a thread t1 = threading.Thread(target=self._register_thread, daemon=True, args=(fingerprint, pubkey, address, satellite, rx_type, antenna, lnb)) t1.start()
[ "def", "_register", "(", "self", ")", ":", "self", ".", "registration_running", "=", "True", "self", ".", "registration_failure", "=", "False", "# Save some state on the local cache", "cache", "=", "Cache", "(", "self", ".", "cfg_dir", ")", "# Show the explainer when running the registration for the first time", "# for this configuration", "if", "(", "cache", ".", "get", "(", "self", ".", "cfg", "+", "'.monitoring.explainer'", ")", "is", "None", ")", ":", "_register_explainer", "(", ")", "# Cache flag indicating that the explainer has been shown already", "cache", ".", "set", "(", "self", ".", "cfg", "+", "'.monitoring.explainer'", ",", "True", ")", "cache", ".", "save", "(", ")", "# Create a GPG keyring and a keypair if necessary", "api", ".", "config_keyring", "(", "self", ".", "gpg", ")", "# Make sure the GPG passphrase is available. The passphrase can be", "# collected on key creation for a new keyring. On the other hand, it", "# wouldn't be available yet at this point for a pre-existing keyring.", "if", "(", "self", ".", "gpg", ".", "passphrase", "is", "None", ")", ":", "util", ".", "fill_print", "(", "\"Please inform your GPG passphrase to decode the \"", "\"encrypted verification code sent over satellite\"", ")", "self", ".", "gpg", ".", "prompt_passphrase", "(", "\"GPG passphrase: \"", ")", "os", ".", "system", "(", "'clear'", ")", "# Get the user's location", "util", ".", "fill_print", "(", "\"Please inform you city, state (if applicable), and country:\"", ")", "confirmed", "=", "False", "while", "(", "not", "confirmed", ")", ":", "# City (required)", "city", "=", "util", ".", "string_input", "(", "\"City\"", ")", "# State (optional)", "state", "=", "input", "(", "\"State: \"", ")", "if", "(", "len", "(", "state", ")", ">", "0", ")", ":", "address", "=", "\"{}, {}\"", ".", "format", "(", "city", ",", "state", ")", "else", ":", "address", "=", "city", "# Country (required)", "country", "=", "util", ".", "string_input", "(", "\"Country\"", ")", "# Wait until the user confirms the full address", "address", "+=", "\", {}\"", ".", "format", "(", "country", ")", "confirmed", "=", "util", ".", "ask_yes_or_no", "(", "\"\\\"{}\\\"?\"", ".", "format", "(", "address", ")", ")", "os", ".", "system", "(", "'clear'", ")", "# Registration parameters", "fingerprint", "=", "self", ".", "gpg", ".", "get_default_priv_key", "(", ")", "[", "'fingerprint'", "]", "pubkey", "=", "self", ".", "gpg", ".", "gpg", ".", "export_keys", "(", "fingerprint", ")", "satellite", "=", "self", ".", "user_info", "[", "'sat'", "]", "[", "'alias'", "]", "rx_type", "=", "config", ".", "get_rx_model", "(", "self", ".", "user_info", ")", "antenna", "=", "config", ".", "get_antenna_model", "(", "self", ".", "user_info", ")", "lnb", "=", "config", ".", "get_lnb_model", "(", "self", ".", "user_info", ")", "# Run step 2 on a thread", "t1", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_register_thread", ",", "daemon", "=", "True", ",", "args", "=", "(", "fingerprint", ",", "pubkey", ",", "address", ",", "satellite", ",", "rx_type", ",", "antenna", ",", "lnb", ")", ")", "t1", ".", "start", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring_api.py#L177-L259
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring_api.py
python
BsMonitoring._register_thread
(self, fingerprint, pubkey, address, satellite, rx_type, antenna, lnb, attempts=5)
Complete the registration procedure after receiver locking Sends the registration request to the Monitoring API and waits for the validation code sent over satellite through a Satellite API message. Args: fingerprint : User GnuPG fingerprint pubkey : User GnuPG public key address : User address satellite : Satellite covering the user location rx_type : Receiver type (vendor and model) antenna : Antenna type and size lnb : LNB model attempts : Maximum number of registration attempts
Complete the registration procedure after receiver locking
[ "Complete", "the", "registration", "procedure", "after", "receiver", "locking" ]
def _register_thread(self, fingerprint, pubkey, address, satellite, rx_type, antenna, lnb, attempts=5): """Complete the registration procedure after receiver locking Sends the registration request to the Monitoring API and waits for the validation code sent over satellite through a Satellite API message. Args: fingerprint : User GnuPG fingerprint pubkey : User GnuPG public key address : User address satellite : Satellite covering the user location rx_type : Receiver type (vendor and model) antenna : Antenna type and size lnb : LNB model attempts : Maximum number of registration attempts """ logger.info( "Waiting for Rx lock to initiate the registration with the " "monitoring server") self.rx_lock_event.wait() logger.info("Receiver locked. Ready to initiate the registration with " "the monitoring server.") logger.info("Launching the API listener to receive the verification " "code sent over satellite") # Run the API listener loop # # Note the validation code is: # - Encrypted to us (the Monitoring API encrypts using our public key) # - Sent as a raw (non-encapsulated) API message # - Sent over the API channel dedicated for authentication messages download_dir = None # Don't save messages interface = config.get_net_if(self.user_info) recv_queue = queue.Queue() # save API donwloads on this queue listen_loop = ApiListener(recv_queue=recv_queue) listen_thread = threading.Thread(target=listen_loop.run, daemon=True, args=(self.gpg, download_dir, defs.api_dst_addr, interface), kwargs={ 'channel': ApiChannel.AUTH.value, 'plaintext': False, 'save_raw': True, 'no_save': True }) listen_thread.start() failure = False while (attempts > 0): rv = requests.post(account_endpoint, json={ 'fingerprint': fingerprint, 'publickey': pubkey, 'city': address, 'satellite': satellite, 'receiver_type': rx_type, 'antenna': antenna, 'lnb': lnb }) if (rv.status_code != requests.codes.ok): logger.error("Failed to register receiver with the monitoring " "server") logger.error("{} ({})".format(rv.reason, rv.status_code)) # If the initial registration call fails, declare failure right # away and break the loop. The problem likely won't go away if # we try again (e.g., a server error or invalid pubkey). failure = True break uuid = rv.json()['uuid'] verified = rv.json()['verified'] if (verified): logger.info("Receiver already registered and verified") self._save_credentials(uuid, fingerprint) break try: validation_key = recv_queue.get(timeout=10) recv_queue.task_done() except queue.Empty: logger.warning("Failed to receive the verification code. " "Trying again...") attempts -= 1 continue rv = requests.patch(account_endpoint, json={ 'uuid': uuid, 'validation_key': validation_key.decode() }) if (rv.status_code != requests.codes.ok): logger.error("Verification failed") logger.error("{} ({})".format(rv.reason, rv.status_code)) attempts -= 1 if (attempts > 0): logger.warning("Trying again...") time.sleep(1) else: logger.info("Functional receiver successfully validated") logger.info("Ready to report Rx metrics to the monitoring " "server") self._save_credentials(uuid, fingerprint) break if (attempts == 0): logger.error("Maximum number of registration attempts " "reached") logger.error("Please check if your receiver is running properly " "and restart the application to try again") failure = True self.registration_running = False self.registration_failure = failure # Stop the API listener listen_loop.stop() listen_thread.join()
[ "def", "_register_thread", "(", "self", ",", "fingerprint", ",", "pubkey", ",", "address", ",", "satellite", ",", "rx_type", ",", "antenna", ",", "lnb", ",", "attempts", "=", "5", ")", ":", "logger", ".", "info", "(", "\"Waiting for Rx lock to initiate the registration with the \"", "\"monitoring server\"", ")", "self", ".", "rx_lock_event", ".", "wait", "(", ")", "logger", ".", "info", "(", "\"Receiver locked. Ready to initiate the registration with \"", "\"the monitoring server.\"", ")", "logger", ".", "info", "(", "\"Launching the API listener to receive the verification \"", "\"code sent over satellite\"", ")", "# Run the API listener loop", "#", "# Note the validation code is:", "# - Encrypted to us (the Monitoring API encrypts using our public key)", "# - Sent as a raw (non-encapsulated) API message", "# - Sent over the API channel dedicated for authentication messages", "download_dir", "=", "None", "# Don't save messages", "interface", "=", "config", ".", "get_net_if", "(", "self", ".", "user_info", ")", "recv_queue", "=", "queue", ".", "Queue", "(", ")", "# save API donwloads on this queue", "listen_loop", "=", "ApiListener", "(", "recv_queue", "=", "recv_queue", ")", "listen_thread", "=", "threading", ".", "Thread", "(", "target", "=", "listen_loop", ".", "run", ",", "daemon", "=", "True", ",", "args", "=", "(", "self", ".", "gpg", ",", "download_dir", ",", "defs", ".", "api_dst_addr", ",", "interface", ")", ",", "kwargs", "=", "{", "'channel'", ":", "ApiChannel", ".", "AUTH", ".", "value", ",", "'plaintext'", ":", "False", ",", "'save_raw'", ":", "True", ",", "'no_save'", ":", "True", "}", ")", "listen_thread", ".", "start", "(", ")", "failure", "=", "False", "while", "(", "attempts", ">", "0", ")", ":", "rv", "=", "requests", ".", "post", "(", "account_endpoint", ",", "json", "=", "{", "'fingerprint'", ":", "fingerprint", ",", "'publickey'", ":", "pubkey", ",", "'city'", ":", "address", ",", "'satellite'", ":", "satellite", ",", "'receiver_type'", ":", "rx_type", ",", "'antenna'", ":", "antenna", ",", "'lnb'", ":", "lnb", "}", ")", "if", "(", "rv", ".", "status_code", "!=", "requests", ".", "codes", ".", "ok", ")", ":", "logger", ".", "error", "(", "\"Failed to register receiver with the monitoring \"", "\"server\"", ")", "logger", ".", "error", "(", "\"{} ({})\"", ".", "format", "(", "rv", ".", "reason", ",", "rv", ".", "status_code", ")", ")", "# If the initial registration call fails, declare failure right", "# away and break the loop. The problem likely won't go away if", "# we try again (e.g., a server error or invalid pubkey).", "failure", "=", "True", "break", "uuid", "=", "rv", ".", "json", "(", ")", "[", "'uuid'", "]", "verified", "=", "rv", ".", "json", "(", ")", "[", "'verified'", "]", "if", "(", "verified", ")", ":", "logger", ".", "info", "(", "\"Receiver already registered and verified\"", ")", "self", ".", "_save_credentials", "(", "uuid", ",", "fingerprint", ")", "break", "try", ":", "validation_key", "=", "recv_queue", ".", "get", "(", "timeout", "=", "10", ")", "recv_queue", ".", "task_done", "(", ")", "except", "queue", ".", "Empty", ":", "logger", ".", "warning", "(", "\"Failed to receive the verification code. \"", "\"Trying again...\"", ")", "attempts", "-=", "1", "continue", "rv", "=", "requests", ".", "patch", "(", "account_endpoint", ",", "json", "=", "{", "'uuid'", ":", "uuid", ",", "'validation_key'", ":", "validation_key", ".", "decode", "(", ")", "}", ")", "if", "(", "rv", ".", "status_code", "!=", "requests", ".", "codes", ".", "ok", ")", ":", "logger", ".", "error", "(", "\"Verification failed\"", ")", "logger", ".", "error", "(", "\"{} ({})\"", ".", "format", "(", "rv", ".", "reason", ",", "rv", ".", "status_code", ")", ")", "attempts", "-=", "1", "if", "(", "attempts", ">", "0", ")", ":", "logger", ".", "warning", "(", "\"Trying again...\"", ")", "time", ".", "sleep", "(", "1", ")", "else", ":", "logger", ".", "info", "(", "\"Functional receiver successfully validated\"", ")", "logger", ".", "info", "(", "\"Ready to report Rx metrics to the monitoring \"", "\"server\"", ")", "self", ".", "_save_credentials", "(", "uuid", ",", "fingerprint", ")", "break", "if", "(", "attempts", "==", "0", ")", ":", "logger", ".", "error", "(", "\"Maximum number of registration attempts \"", "\"reached\"", ")", "logger", ".", "error", "(", "\"Please check if your receiver is running properly \"", "\"and restart the application to try again\"", ")", "failure", "=", "True", "self", ".", "registration_running", "=", "False", "self", ".", "registration_failure", "=", "failure", "# Stop the API listener", "listen_loop", ".", "stop", "(", ")", "listen_thread", ".", "join", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring_api.py#L261-L390
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/monitoring_api.py
python
BsMonitoring.sign_report
(self, data)
Sign a dictionary of metrics to be reported to the monitoring API First, add the monitored receiver's UUID to the dictionary of metrics. Then, use the default local GPG privkey to generate a detached signature corresponding to the JSON-dumped version of the dictionary (including the UUID). Lastly, append the detached signature. The resulting dictionary (including both the UUID and the signature) is ready to be sent to the API. Args: data : Dictionary with receiver data to be reported
Sign a dictionary of metrics to be reported to the monitoring API
[ "Sign", "a", "dictionary", "of", "metrics", "to", "be", "reported", "to", "the", "monitoring", "API" ]
def sign_report(self, data): """Sign a dictionary of metrics to be reported to the monitoring API First, add the monitored receiver's UUID to the dictionary of metrics. Then, use the default local GPG privkey to generate a detached signature corresponding to the JSON-dumped version of the dictionary (including the UUID). Lastly, append the detached signature. The resulting dictionary (including both the UUID and the signature) is ready to be sent to the API. Args: data : Dictionary with receiver data to be reported """ assert (self.registered) data['uuid'] = self.user_info['monitoring']['uuid'] fingerprint = self.user_info['monitoring']['fingerprint'] data['signature'] = str( self.gpg.sign(json.dumps(data), fingerprint, clearsign=False, detach=True)) if (data['signature'] == ''): logger.error('GPG signature failed')
[ "def", "sign_report", "(", "self", ",", "data", ")", ":", "assert", "(", "self", ".", "registered", ")", "data", "[", "'uuid'", "]", "=", "self", ".", "user_info", "[", "'monitoring'", "]", "[", "'uuid'", "]", "fingerprint", "=", "self", ".", "user_info", "[", "'monitoring'", "]", "[", "'fingerprint'", "]", "data", "[", "'signature'", "]", "=", "str", "(", "self", ".", "gpg", ".", "sign", "(", "json", ".", "dumps", "(", "data", ")", ",", "fingerprint", ",", "clearsign", "=", "False", ",", "detach", "=", "True", ")", ")", "if", "(", "data", "[", "'signature'", "]", "==", "''", ")", ":", "logger", ".", "error", "(", "'GPG signature failed'", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/monitoring_api.py#L392-L415
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
_check_distro
(setup_type)
Check if distribution is supported
Check if distribution is supported
[ "Check", "if", "distribution", "is", "supported" ]
def _check_distro(setup_type): """Check if distribution is supported""" if (distro.id() in supported_distros): return base_url = defs.user_guide_url + "doc/" instructions_url = { defs.sdr_setup_type: "sdr.md", defs.linux_usb_setup_type: "tbs.md", defs.standalone_setup_type: "s400.md", defs.sat_ip_setup_type: "sat-ip.md" } full_url = base_url + instructions_url[setup_type] logger.error("{} is not a supported Linux distribution".format( distro.name())) logger.info( textwrap.fill("Please, refer to the {} receiver setup " "instructions at {}".format(setup_type, full_url))) raise ValueError("Unsupported Linux distribution")
[ "def", "_check_distro", "(", "setup_type", ")", ":", "if", "(", "distro", ".", "id", "(", ")", "in", "supported_distros", ")", ":", "return", "base_url", "=", "defs", ".", "user_guide_url", "+", "\"doc/\"", "instructions_url", "=", "{", "defs", ".", "sdr_setup_type", ":", "\"sdr.md\"", ",", "defs", ".", "linux_usb_setup_type", ":", "\"tbs.md\"", ",", "defs", ".", "standalone_setup_type", ":", "\"s400.md\"", ",", "defs", ".", "sat_ip_setup_type", ":", "\"sat-ip.md\"", "}", "full_url", "=", "base_url", "+", "instructions_url", "[", "setup_type", "]", "logger", ".", "error", "(", "\"{} is not a supported Linux distribution\"", ".", "format", "(", "distro", ".", "name", "(", ")", ")", ")", "logger", ".", "info", "(", "textwrap", ".", "fill", "(", "\"Please, refer to the {} receiver setup \"", "\"instructions at {}\"", ".", "format", "(", "setup_type", ",", "full_url", ")", ")", ")", "raise", "ValueError", "(", "\"Unsupported Linux distribution\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L30-L48
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
_get_apt_repo
(distro_id)
return apt_repo
Find the APT package repository for the given distro
Find the APT package repository for the given distro
[ "Find", "the", "APT", "package", "repository", "for", "the", "given", "distro" ]
def _get_apt_repo(distro_id): """Find the APT package repository for the given distro""" if distro_id == "ubuntu": apt_repo = "ppa:blockstream/satellite" elif distro_id in ["debian", "raspbian"]: apt_repo = ("https://aptly.blockstream.com/" "satellite/{}/").format(distro_id) else: raise ValueError("Unsupported distribution {}".format(distro_id)) return apt_repo
[ "def", "_get_apt_repo", "(", "distro_id", ")", ":", "if", "distro_id", "==", "\"ubuntu\"", ":", "apt_repo", "=", "\"ppa:blockstream/satellite\"", "elif", "distro_id", "in", "[", "\"debian\"", ",", "\"raspbian\"", "]", ":", "apt_repo", "=", "(", "\"https://aptly.blockstream.com/\"", "\"satellite/{}/\"", ")", ".", "format", "(", "distro_id", ")", "else", ":", "raise", "ValueError", "(", "\"Unsupported distribution {}\"", ".", "format", "(", "distro_id", ")", ")", "return", "apt_repo" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L51-L60
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
_check_pkg_repo
(distro_id)
return found
Check if Blockstream Satellite's binary package repository is enabled Args: distro_id: Linux distribution ID Returns: (bool) True if the repository is already enabled
Check if Blockstream Satellite's binary package repository is enabled
[ "Check", "if", "Blockstream", "Satellite", "s", "binary", "package", "repository", "is", "enabled" ]
def _check_pkg_repo(distro_id): """Check if Blockstream Satellite's binary package repository is enabled Args: distro_id: Linux distribution ID Returns: (bool) True if the repository is already enabled """ found = False if (which("apt")): apt_repo = _get_apt_repo(distro_id) grep_str = apt_repo.replace("ppa:", "") apt_sources = glob.glob("/etc/apt/sources.list.d/*") apt_sources.append("/etc/apt/sources.list") cmd = ["grep", grep_str] cmd.extend(apt_sources) res = runner.run(cmd, stdout=subprocess.DEVNULL, nocheck=True) found = (res.returncode == 0) elif (which("dnf")): res = runner.run(["dnf", "copr", "list", "--enabled"], root=True, capture_output=True) pkgs = res.stdout.decode().splitlines() found = ("copr.fedorainfracloud.org/blockstream/satellite" in pkgs) elif (which("yum")): yum_sources = glob.glob("/etc/yum.repos.d/*") cmd = ["grep", "blockstream/satellite"] cmd.extend(yum_sources) res = runner.run(cmd, stdout=subprocess.DEVNULL, nocheck=True) found = (res.returncode == 0) else: raise RuntimeError("Could not find a supported package manager") if (found): logger.debug("blockstream/satellite repository already enabled") return found
[ "def", "_check_pkg_repo", "(", "distro_id", ")", ":", "found", "=", "False", "if", "(", "which", "(", "\"apt\"", ")", ")", ":", "apt_repo", "=", "_get_apt_repo", "(", "distro_id", ")", "grep_str", "=", "apt_repo", ".", "replace", "(", "\"ppa:\"", ",", "\"\"", ")", "apt_sources", "=", "glob", ".", "glob", "(", "\"/etc/apt/sources.list.d/*\"", ")", "apt_sources", ".", "append", "(", "\"/etc/apt/sources.list\"", ")", "cmd", "=", "[", "\"grep\"", ",", "grep_str", "]", "cmd", ".", "extend", "(", "apt_sources", ")", "res", "=", "runner", ".", "run", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "DEVNULL", ",", "nocheck", "=", "True", ")", "found", "=", "(", "res", ".", "returncode", "==", "0", ")", "elif", "(", "which", "(", "\"dnf\"", ")", ")", ":", "res", "=", "runner", ".", "run", "(", "[", "\"dnf\"", ",", "\"copr\"", ",", "\"list\"", ",", "\"--enabled\"", "]", ",", "root", "=", "True", ",", "capture_output", "=", "True", ")", "pkgs", "=", "res", ".", "stdout", ".", "decode", "(", ")", ".", "splitlines", "(", ")", "found", "=", "(", "\"copr.fedorainfracloud.org/blockstream/satellite\"", "in", "pkgs", ")", "elif", "(", "which", "(", "\"yum\"", ")", ")", ":", "yum_sources", "=", "glob", ".", "glob", "(", "\"/etc/yum.repos.d/*\"", ")", "cmd", "=", "[", "\"grep\"", ",", "\"blockstream/satellite\"", "]", "cmd", ".", "extend", "(", "yum_sources", ")", "res", "=", "runner", ".", "run", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "DEVNULL", ",", "nocheck", "=", "True", ")", "found", "=", "(", "res", ".", "returncode", "==", "0", ")", "else", ":", "raise", "RuntimeError", "(", "\"Could not find a supported package manager\"", ")", "if", "(", "found", ")", ":", "logger", ".", "debug", "(", "\"blockstream/satellite repository already enabled\"", ")", "return", "found" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L63-L101
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
_enable_pkg_repo
(distro_id, interactive)
Enable Blockstream Satellite's binary package repository Args: distro_id: Linux distribution ID interactive: Interactive mode
Enable Blockstream Satellite's binary package repository
[ "Enable", "Blockstream", "Satellite", "s", "binary", "package", "repository" ]
def _enable_pkg_repo(distro_id, interactive): """Enable Blockstream Satellite's binary package repository Args: distro_id: Linux distribution ID interactive: Interactive mode """ cmds = list() if (which("apt")): apt_repo = _get_apt_repo(distro_id) # On debian, add the apt repository through "add-apt-repository". On # raspbian, where "add-apt-repository" does not work, manually add a # file into /etc/apt/sources.list.d/. if distro_id == "raspbian": release_codename = distro.codename() apt_list_filename = "blockstream-satellite-{}-{}.list".format( distro_id, release_codename) apt_list_file = os.path.join("/etc/apt/sources.list.d/", apt_list_filename) apt_component = "main" apt_file_content = "deb {0} {1} {2}\n# deb-src {0} {1} {2}".format( apt_repo, release_codename, apt_component) # In execution mode, create a temporary file and move it to # /etc/apt/sources.list.d/. With that, only the move command needs # root permissions, whereas the temporary file does not. In dry-run # mode, print an equivalent echo command. if (runner.dry): cmd = [ "echo", "-e", repr(apt_file_content), ">>", apt_list_file ] else: tmp_file = tempfile.NamedTemporaryFile(mode="w", delete=False) with tmp_file as fd: fd.write(apt_file_content) cmd = ["mv", tmp_file.name, apt_list_file] else: cmd = ["add-apt-repository", apt_repo] if (not interactive): cmd.append("-y") cmds.append(cmd) if distro_id in ["debian", "raspbian"]: cmd = [ "apt-key", "adv", "--keyserver", "keyserver.ubuntu.com", "--recv-keys", defs.blocksat_pubkey ] cmds.append(cmd) cmd = ["apt", "update"] if (not interactive): cmd.append("-y") cmds.append(cmd) elif (which("dnf")): cmd = ["dnf", "copr", "enable", "blockstream/satellite"] if (not interactive): cmd.append("-y") cmds.append(cmd) elif (which("yum")): cmd = ["yum", "copr", "enable", "blockstream/satellite"] if (not interactive): cmd.append("-y") cmds.append(cmd) else: raise RuntimeError("Could not find a supported package manager") for cmd in cmds: runner.run(cmd, root=True)
[ "def", "_enable_pkg_repo", "(", "distro_id", ",", "interactive", ")", ":", "cmds", "=", "list", "(", ")", "if", "(", "which", "(", "\"apt\"", ")", ")", ":", "apt_repo", "=", "_get_apt_repo", "(", "distro_id", ")", "# On debian, add the apt repository through \"add-apt-repository\". On", "# raspbian, where \"add-apt-repository\" does not work, manually add a", "# file into /etc/apt/sources.list.d/.", "if", "distro_id", "==", "\"raspbian\"", ":", "release_codename", "=", "distro", ".", "codename", "(", ")", "apt_list_filename", "=", "\"blockstream-satellite-{}-{}.list\"", ".", "format", "(", "distro_id", ",", "release_codename", ")", "apt_list_file", "=", "os", ".", "path", ".", "join", "(", "\"/etc/apt/sources.list.d/\"", ",", "apt_list_filename", ")", "apt_component", "=", "\"main\"", "apt_file_content", "=", "\"deb {0} {1} {2}\\n# deb-src {0} {1} {2}\"", ".", "format", "(", "apt_repo", ",", "release_codename", ",", "apt_component", ")", "# In execution mode, create a temporary file and move it to", "# /etc/apt/sources.list.d/. With that, only the move command needs", "# root permissions, whereas the temporary file does not. In dry-run", "# mode, print an equivalent echo command.", "if", "(", "runner", ".", "dry", ")", ":", "cmd", "=", "[", "\"echo\"", ",", "\"-e\"", ",", "repr", "(", "apt_file_content", ")", ",", "\">>\"", ",", "apt_list_file", "]", "else", ":", "tmp_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "\"w\"", ",", "delete", "=", "False", ")", "with", "tmp_file", "as", "fd", ":", "fd", ".", "write", "(", "apt_file_content", ")", "cmd", "=", "[", "\"mv\"", ",", "tmp_file", ".", "name", ",", "apt_list_file", "]", "else", ":", "cmd", "=", "[", "\"add-apt-repository\"", ",", "apt_repo", "]", "if", "(", "not", "interactive", ")", ":", "cmd", ".", "append", "(", "\"-y\"", ")", "cmds", ".", "append", "(", "cmd", ")", "if", "distro_id", "in", "[", "\"debian\"", ",", "\"raspbian\"", "]", ":", "cmd", "=", "[", "\"apt-key\"", ",", "\"adv\"", ",", "\"--keyserver\"", ",", "\"keyserver.ubuntu.com\"", ",", "\"--recv-keys\"", ",", "defs", ".", "blocksat_pubkey", "]", "cmds", ".", "append", "(", "cmd", ")", "cmd", "=", "[", "\"apt\"", ",", "\"update\"", "]", "if", "(", "not", "interactive", ")", ":", "cmd", ".", "append", "(", "\"-y\"", ")", "cmds", ".", "append", "(", "cmd", ")", "elif", "(", "which", "(", "\"dnf\"", ")", ")", ":", "cmd", "=", "[", "\"dnf\"", ",", "\"copr\"", ",", "\"enable\"", ",", "\"blockstream/satellite\"", "]", "if", "(", "not", "interactive", ")", ":", "cmd", ".", "append", "(", "\"-y\"", ")", "cmds", ".", "append", "(", "cmd", ")", "elif", "(", "which", "(", "\"yum\"", ")", ")", ":", "cmd", "=", "[", "\"yum\"", ",", "\"copr\"", ",", "\"enable\"", ",", "\"blockstream/satellite\"", "]", "if", "(", "not", "interactive", ")", ":", "cmd", ".", "append", "(", "\"-y\"", ")", "cmds", ".", "append", "(", "cmd", ")", "else", ":", "raise", "RuntimeError", "(", "\"Could not find a supported package manager\"", ")", "for", "cmd", "in", "cmds", ":", "runner", ".", "run", "(", "cmd", ",", "root", "=", "True", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L104-L174
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
_update_pkg_repo
(interactive)
Update APT's package index NOTE: this function updates APT only. On dnf/yum, there is no need to run an update manually. The tool (dnf/yum) updates the package index automatically when an install/upgrade command is called.
Update APT's package index
[ "Update", "APT", "s", "package", "index" ]
def _update_pkg_repo(interactive): """Update APT's package index NOTE: this function updates APT only. On dnf/yum, there is no need to run an update manually. The tool (dnf/yum) updates the package index automatically when an install/upgrade command is called. """ if (not which("apt")): return cmd = ["apt", "update"] if (not interactive): cmd.append("-y") runner.run(cmd, root=True)
[ "def", "_update_pkg_repo", "(", "interactive", ")", ":", "if", "(", "not", "which", "(", "\"apt\"", ")", ")", ":", "return", "cmd", "=", "[", "\"apt\"", ",", "\"update\"", "]", "if", "(", "not", "interactive", ")", ":", "cmd", ".", "append", "(", "\"-y\"", ")", "runner", ".", "run", "(", "cmd", ",", "root", "=", "True", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L177-L193
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
_install_packages
(apt_list, dnf_list, yum_list, interactive=True, update=False)
Install binary packages Args: apt_list : List of package names for installation via apt dnf_list : List of package names for installation via dnf dnf_list : List of package names for installation via yum interactive : Whether to run an interactive install (w/ user prompting) update : Whether to update pre-installed packages instead
Install binary packages
[ "Install", "binary", "packages" ]
def _install_packages(apt_list, dnf_list, yum_list, interactive=True, update=False): """Install binary packages Args: apt_list : List of package names for installation via apt dnf_list : List of package names for installation via dnf dnf_list : List of package names for installation via yum interactive : Whether to run an interactive install (w/ user prompting) update : Whether to update pre-installed packages instead """ if (which("apt")): manager = "apt" cmd = ["apt-get", "install"] if (update): cmd.append("--only-upgrade") cmd.extend(apt_list) elif (which("dnf")): manager = "dnf" if (update): cmd = ["dnf", "upgrade"] else: cmd = ["dnf", "install"] cmd.extend(dnf_list) elif (which("yum")): manager = "yum" if (update): cmd = ["yum", "upgrade"] else: cmd = ["yum", "install"] cmd.extend(yum_list) else: raise RuntimeError("Could not find a supported package manager") env = None if (not interactive): cmd.append("-y") if (manager == "apt"): env = os.environ.copy() env["DEBIAN_FRONTEND"] = "noninteractive" runner.run(cmd, root=True, env=env)
[ "def", "_install_packages", "(", "apt_list", ",", "dnf_list", ",", "yum_list", ",", "interactive", "=", "True", ",", "update", "=", "False", ")", ":", "if", "(", "which", "(", "\"apt\"", ")", ")", ":", "manager", "=", "\"apt\"", "cmd", "=", "[", "\"apt-get\"", ",", "\"install\"", "]", "if", "(", "update", ")", ":", "cmd", ".", "append", "(", "\"--only-upgrade\"", ")", "cmd", ".", "extend", "(", "apt_list", ")", "elif", "(", "which", "(", "\"dnf\"", ")", ")", ":", "manager", "=", "\"dnf\"", "if", "(", "update", ")", ":", "cmd", "=", "[", "\"dnf\"", ",", "\"upgrade\"", "]", "else", ":", "cmd", "=", "[", "\"dnf\"", ",", "\"install\"", "]", "cmd", ".", "extend", "(", "dnf_list", ")", "elif", "(", "which", "(", "\"yum\"", ")", ")", ":", "manager", "=", "\"yum\"", "if", "(", "update", ")", ":", "cmd", "=", "[", "\"yum\"", ",", "\"upgrade\"", "]", "else", ":", "cmd", "=", "[", "\"yum\"", ",", "\"install\"", "]", "cmd", ".", "extend", "(", "yum_list", ")", "else", ":", "raise", "RuntimeError", "(", "\"Could not find a supported package manager\"", ")", "env", "=", "None", "if", "(", "not", "interactive", ")", ":", "cmd", ".", "append", "(", "\"-y\"", ")", "if", "(", "manager", "==", "\"apt\"", ")", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "env", "[", "\"DEBIAN_FRONTEND\"", "]", "=", "\"noninteractive\"", "runner", ".", "run", "(", "cmd", ",", "root", "=", "True", ",", "env", "=", "env", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L196-L242
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
_install_common
(interactive=True, update=False, btc=False)
Install dependencies that are common to all setups
Install dependencies that are common to all setups
[ "Install", "dependencies", "that", "are", "common", "to", "all", "setups" ]
def _install_common(interactive=True, update=False, btc=False): """Install dependencies that are common to all setups""" util.print_header("Installing Common Dependencies") apt_pkg_list = ["software-properties-common"] dnf_pkg_list = ["dnf-plugins-core"] yum_pkg_list = ["yum-plugin-copr"] # "gnupg" is installed as a dependency of "software-properties-common" on # Ubuntu. In contrast, it is not a dependency on Debian. Hence, add it # explicitly to the list. Add also "dirmngr", which may not be # automatically installed with gnupg (it is only automatically installed # from buster onwards). Lastly, add "apt-transport-https" to fetch debian # and raspbian packages from Aptly using HTTPS. distro_id = distro.id() if distro_id in ["debian", "raspbian"]: apt_pkg_list.extend(["gnupg", "dirmngr", "apt-transport-https"]) if distro_id == "centos": dnf_pkg_list.append("epel-release") yum_pkg_list.append("epel-release") _install_packages(apt_pkg_list, dnf_pkg_list, yum_pkg_list, interactive, update) # Enable our binary package repository if runner.dry or (not _check_pkg_repo(distro_id)): _enable_pkg_repo(distro_id, interactive) # Install bitcoin-satellite if (btc): apt_pkg_list = [ "bitcoin-satellite", "bitcoin-satellite-qt", "bitcoin-satellite-tx" ] dnf_pkg_list = ["bitcoin-satellite", "bitcoin-satellite-qt"] yum_pkg_list = ["bitcoin-satellite", "bitcoin-satellite-qt"] if (which("dnf")): # dnf matches partial package names, and so it seems that when # bitcoin-satellite and bitcoin-satellite-qt are installed in one # go, only the latter gets installed. The former is matched to # bitcoin-satellite-qt and assumed as installed. Hence, as a # workaround, install the two packages separately. for pkg in dnf_pkg_list: _install_packages(apt_pkg_list, [pkg], [pkg], interactive, update) else: _install_packages(apt_pkg_list, [], yum_pkg_list, interactive, update)
[ "def", "_install_common", "(", "interactive", "=", "True", ",", "update", "=", "False", ",", "btc", "=", "False", ")", ":", "util", ".", "print_header", "(", "\"Installing Common Dependencies\"", ")", "apt_pkg_list", "=", "[", "\"software-properties-common\"", "]", "dnf_pkg_list", "=", "[", "\"dnf-plugins-core\"", "]", "yum_pkg_list", "=", "[", "\"yum-plugin-copr\"", "]", "# \"gnupg\" is installed as a dependency of \"software-properties-common\" on", "# Ubuntu. In contrast, it is not a dependency on Debian. Hence, add it", "# explicitly to the list. Add also \"dirmngr\", which may not be", "# automatically installed with gnupg (it is only automatically installed", "# from buster onwards). Lastly, add \"apt-transport-https\" to fetch debian", "# and raspbian packages from Aptly using HTTPS.", "distro_id", "=", "distro", ".", "id", "(", ")", "if", "distro_id", "in", "[", "\"debian\"", ",", "\"raspbian\"", "]", ":", "apt_pkg_list", ".", "extend", "(", "[", "\"gnupg\"", ",", "\"dirmngr\"", ",", "\"apt-transport-https\"", "]", ")", "if", "distro_id", "==", "\"centos\"", ":", "dnf_pkg_list", ".", "append", "(", "\"epel-release\"", ")", "yum_pkg_list", ".", "append", "(", "\"epel-release\"", ")", "_install_packages", "(", "apt_pkg_list", ",", "dnf_pkg_list", ",", "yum_pkg_list", ",", "interactive", ",", "update", ")", "# Enable our binary package repository", "if", "runner", ".", "dry", "or", "(", "not", "_check_pkg_repo", "(", "distro_id", ")", ")", ":", "_enable_pkg_repo", "(", "distro_id", ",", "interactive", ")", "# Install bitcoin-satellite", "if", "(", "btc", ")", ":", "apt_pkg_list", "=", "[", "\"bitcoin-satellite\"", ",", "\"bitcoin-satellite-qt\"", ",", "\"bitcoin-satellite-tx\"", "]", "dnf_pkg_list", "=", "[", "\"bitcoin-satellite\"", ",", "\"bitcoin-satellite-qt\"", "]", "yum_pkg_list", "=", "[", "\"bitcoin-satellite\"", ",", "\"bitcoin-satellite-qt\"", "]", "if", "(", "which", "(", "\"dnf\"", ")", ")", ":", "# dnf matches partial package names, and so it seems that when", "# bitcoin-satellite and bitcoin-satellite-qt are installed in one", "# go, only the latter gets installed. The former is matched to", "# bitcoin-satellite-qt and assumed as installed. Hence, as a", "# workaround, install the two packages separately.", "for", "pkg", "in", "dnf_pkg_list", ":", "_install_packages", "(", "apt_pkg_list", ",", "[", "pkg", "]", ",", "[", "pkg", "]", ",", "interactive", ",", "update", ")", "else", ":", "_install_packages", "(", "apt_pkg_list", ",", "[", "]", ",", "yum_pkg_list", ",", "interactive", ",", "update", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L245-L292
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
_install_specific
(target, interactive=True, update=False)
Install setup-specific dependencies
Install setup-specific dependencies
[ "Install", "setup", "-", "specific", "dependencies" ]
def _install_specific(target, interactive=True, update=False): """Install setup-specific dependencies""" key = next(key for key, val in target_map.items() if val == target) pkg_map = { 'sdr': { 'apt': ["gqrx-sdr", "rtl-sdr", "leandvb", "tsduck"], 'dnf': ["gqrx", "rtl-sdr", "leandvb", "tsduck"], 'yum': ["rtl-sdr", "leandvb", "tsduck"] }, 'usb': { 'apt': ["iproute2", "iptables", "dvb-apps", "dvb-tools"], 'dnf': ["iproute", "iptables", "dvb-apps", "v4l-utils"], 'yum': ["iproute", "iptables", "dvb-apps", "v4l-utils"] }, 'standalone': { 'apt': ["iproute2", "iptables"], 'dnf': ["iproute", "iptables"], 'yum': ["iproute", "iptables"] }, 'sat-ip': { 'apt': ["iproute2", "tsduck"], 'dnf': ["iproute", "tsduck"], 'yum': ["iproute", "tsduck"] } } # NOTE: # - leandvb and tsduck come from our repository. Also, note gqrx is not # available on CentOS (hence not included on the yum list). # - In the USB setup, the only package from our repository is dvb-apps in # the specific case of dnf (RPM) installation, given that dvb-apps is not # available on the latest mainstream fedora repositories. util.print_header("Installing {} Receiver Dependencies".format(target)) _install_packages(pkg_map[key]['apt'], pkg_map[key]['dnf'], pkg_map[key]['yum'], interactive, update)
[ "def", "_install_specific", "(", "target", ",", "interactive", "=", "True", ",", "update", "=", "False", ")", ":", "key", "=", "next", "(", "key", "for", "key", ",", "val", "in", "target_map", ".", "items", "(", ")", "if", "val", "==", "target", ")", "pkg_map", "=", "{", "'sdr'", ":", "{", "'apt'", ":", "[", "\"gqrx-sdr\"", ",", "\"rtl-sdr\"", ",", "\"leandvb\"", ",", "\"tsduck\"", "]", ",", "'dnf'", ":", "[", "\"gqrx\"", ",", "\"rtl-sdr\"", ",", "\"leandvb\"", ",", "\"tsduck\"", "]", ",", "'yum'", ":", "[", "\"rtl-sdr\"", ",", "\"leandvb\"", ",", "\"tsduck\"", "]", "}", ",", "'usb'", ":", "{", "'apt'", ":", "[", "\"iproute2\"", ",", "\"iptables\"", ",", "\"dvb-apps\"", ",", "\"dvb-tools\"", "]", ",", "'dnf'", ":", "[", "\"iproute\"", ",", "\"iptables\"", ",", "\"dvb-apps\"", ",", "\"v4l-utils\"", "]", ",", "'yum'", ":", "[", "\"iproute\"", ",", "\"iptables\"", ",", "\"dvb-apps\"", ",", "\"v4l-utils\"", "]", "}", ",", "'standalone'", ":", "{", "'apt'", ":", "[", "\"iproute2\"", ",", "\"iptables\"", "]", ",", "'dnf'", ":", "[", "\"iproute\"", ",", "\"iptables\"", "]", ",", "'yum'", ":", "[", "\"iproute\"", ",", "\"iptables\"", "]", "}", ",", "'sat-ip'", ":", "{", "'apt'", ":", "[", "\"iproute2\"", ",", "\"tsduck\"", "]", ",", "'dnf'", ":", "[", "\"iproute\"", ",", "\"tsduck\"", "]", ",", "'yum'", ":", "[", "\"iproute\"", ",", "\"tsduck\"", "]", "}", "}", "# NOTE:", "# - leandvb and tsduck come from our repository. Also, note gqrx is not", "# available on CentOS (hence not included on the yum list).", "# - In the USB setup, the only package from our repository is dvb-apps in", "# the specific case of dnf (RPM) installation, given that dvb-apps is not", "# available on the latest mainstream fedora repositories.", "util", ".", "print_header", "(", "\"Installing {} Receiver Dependencies\"", ".", "format", "(", "target", ")", ")", "_install_packages", "(", "pkg_map", "[", "key", "]", "[", "'apt'", "]", ",", "pkg_map", "[", "key", "]", "[", "'dnf'", "]", ",", "pkg_map", "[", "key", "]", "[", "'yum'", "]", ",", "interactive", ",", "update", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L295-L329
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
_print_help
(args)
Re-create argparse's help menu
Re-create argparse's help menu
[ "Re", "-", "create", "argparse", "s", "help", "menu" ]
def _print_help(args): """Re-create argparse's help menu""" parser = ArgumentParser() subparsers = parser.add_subparsers(title='', help='') parser = subparser(subparsers) print(parser.format_help())
[ "def", "_print_help", "(", "args", ")", ":", "parser", "=", "ArgumentParser", "(", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", "title", "=", "''", ",", "help", "=", "''", ")", "parser", "=", "subparser", "(", "subparsers", ")", "print", "(", "parser", ".", "format_help", "(", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L332-L337
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
subparser
(subparsers)
return p
Parser for install command
Parser for install command
[ "Parser", "for", "install", "command" ]
def subparser(subparsers): """Parser for install command""" p = subparsers.add_parser('dependencies', aliases=['deps'], description="Manage dependencies", help='Manage dependencies', formatter_class=ArgumentDefaultsHelpFormatter) p.set_defaults(func=_print_help) p.add_argument("-y", "--yes", action='store_true', default=False, help="Non-interactive mode. Answers \"yes\" automatically \ to binary package installation prompts") p.add_argument("--dry-run", action='store_true', default=False, help="Print all commands but do not execute them") subsubp = p.add_subparsers(title='subcommands', help='Target sub-command') p1 = subsubp.add_parser('install', description="Install software dependencies", help='Install software dependencies') p1.add_argument("--target", choices=list(target_map.keys()), default=None, help="Target setup type for installation of dependencies") p1.add_argument("--btc", action='store_true', default=False, help="Install bitcoin-satellite") p1.set_defaults(func=run, update=False) p2 = subsubp.add_parser('update', aliases=['upgrade'], description="Update software dependencies", help='Update software dependencies') p2.add_argument("--target", choices=list(target_map.keys()), default=None, help="Target setup type for the update of dependencies") p2.add_argument("--btc", action='store_true', default=False, help="Update bitcoin-satellite") p2.set_defaults(func=run, update=True) p3 = subsubp.add_parser('tbs-drivers', description="Install TBS USB receiver drivers", help='Install TBS USB receiver drivers') p3.set_defaults(func=drivers) return p
[ "def", "subparser", "(", "subparsers", ")", ":", "p", "=", "subparsers", ".", "add_parser", "(", "'dependencies'", ",", "aliases", "=", "[", "'deps'", "]", ",", "description", "=", "\"Manage dependencies\"", ",", "help", "=", "'Manage dependencies'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "p", ".", "set_defaults", "(", "func", "=", "_print_help", ")", "p", ".", "add_argument", "(", "\"-y\"", ",", "\"--yes\"", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "\"Non-interactive mode. Answers \\\"yes\\\" automatically \\\n to binary package installation prompts\"", ")", "p", ".", "add_argument", "(", "\"--dry-run\"", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "\"Print all commands but do not execute them\"", ")", "subsubp", "=", "p", ".", "add_subparsers", "(", "title", "=", "'subcommands'", ",", "help", "=", "'Target sub-command'", ")", "p1", "=", "subsubp", ".", "add_parser", "(", "'install'", ",", "description", "=", "\"Install software dependencies\"", ",", "help", "=", "'Install software dependencies'", ")", "p1", ".", "add_argument", "(", "\"--target\"", ",", "choices", "=", "list", "(", "target_map", ".", "keys", "(", ")", ")", ",", "default", "=", "None", ",", "help", "=", "\"Target setup type for installation of dependencies\"", ")", "p1", ".", "add_argument", "(", "\"--btc\"", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "\"Install bitcoin-satellite\"", ")", "p1", ".", "set_defaults", "(", "func", "=", "run", ",", "update", "=", "False", ")", "p2", "=", "subsubp", ".", "add_parser", "(", "'update'", ",", "aliases", "=", "[", "'upgrade'", "]", ",", "description", "=", "\"Update software dependencies\"", ",", "help", "=", "'Update software dependencies'", ")", "p2", ".", "add_argument", "(", "\"--target\"", ",", "choices", "=", "list", "(", "target_map", ".", "keys", "(", ")", ")", ",", "default", "=", "None", ",", "help", "=", "\"Target setup type for the update of dependencies\"", ")", "p2", ".", "add_argument", "(", "\"--btc\"", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "\"Update bitcoin-satellite\"", ")", "p2", ".", "set_defaults", "(", "func", "=", "run", ",", "update", "=", "True", ")", "p3", "=", "subsubp", ".", "add_parser", "(", "'tbs-drivers'", ",", "description", "=", "\"Install TBS USB receiver drivers\"", ",", "help", "=", "'Install TBS USB receiver drivers'", ")", "p3", ".", "set_defaults", "(", "func", "=", "drivers", ")", "return", "p" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L340-L394
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
run
(args)
Run installations
Run installations
[ "Run", "installations" ]
def run(args): """Run installations""" # Interactive installation? I.e., requires user to press "y/n" interactive = (not args.yes) # Configure the subprocess runner runner.set_dry(args.dry_run) if (args.target is not None): target = target_map[args.target] else: info = config.read_cfg_file(args.cfg, args.cfg_dir) if (info is None): return target = info['setup']['type'] _check_distro(target) if (os.geteuid() != 0 and not args.dry_run): util.fill_print("Some commands require root access and may prompt " "for a password") if (args.dry_run): util.print_header("Dry Run Mode") # Update package index _update_pkg_repo(interactive) # Common dependencies (regardless of setup) _install_common(interactive=interactive, update=args.update, btc=args.btc) # Install setup-specific dependencies _install_specific(target, interactive=interactive, update=args.update)
[ "def", "run", "(", "args", ")", ":", "# Interactive installation? I.e., requires user to press \"y/n\"", "interactive", "=", "(", "not", "args", ".", "yes", ")", "# Configure the subprocess runner", "runner", ".", "set_dry", "(", "args", ".", "dry_run", ")", "if", "(", "args", ".", "target", "is", "not", "None", ")", ":", "target", "=", "target_map", "[", "args", ".", "target", "]", "else", ":", "info", "=", "config", ".", "read_cfg_file", "(", "args", ".", "cfg", ",", "args", ".", "cfg_dir", ")", "if", "(", "info", "is", "None", ")", ":", "return", "target", "=", "info", "[", "'setup'", "]", "[", "'type'", "]", "_check_distro", "(", "target", ")", "if", "(", "os", ".", "geteuid", "(", ")", "!=", "0", "and", "not", "args", ".", "dry_run", ")", ":", "util", ".", "fill_print", "(", "\"Some commands require root access and may prompt \"", "\"for a password\"", ")", "if", "(", "args", ".", "dry_run", ")", ":", "util", ".", "print_header", "(", "\"Dry Run Mode\"", ")", "# Update package index", "_update_pkg_repo", "(", "interactive", ")", "# Common dependencies (regardless of setup)", "_install_common", "(", "interactive", "=", "interactive", ",", "update", "=", "args", ".", "update", ",", "btc", "=", "args", ".", "btc", ")", "# Install setup-specific dependencies", "_install_specific", "(", "target", ",", "interactive", "=", "interactive", ",", "update", "=", "args", ".", "update", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L397-L430
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/dependencies.py
python
check_apps
(apps)
return True
Check if required apps are installed
Check if required apps are installed
[ "Check", "if", "required", "apps", "are", "installed" ]
def check_apps(apps): """Check if required apps are installed""" for app in apps: if (not which(app)): logging.error("Couldn't find {}. Is it installed?".format(app)) print("\nTo install software dependencies, run:") print(""" blocksat-cli deps install """) return False # All apps are installed return True
[ "def", "check_apps", "(", "apps", ")", ":", "for", "app", "in", "apps", ":", "if", "(", "not", "which", "(", "app", ")", ")", ":", "logging", ".", "error", "(", "\"Couldn't find {}. Is it installed?\"", ".", "format", "(", "app", ")", ")", "print", "(", "\"\\nTo install software dependencies, run:\"", ")", "print", "(", "\"\"\"\n blocksat-cli deps install\n \"\"\"", ")", "return", "False", "# All apps are installed", "return", "True" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/dependencies.py#L597-L608
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/verify_deps_instal.py
python
TestDependencies.gen_args
(self, target, btc=False)
return parser.parse_args(args)
Mock command-line argument
Mock command-line argument
[ "Mock", "command", "-", "line", "argument" ]
def gen_args(self, target, btc=False): """Mock command-line argument""" logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() dependencies.subparser(subparsers) args = ["deps", "-y", "install", "--target", target] if (btc): args.append("--btc") return parser.parse_args(args)
[ "def", "gen_args", "(", "self", ",", "target", ",", "btc", "=", "False", ")", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", ")", "dependencies", ".", "subparser", "(", "subparsers", ")", "args", "=", "[", "\"deps\"", ",", "\"-y\"", ",", "\"install\"", ",", "\"--target\"", ",", "target", "]", "if", "(", "btc", ")", ":", "args", ".", "append", "(", "\"--btc\"", ")", "return", "parser", ".", "parse_args", "(", "args", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/verify_deps_instal.py#L8-L17
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/verify_deps_instal.py
python
TestDependencies.test_usb_deps
(self)
Test the installation of USB receiver dependencies
Test the installation of USB receiver dependencies
[ "Test", "the", "installation", "of", "USB", "receiver", "dependencies" ]
def test_usb_deps(self): """Test the installation of USB receiver dependencies""" args = self.gen_args("usb") dependencies.run(args) expected_apps = [ "dvbnet", "dvb-fe-tool", "dvbv5-zap", "ip", "iptables" ] self.assertTrue(dependencies.check_apps(expected_apps))
[ "def", "test_usb_deps", "(", "self", ")", ":", "args", "=", "self", ".", "gen_args", "(", "\"usb\"", ")", "dependencies", ".", "run", "(", "args", ")", "expected_apps", "=", "[", "\"dvbnet\"", ",", "\"dvb-fe-tool\"", ",", "\"dvbv5-zap\"", ",", "\"ip\"", ",", "\"iptables\"", "]", "self", ".", "assertTrue", "(", "dependencies", ".", "check_apps", "(", "expected_apps", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/verify_deps_instal.py#L19-L26
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/verify_deps_instal.py
python
TestDependencies.test_sdr_deps
(self)
Test the installation of SDR receiver dependencies
Test the installation of SDR receiver dependencies
[ "Test", "the", "installation", "of", "SDR", "receiver", "dependencies" ]
def test_sdr_deps(self): """Test the installation of SDR receiver dependencies""" args = self.gen_args("sdr") dependencies.run(args) expected_apps = ["rtl_sdr", "leandvb", "ldpc_tool", "tsp"] self.assertTrue(dependencies.check_apps(expected_apps))
[ "def", "test_sdr_deps", "(", "self", ")", ":", "args", "=", "self", ".", "gen_args", "(", "\"sdr\"", ")", "dependencies", ".", "run", "(", "args", ")", "expected_apps", "=", "[", "\"rtl_sdr\"", ",", "\"leandvb\"", ",", "\"ldpc_tool\"", ",", "\"tsp\"", "]", "self", ".", "assertTrue", "(", "dependencies", ".", "check_apps", "(", "expected_apps", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/verify_deps_instal.py#L28-L33
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/verify_deps_instal.py
python
TestDependencies.test_standalone_deps
(self)
Test the installation of standalone receiver dependencies
Test the installation of standalone receiver dependencies
[ "Test", "the", "installation", "of", "standalone", "receiver", "dependencies" ]
def test_standalone_deps(self): """Test the installation of standalone receiver dependencies""" args = self.gen_args("standalone") dependencies.run(args) expected_apps = ["ip", "iptables"] self.assertTrue(dependencies.check_apps(expected_apps))
[ "def", "test_standalone_deps", "(", "self", ")", ":", "args", "=", "self", ".", "gen_args", "(", "\"standalone\"", ")", "dependencies", ".", "run", "(", "args", ")", "expected_apps", "=", "[", "\"ip\"", ",", "\"iptables\"", "]", "self", ".", "assertTrue", "(", "dependencies", ".", "check_apps", "(", "expected_apps", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/verify_deps_instal.py#L35-L40
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/verify_deps_instal.py
python
TestDependencies.test_sat_ip_deps
(self)
Test the installation of sat-ip receiver dependencies
Test the installation of sat-ip receiver dependencies
[ "Test", "the", "installation", "of", "sat", "-", "ip", "receiver", "dependencies" ]
def test_sat_ip_deps(self): """Test the installation of sat-ip receiver dependencies""" args = self.gen_args("sat-ip") dependencies.run(args) expected_apps = ["tsp"] self.assertTrue(dependencies.check_apps(expected_apps))
[ "def", "test_sat_ip_deps", "(", "self", ")", ":", "args", "=", "self", ".", "gen_args", "(", "\"sat-ip\"", ")", "dependencies", ".", "run", "(", "args", ")", "expected_apps", "=", "[", "\"tsp\"", "]", "self", ".", "assertTrue", "(", "dependencies", ".", "check_apps", "(", "expected_apps", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/verify_deps_instal.py#L42-L47
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/verify_deps_instal.py
python
TestDependencies.test_bitcoin_satellite
(self)
Test the installation of bitcoin-satellite
Test the installation of bitcoin-satellite
[ "Test", "the", "installation", "of", "bitcoin", "-", "satellite" ]
def test_bitcoin_satellite(self): """Test the installation of bitcoin-satellite""" args = self.gen_args("standalone", btc=True) dependencies.run(args) expected_apps = ["bitcoind", "bitcoin-cli", "bitcoin-tx", "bitcoin-qt"] self.assertTrue(dependencies.check_apps(expected_apps))
[ "def", "test_bitcoin_satellite", "(", "self", ")", ":", "args", "=", "self", ".", "gen_args", "(", "\"standalone\"", ",", "btc", "=", "True", ")", "dependencies", ".", "run", "(", "args", ")", "expected_apps", "=", "[", "\"bitcoind\"", ",", "\"bitcoin-cli\"", ",", "\"bitcoin-tx\"", ",", "\"bitcoin-qt\"", "]", "self", ".", "assertTrue", "(", "dependencies", ".", "check_apps", "(", "expected_apps", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/verify_deps_instal.py#L49-L54
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/bitcoin.py
python
_udpmulticast
(dev, src_addr, dst_addr=defs.btc_dst_addr, trusted="1", label="")
return dev + "," + dst_addr + "," + src_addr + "," + trusted + "," + label
Return the udpmulticast configuration line for bitcoin.conf
Return the udpmulticast configuration line for bitcoin.conf
[ "Return", "the", "udpmulticast", "configuration", "line", "for", "bitcoin", ".", "conf" ]
def _udpmulticast(dev, src_addr, dst_addr=defs.btc_dst_addr, trusted="1", label=""): """Return the udpmulticast configuration line for bitcoin.conf""" return dev + "," + dst_addr + "," + src_addr + "," + trusted + "," + label
[ "def", "_udpmulticast", "(", "dev", ",", "src_addr", ",", "dst_addr", "=", "defs", ".", "btc_dst_addr", ",", "trusted", "=", "\"1\"", ",", "label", "=", "\"\"", ")", ":", "return", "dev", "+", "\",\"", "+", "dst_addr", "+", "\",\"", "+", "src_addr", "+", "\",\"", "+", "trusted", "+", "\",\"", "+", "label" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/bitcoin.py#L54-L60
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/bitcoin.py
python
_gen_cfgs
(info, interface)
return cfg
Generate configurations
Generate configurations
[ "Generate", "configurations" ]
def _gen_cfgs(info, interface): """Generate configurations""" cfg = Cfg() cfg.add_opt("debug", "udpnet") cfg.add_opt("debug", "udpmulticast") cfg.add_opt("udpmulticastloginterval", "600") if (info['setup']['type'] == defs.sdr_setup_type): src_addr = "127.0.0.1" label = "blocksat-sdr" elif (info['setup']['type'] == defs.linux_usb_setup_type): src_addr = info['sat']['ip'] label = "blocksat-tbs" elif (info['setup']['type'] == defs.standalone_setup_type): src_addr = info['sat']['ip'] label = "blocksat-s400" elif (info['setup']['type'] == defs.sat_ip_setup_type): src_addr = "127.0.0.1" label = "blocksat-sat-ip" else: raise ValueError("Unknown setup type") cfg.add_opt("udpmulticast", _udpmulticast(dev=interface, src_addr=src_addr, label=label)) return cfg
[ "def", "_gen_cfgs", "(", "info", ",", "interface", ")", ":", "cfg", "=", "Cfg", "(", ")", "cfg", ".", "add_opt", "(", "\"debug\"", ",", "\"udpnet\"", ")", "cfg", ".", "add_opt", "(", "\"debug\"", ",", "\"udpmulticast\"", ")", "cfg", ".", "add_opt", "(", "\"udpmulticastloginterval\"", ",", "\"600\"", ")", "if", "(", "info", "[", "'setup'", "]", "[", "'type'", "]", "==", "defs", ".", "sdr_setup_type", ")", ":", "src_addr", "=", "\"127.0.0.1\"", "label", "=", "\"blocksat-sdr\"", "elif", "(", "info", "[", "'setup'", "]", "[", "'type'", "]", "==", "defs", ".", "linux_usb_setup_type", ")", ":", "src_addr", "=", "info", "[", "'sat'", "]", "[", "'ip'", "]", "label", "=", "\"blocksat-tbs\"", "elif", "(", "info", "[", "'setup'", "]", "[", "'type'", "]", "==", "defs", ".", "standalone_setup_type", ")", ":", "src_addr", "=", "info", "[", "'sat'", "]", "[", "'ip'", "]", "label", "=", "\"blocksat-s400\"", "elif", "(", "info", "[", "'setup'", "]", "[", "'type'", "]", "==", "defs", ".", "sat_ip_setup_type", ")", ":", "src_addr", "=", "\"127.0.0.1\"", "label", "=", "\"blocksat-sat-ip\"", "else", ":", "raise", "ValueError", "(", "\"Unknown setup type\"", ")", "cfg", ".", "add_opt", "(", "\"udpmulticast\"", ",", "_udpmulticast", "(", "dev", "=", "interface", ",", "src_addr", "=", "src_addr", ",", "label", "=", "label", ")", ")", "return", "cfg" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/bitcoin.py#L63-L88
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/bitcoin.py
python
subparser
(subparsers)
return subparser
Argument parser of bitcoin-conf command
Argument parser of bitcoin-conf command
[ "Argument", "parser", "of", "bitcoin", "-", "conf", "command" ]
def subparser(subparsers): """Argument parser of bitcoin-conf command""" p = subparsers.add_parser( 'bitcoin-conf', aliases=['btc'], description="Generate Bitcoin configuration file", help='Generate Bitcoin configuration file', formatter_class=ArgumentDefaultsHelpFormatter) p.add_argument('-d', '--datadir', default=None, help='Path to the data directory where the generated ' 'bitcoin.conf will be saved') p.add_argument('--stdout', action='store_true', default=False, help='Print the generated bitcoin.conf file to the ' 'standard output instead of saving the file') p.add_argument('--concat', action='store_true', default=False, help='Concatenate configurations to pre-existing ' 'bitcoin.conf file') p.set_defaults(func=configure) return subparser
[ "def", "subparser", "(", "subparsers", ")", ":", "p", "=", "subparsers", ".", "add_parser", "(", "'bitcoin-conf'", ",", "aliases", "=", "[", "'btc'", "]", ",", "description", "=", "\"Generate Bitcoin configuration file\"", ",", "help", "=", "'Generate Bitcoin configuration file'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "p", ".", "add_argument", "(", "'-d'", ",", "'--datadir'", ",", "default", "=", "None", ",", "help", "=", "'Path to the data directory where the generated '", "'bitcoin.conf will be saved'", ")", "p", ".", "add_argument", "(", "'--stdout'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Print the generated bitcoin.conf file to the '", "'standard output instead of saving the file'", ")", "p", ".", "add_argument", "(", "'--concat'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Concatenate configurations to pre-existing '", "'bitcoin.conf file'", ")", "p", ".", "set_defaults", "(", "func", "=", "configure", ")", "return", "subparser" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/bitcoin.py#L91-L116
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/bitcoin.py
python
configure
(args)
Generate bitcoin.conf configuration
Generate bitcoin.conf configuration
[ "Generate", "bitcoin", ".", "conf", "configuration" ]
def configure(args): """Generate bitcoin.conf configuration""" info = config.read_cfg_file(args.cfg, args.cfg_dir) if (info is None): return if (not args.stdout): util.print_header("Bitcoin Conf Generator") if args.datadir is None: home = os.path.expanduser("~") path = os.path.join(home, ".bitcoin") else: path = os.path.abspath(args.datadir) conf_file = "bitcoin.conf" abs_path = os.path.join(path, conf_file) # Network interface ifname = config.get_net_if(info) # Generate configuration object cfg = _gen_cfgs(info, ifname) # Load and concatenate pre-existing configurations if args.concat and os.path.exists(abs_path): with open(abs_path, "r") as fd: prev_cfg_text = fd.read() cfg.load_text_cfg(prev_cfg_text) # Export configurations to text format cfg_text = cfg.text() # Print configurations to stdout and don't save them if (args.stdout): print(cfg_text) return # Proceed to saving configurations print("Save {} at {}".format(conf_file, path)) if (not util.ask_yes_or_no("Proceed?")): print("Aborted") return if not os.path.exists(path): os.makedirs(path) if os.path.exists(abs_path) and not args.concat: if (not util.ask_yes_or_no("File already exists. Overwrite?")): print("Aborted") return with open(abs_path, "w") as fd: fd.write(cfg_text) print("Saved") if (info['setup']['type'] == defs.linux_usb_setup_type): print() util.fill_print( "NOTE: {} was configured assuming the dvbnet interface is " "named {}. You can check if this is the case after launching the " "receiver by running:".format(conf_file, ifname)) print(" ip link show | grep dvb\n") util.fill_print("If the dvb interfaces are numbered differently, " "please update {} accordingly.".format(conf_file)) elif (info['setup']['type'] == defs.standalone_setup_type): print("\n" + textwrap.fill( ("NOTE: {0} was configured assuming the Novra S400 receiver will " "be connected to interface {1}. If this is not the case anymore, " "please update {0} accordingly.").format(conf_file, ifname)))
[ "def", "configure", "(", "args", ")", ":", "info", "=", "config", ".", "read_cfg_file", "(", "args", ".", "cfg", ",", "args", ".", "cfg_dir", ")", "if", "(", "info", "is", "None", ")", ":", "return", "if", "(", "not", "args", ".", "stdout", ")", ":", "util", ".", "print_header", "(", "\"Bitcoin Conf Generator\"", ")", "if", "args", ".", "datadir", "is", "None", ":", "home", "=", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "path", "=", "os", ".", "path", ".", "join", "(", "home", ",", "\".bitcoin\"", ")", "else", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "args", ".", "datadir", ")", "conf_file", "=", "\"bitcoin.conf\"", "abs_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "conf_file", ")", "# Network interface", "ifname", "=", "config", ".", "get_net_if", "(", "info", ")", "# Generate configuration object", "cfg", "=", "_gen_cfgs", "(", "info", ",", "ifname", ")", "# Load and concatenate pre-existing configurations", "if", "args", ".", "concat", "and", "os", ".", "path", ".", "exists", "(", "abs_path", ")", ":", "with", "open", "(", "abs_path", ",", "\"r\"", ")", "as", "fd", ":", "prev_cfg_text", "=", "fd", ".", "read", "(", ")", "cfg", ".", "load_text_cfg", "(", "prev_cfg_text", ")", "# Export configurations to text format", "cfg_text", "=", "cfg", ".", "text", "(", ")", "# Print configurations to stdout and don't save them", "if", "(", "args", ".", "stdout", ")", ":", "print", "(", "cfg_text", ")", "return", "# Proceed to saving configurations", "print", "(", "\"Save {} at {}\"", ".", "format", "(", "conf_file", ",", "path", ")", ")", "if", "(", "not", "util", ".", "ask_yes_or_no", "(", "\"Proceed?\"", ")", ")", ":", "print", "(", "\"Aborted\"", ")", "return", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "abs_path", ")", "and", "not", "args", ".", "concat", ":", "if", "(", "not", "util", ".", "ask_yes_or_no", "(", "\"File already exists. Overwrite?\"", ")", ")", ":", "print", "(", "\"Aborted\"", ")", "return", "with", "open", "(", "abs_path", ",", "\"w\"", ")", "as", "fd", ":", "fd", ".", "write", "(", "cfg_text", ")", "print", "(", "\"Saved\"", ")", "if", "(", "info", "[", "'setup'", "]", "[", "'type'", "]", "==", "defs", ".", "linux_usb_setup_type", ")", ":", "print", "(", ")", "util", ".", "fill_print", "(", "\"NOTE: {} was configured assuming the dvbnet interface is \"", "\"named {}. You can check if this is the case after launching the \"", "\"receiver by running:\"", ".", "format", "(", "conf_file", ",", "ifname", ")", ")", "print", "(", "\" ip link show | grep dvb\\n\"", ")", "util", ".", "fill_print", "(", "\"If the dvb interfaces are numbered differently, \"", "\"please update {} accordingly.\"", ".", "format", "(", "conf_file", ")", ")", "elif", "(", "info", "[", "'setup'", "]", "[", "'type'", "]", "==", "defs", ".", "standalone_setup_type", ")", ":", "print", "(", "\"\\n\"", "+", "textwrap", ".", "fill", "(", "(", "\"NOTE: {0} was configured assuming the Novra S400 receiver will \"", "\"be connected to interface {1}. If this is not the case anymore, \"", "\"please update {0} accordingly.\"", ")", ".", "format", "(", "conf_file", ",", "ifname", ")", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/bitcoin.py#L119-L191
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/bitcoin.py
python
Cfg.add_opt
(self, key, val)
Add key-value pair to configuration dictionary
Add key-value pair to configuration dictionary
[ "Add", "key", "-", "value", "pair", "to", "configuration", "dictionary" ]
def add_opt(self, key, val): """Add key-value pair to configuration dictionary""" # The options that appear more than once become lists on the # resulting dictionary. if (key in self.cfg): # If this key is not a list yet in the dictionary, make it a list if (not isinstance(self.cfg[key], list)): if (val == self.cfg[key]): return # identical value found new_val = list() new_val.append(self.cfg[key]) new_val.append(val) self.cfg[key] = new_val else: if (val in self.cfg[key]): return # identical value found self.cfg[key].append(val) else: self.cfg[key] = val
[ "def", "add_opt", "(", "self", ",", "key", ",", "val", ")", ":", "# The options that appear more than once become lists on the", "# resulting dictionary.", "if", "(", "key", "in", "self", ".", "cfg", ")", ":", "# If this key is not a list yet in the dictionary, make it a list", "if", "(", "not", "isinstance", "(", "self", ".", "cfg", "[", "key", "]", ",", "list", ")", ")", ":", "if", "(", "val", "==", "self", ".", "cfg", "[", "key", "]", ")", ":", "return", "# identical value found", "new_val", "=", "list", "(", ")", "new_val", ".", "append", "(", "self", ".", "cfg", "[", "key", "]", ")", "new_val", ".", "append", "(", "val", ")", "self", ".", "cfg", "[", "key", "]", "=", "new_val", "else", ":", "if", "(", "val", "in", "self", ".", "cfg", "[", "key", "]", ")", ":", "return", "# identical value found", "self", ".", "cfg", "[", "key", "]", ".", "append", "(", "val", ")", "else", ":", "self", ".", "cfg", "[", "key", "]", "=", "val" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/bitcoin.py#L12-L33
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/bitcoin.py
python
Cfg.load_text_cfg
(self, text)
Load configuration from text
Load configuration from text
[ "Load", "configuration", "from", "text" ]
def load_text_cfg(self, text): """Load configuration from text""" for line in text.splitlines(): key = line.split("=")[0] val = line.split("=")[1] self.add_opt(key, val)
[ "def", "load_text_cfg", "(", "self", ",", "text", ")", ":", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "key", "=", "line", ".", "split", "(", "\"=\"", ")", "[", "0", "]", "val", "=", "line", ".", "split", "(", "\"=\"", ")", "[", "1", "]", "self", ".", "add_opt", "(", "key", ",", "val", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/bitcoin.py#L35-L40
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/bitcoin.py
python
Cfg.text
(self)
return text
Export configuration to text version
Export configuration to text version
[ "Export", "configuration", "to", "text", "version" ]
def text(self): """Export configuration to text version""" text = "" for k in self.cfg: if (isinstance(self.cfg[k], list)): for e in self.cfg[k]: text += k + "=" + e + "\n" else: text += k + "=" + self.cfg[k] + "\n" return text
[ "def", "text", "(", "self", ")", ":", "text", "=", "\"\"", "for", "k", "in", "self", ".", "cfg", ":", "if", "(", "isinstance", "(", "self", ".", "cfg", "[", "k", "]", ",", "list", ")", ")", ":", "for", "e", "in", "self", ".", "cfg", "[", "k", "]", ":", "text", "+=", "k", "+", "\"=\"", "+", "e", "+", "\"\\n\"", "else", ":", "text", "+=", "k", "+", "\"=\"", "+", "self", ".", "cfg", "[", "k", "]", "+", "\"\\n\"", "return", "text" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/bitcoin.py#L42-L51
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/standalone.py
python
_parse_address
(user_info, arg_addr)
return str(validated_addr)
Parse the receiver's IP address
Parse the receiver's IP address
[ "Parse", "the", "receiver", "s", "IP", "address" ]
def _parse_address(user_info, arg_addr): """Parse the receiver's IP address""" # If the command-line address argument is defined, prioritize it over the # address configured on the JSON config file if (arg_addr is not None): raw_addr = arg_addr elif "rx_ip" in user_info["setup"]: raw_addr = user_info["setup"]["rx_ip"] else: raw_addr = defs.default_standalone_ip_addr try: validated_addr = ip_address(raw_addr) except ValueError: logger.error("{} is not a valid IPv4 address".format(raw_addr)) return return str(validated_addr)
[ "def", "_parse_address", "(", "user_info", ",", "arg_addr", ")", ":", "# If the command-line address argument is defined, prioritize it over the", "# address configured on the JSON config file", "if", "(", "arg_addr", "is", "not", "None", ")", ":", "raw_addr", "=", "arg_addr", "elif", "\"rx_ip\"", "in", "user_info", "[", "\"setup\"", "]", ":", "raw_addr", "=", "user_info", "[", "\"setup\"", "]", "[", "\"rx_ip\"", "]", "else", ":", "raw_addr", "=", "defs", ".", "default_standalone_ip_addr", "try", ":", "validated_addr", "=", "ip_address", "(", "raw_addr", ")", "except", "ValueError", ":", "logger", ".", "error", "(", "\"{} is not a valid IPv4 address\"", ".", "format", "(", "raw_addr", ")", ")", "return", "return", "str", "(", "validated_addr", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/standalone.py#L435-L451