Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 36 additions & 51 deletions pyindi/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def printa(msg: Union[str, bytes]):
We use the stdio fxn now.
"""

if type(msg) == bytes:
if isinstance(msg, bytes):
msg = msg.decode()
sys.stdout.write(msg)
sys.stdout.flush()
Expand Down Expand Up @@ -282,9 +282,8 @@ def Def(self, msg=None):
tagname = "def" + self.tagcontext
dtd_elements = {tag.name: tag for tag in self.dtd.iterelements()}
if tagname not in dtd_elements:
raise AttributeError(
"{tagname} not defined in \
Document Type Definition")
raise AttributeError(f"{tagname} not defined in Document Type "
"Definition")

ele_definition = dtd_elements[tagname]
ele = etree.Element(ele_definition.name)
Expand Down Expand Up @@ -316,17 +315,16 @@ def Set(self, msg=None):
tagname = "set" + self.tagcontext
dtd_elements = {tag.name: tag for tag in self.dtd.iterelements()}
if tagname not in dtd_elements:
raise AttributeError(
f"{tagname} not defined in \
Document Type Definition")
raise AttributeError(f"{tagname} not defined in Document Type "
"Definition")

ele_definition = dtd_elements[tagname]
ele = etree.Element(ele_definition.name)
for attribute in ele_definition.iterattributes():
if hasattr(self, attribute.name):
ele.set(attribute.name, str(getattr(self, attribute.name)))
for prop in self.iprops:
logging.warning(prop)
logging.debug(prop)
ele.append(prop.Set())

if msg is not None:
Expand Down Expand Up @@ -394,9 +392,8 @@ def Def(self):
dtd_elements = {tag.name: tag for tag in self.dtd.iterelements()}

if tagname not in dtd_elements:
raise AttributeError(
f"{tagname} not defined in \
Document Type Definition")
raise AttributeError(f"{tagname} not defined in Document Type "
"Definition")

ele_definition = dtd_elements[tagname]
ele = etree.Element(ele_definition.name)
Expand All @@ -415,9 +412,8 @@ def Set(self):
dtd_elements = {tag.name: tag for tag in self.dtd.iterelements()}

if tagname not in dtd_elements:
raise AttributeError(
f"{tagname} not defined in \
Document Type Definition")
raise AttributeError(f"{tagname} not defined in Document Type "
"Definition")

ele_definition = dtd_elements[tagname]
ele = etree.Element(ele_definition.name)
Expand All @@ -442,10 +438,8 @@ def value(self):
elif isinstance(self, IBLOB):
return self.data

raise TypeError(f"""value method must be called with INumber,
IText, ILight, ISwitch or IBLOB not {type(self)}
{isinstance(self, INumber)}
""")
raise TypeError(f"value method must be called with INumber, IText,"
f" ILight, ISwitch or IBLOB not {type(self)}")

@value.setter
def value(self, val):
Expand All @@ -462,14 +456,8 @@ def value(self, val):
elif isinstance(self, IBLOB):
self.data = val
else:
raise TypeError(f"""
value method must be called with INumber, IText,
ILight, ISwitch or IBLOB not {type(self)} {self}
{isinstance(self, INumber)} {self.tagcontext}
{type(self) == INumber}
{self.tagcontext == "Switch"}
{self.__class__ == ISwitch}
""")
raise TypeError("value method must be called with INumber, IText,"
f" ILight, ISwitch or IBLOB, not {type(self)}")


class INumberVector(IVectorProperty):
Expand Down Expand Up @@ -784,7 +772,7 @@ def value(self) -> str:

@value.setter
def value(self, val: bytes):
if type(val) != bytes:
if not isinstance(val, bytes):
raise ValueError("""IBLOB value must by bytes type""")

self.size = len(val)
Expand Down Expand Up @@ -855,7 +843,8 @@ def start(self):
astart
"""

self.mainloop = asyncio.get_event_loop()
if self.mainloop is None:
self.mainloop = asyncio.get_event_loop()
self.reader, self.writer = self.mainloop.run_until_complete(stdio())
self.running = True
future = asyncio.gather(
Expand All @@ -874,7 +863,8 @@ async def astart(self, *tasks):
other device tasks.
"""

self.mainloop = asyncio.get_running_loop()
if self.mainloop is None:
self.mainloop = asyncio.get_event_loop()
self.reader, self.writer = await stdio()
self.running = True
future = asyncio.gather(
Expand All @@ -896,12 +886,9 @@ async def repeat_queuer(self):
func(self)

except Exception as error:
sys.stderr.write(
f"There was an exception in the \
later decorated fxn {func}:")

sys.stderr.write(f"{error}")
sys.stderr.write("See traceback below.")
sys.stderr.write("There was an exception in the later "
f"decorated fxn {func}:\n{error}\nSee "
"traceback below.")
traceback.print_exc(file=sys.stderr)

def exception(self, loop, context):
Expand Down Expand Up @@ -1115,16 +1102,15 @@ def buildSkeleton(self, skelfile):
try:
ivec = self.vectorFactory(xml_def.tag, xml_def.attrib, properties)
except Exception as error:
logging.error(f"The following error was caused by this xml tag \
\n {etree.tostring(xml_def)}")
logging.error("The following error was caused by this xml tag:"
f"\n{etree.tostring(xml_def).decode()}")
logging.error(error)
raise
self.IDDef(ivec)

def ISNewNumber(self, dev: str, name: str, values: list, names: list):
raise NotImplementedError(
"Device driver must \
overload ISNewNumber method.")
"Device driver must overload ISNewNumber method.")

def IUFind(self, name, device=None, group=None):
"""
Expand Down Expand Up @@ -1172,9 +1158,8 @@ def IUUpdate(self, device, name, values, names, Set=False):
return vp

def ISGetProperties(self, device):
raise NotImplementedError(
f"Subclass of {self} must \
implement ISGetProperties")
raise NotImplementedError(f"Subclass of {self} must implement "
"ISGetProperties")

def IDMessage(
self, msg: str,
Expand All @@ -1192,17 +1177,17 @@ def IDMessage(
msgtype : str, optional
one of "DEBUG", "INFO", "WARN", by default "INFO"
"""
if type(timestamp) == datetime.datetime:
if isinstance(timestamp, datetime.datetime):
timestamp = timestamp.strftime("%Y-%m-%dT%H:%M:%S")

elif timestamp is None:
timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")

xml = f'<message message="[{msgtype}] {msg}" '
xml += f'timestamp="{timestamp}" '
xml += f'device="{self.name()}"/> '

self.outq.put_nowait(xml.encode())
xml = etree.Element("message",
attrib={"message": f"[{msgtype}] {msg}",
"timestamp": timestamp,
"device": self.name()})
self.outq.put_nowait(etree.tostring(xml))
# self.writer.write(xml.encode())

def IDSetNumber(self, n: INumberVector, msg=None):
Expand Down Expand Up @@ -1370,8 +1355,8 @@ def vectorFactory(vector_type, attribs, properties):
vec.tp.append(iprop)

else:
message = f"vector_type argument must be a string containing \
Light, Number, Switch, Text or BLOB not {vector_type}"
raise ValueError(message)
raise ValueError("vector_type argument must be a string containing"
" Light, Number, Switch, Text or BLOB, not "
f"{vector_type}")

return vec