openwebrx-clone/owrx/command.py

72 lines
1.8 KiB
Python
Raw Normal View History

2019-12-27 23:26:45 +00:00
from abc import ABC, abstractmethod
class CommandMapper(object):
def __init__(self, base=None, mappings=None, static=None):
2019-12-27 23:26:45 +00:00
self.base = base
self.mappings = {} if mappings is None else mappings
2019-12-27 23:26:45 +00:00
self.static = static
def map(self, values):
args = [self.mappings[k].map(v) for k, v in values.items() if k in self.mappings]
args = [a for a in args if a != ""]
options = " ".join(args)
command = "{0} {1}".format(self.base, options)
if self.static is not None:
command += " " + self.static
return command
def setMapping(self, key, mapping):
self.mappings[key] = mapping
return self
def setMappings(self, mappings):
for k, v in mappings.items():
self.setMapping(k, v)
return self
def setBase(self, base):
self.base = base
return self
def setStatic(self, static):
self.static = static
return self
class CommandMapping(ABC):
@abstractmethod
def map(self, value):
pass
class Flag(CommandMapping):
def __init__(self, flag):
self.flag = flag
def map(self, value):
if value is not None and value:
return self.flag
else:
return ""
class Option(CommandMapping):
def __init__(self, option):
self.option = option
2020-01-10 19:50:56 +00:00
self.spacer = " "
2019-12-27 23:26:45 +00:00
def map(self, value):
if value is not None:
if isinstance(value, str) and " " in value:
2020-01-10 19:50:56 +00:00
template = '{option}{spacer}"{value}"'
2019-12-27 23:26:45 +00:00
else:
2020-01-10 19:50:56 +00:00
template = "{option}{spacer}{value}"
return template.format(option=self.option, spacer=self.spacer, value=value)
2019-12-27 23:26:45 +00:00
else:
return ""
2020-01-10 19:50:56 +00:00
def setSpacer(self, spacer):
self.spacer = spacer
return self