Skip to content

Commit

Permalink
start paring down list via mypy.ini and fixing errors, 6 files to go …
Browse files Browse the repository at this point in the history
…after this commit
  • Loading branch information
gnmerritt committed Sep 12, 2022
1 parent f3c6a71 commit 8d521c7
Show file tree
Hide file tree
Showing 23 changed files with 71 additions and 113 deletions.
8 changes: 8 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[flake8]
ignore = W291,W503,E265,E266,E302,E722
max-line-length = 127
exclude =
.git,
__pycache__,
.mypy_cache,
.pytest_cache,
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]
python-version: [3.6, 3.7, 3.8, 3.9, 3.10]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
Expand Down
2 changes: 1 addition & 1 deletion BAC0/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@

connect = gui
else:
connect = lite
connect = lite # type: ignore[assignment, misc]
web = lambda: print(
"All features not available to run BAC0.web(). Some modules are missing (flask, flask-bootstrap, bokeh, pandas). See docs for details. To start BAC0, use BAC0.lite()"
)
Expand Down
3 changes: 2 additions & 1 deletion BAC0/core/app/ScriptApplication.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"""
# --- standard Python modules ---
from collections import defaultdict
import typing as t

# --- 3rd party modules ---
from bacpypes.app import ApplicationIOController
Expand Down Expand Up @@ -224,7 +225,7 @@ def __init__(
# bind the BIP stack to the network, no network number
self.nsap.bind(self.bip, address=self.localAddress)

self.i_am_counter = defaultdict(int)
self.i_am_counter: t.Dict[t.Tuple[str, int], int] = defaultdict(int)
self.i_have_counter = defaultdict(int)
self.who_is_counter = defaultdict(int)

Expand Down
22 changes: 1 addition & 21 deletions BAC0/core/devices/Trends.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,18 @@
# Copyright (C) 2015 by Christian Tremblay, P.Eng <[email protected]>
# Licensed under LGPLv3, see file LICENSE in this source tree.
#
"""
Points.py - Definition of points so operations on Read results are more convenient.
"""

# --- standard Python modules ---
from datetime import datetime
from collections import namedtuple
import time
from itertools import islice


# --- 3rd party modules ---
try:
import pandas as pd
from pandas.io import sql

try:
from pandas import Timestamp
except ImportError:
from pandas.lib import Timestamp
_PANDAS = True
except ImportError:
_PANDAS = False

from bacpypes.object import TrendLogObject
from bacpypes.primitivedata import Date, Time

# --- this application's modules ---
from ...tasks.Poll import SimplePoll as Poll
from ...tasks.Match import Match, Match_Value
from ..io.IOExceptions import NoResponseFromController, UnknownPropertyError
from ..utils.notes import note_and_log


Expand All @@ -56,7 +37,6 @@ def __init__(self):
self.record_count = 0
self.total_record_count = 0
self.log_interval = 0
self.description = None
self.statusFlags = None
self.status_flags = {
"in_alarm": False,
Expand Down Expand Up @@ -196,7 +176,7 @@ def create_dataframe(self, log_buffer):
@property
def history(self):
self.read_log_buffer()
if not _PANDAS:
if not _PANDAS or self.properties._df is None:
return dict(
zip(
self.properties._history_components["index"],
Expand Down
26 changes: 5 additions & 21 deletions BAC0/core/devices/local/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,14 @@
BAC0BBMDDeviceApplication,
BAC0ForeignDeviceApplication,
)

from bacpypes.object import (
AnalogInputObject,
AnalogValueObject,
BinaryValueObject,
Property,
register_object_type,
registered_object_types,
DatePatternValueObject,
ReadableProperty,
WritableProperty,
OptionalProperty,
)
from bacpypes.basetypes import (
EngineeringUnits,
DateTime,
PriorityArray,
StatusFlags,
Reliability,
Polarity,
)

import typing as t
from collections import namedtuple
from colorama import Fore, Back, Style
from colorama import Fore


@note_and_log
Expand All @@ -55,14 +39,14 @@ class ObjectFactory(object):
"""

instances = {}
instances: t.Dict[str, t.Set] = {}

definition = namedtuple(
definition = namedtuple( # type: ignore[name-match]
"Definition",
"name, objectType, instance, properties, description, presentValue, is_commandable, relinquish_default",
)

objects = {}
objects: t.Dict[str, t.Any] = {}
# In the future... should think about a way to store relinquish default values because on a restart
# those should be restored.

Expand Down
6 changes: 3 additions & 3 deletions BAC0/core/devices/mixins/read_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
read_mixin.py - Add ReadProperty and ReadPropertyMultiple to a device
"""
# --- standard Python modules ---
import typing as t

# --- 3rd party modules ---

# --- this application's modules ---
from ....tasks.Poll import DeviceNormalPoll, DeviceFastPoll
from ...io.IOExceptions import (
ReadPropertyMultipleException,
NoResponseFromController,
SegmentationNotSupported,
BufferOverflow,
Expand All @@ -24,7 +24,6 @@
BooleanPoint,
EnumPoint,
StringPoint,
OfflinePoint,
DateTimePoint,
)
from ..Trends import TrendLog
Expand Down Expand Up @@ -565,6 +564,7 @@ def poll(self, command="start", *, delay=10):
device.poll('stop')
device.poll(delay = 5)
"""
_poll_cls: t.Union[t.Type[DeviceFastPoll], t.Type[DeviceNormalPoll]]
if delay < 10:
self.properties.fast_polling = True
_poll_cls = DeviceFastPoll
Expand All @@ -580,7 +580,7 @@ def poll(self, command="start", *, delay=10):

if (
str(command).lower() == "stop"
or command == False
or command == False # noqa E712
or command == 0
or delay == 0
):
Expand Down
11 changes: 3 additions & 8 deletions BAC0/core/functions/DeviceCommunicationControl.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@
"""
# --- standard Python modules ---
import datetime as dt

# --- 3rd party modules ---
from bacpypes.pdu import Address, GlobalBroadcast
from bacpypes.primitivedata import Date, Time, CharacterString, Unsigned16
from bacpypes.basetypes import DateTime
from bacpypes.pdu import Address
from bacpypes.primitivedata import CharacterString, Unsigned16
from bacpypes.apdu import (
DeviceCommunicationControlRequest,
DeviceCommunicationControlRequestEnableDisable,
Expand All @@ -25,9 +23,6 @@

from ...core.io.Read import find_reason
from ..io.IOExceptions import (
SegmentationNotSupported,
ReadPropertyException,
ReadPropertyMultipleException,
NoResponseFromController,
ApplicationNotStarted,
)
Expand Down Expand Up @@ -81,7 +76,7 @@ def dcc(self, address=None, duration=None, password=None, state=None):
if not isinstance(apdu, SimpleAckPDU): # expect an ACK
self._log.warning("Not an ack, see debug for more infos.")
self._log.debug(
"Not an ack. | APDU : {} / {}".format((apdu, type(apdu)))
"Not an ack. | APDU : {} / {}".format(apdu, type(apdu))
)
return

Expand Down
11 changes: 3 additions & 8 deletions BAC0/core/functions/Reinitialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,16 @@
"""
from ...core.io.Read import find_reason
from ..io.IOExceptions import (
SegmentationNotSupported,
ReadPropertyException,
ReadPropertyMultipleException,
NoResponseFromController,
ApplicationNotStarted,
)
from ...core.utils.notes import note_and_log

# --- standard Python modules ---
import datetime as dt

# --- 3rd party modules ---
from bacpypes.pdu import Address, GlobalBroadcast
from bacpypes.primitivedata import Date, Time, CharacterString
from bacpypes.basetypes import DateTime
from bacpypes.pdu import Address
from bacpypes.primitivedata import CharacterString
from bacpypes.apdu import (
ReinitializeDeviceRequest,
ReinitializeDeviceRequestReinitializedStateOfDevice,
Expand Down Expand Up @@ -74,7 +69,7 @@ def reinitialize(self, address=None, password=None, state="coldstart"):
if not isinstance(apdu, SimpleAckPDU): # expect an ACK
self._log.warning("Not an ack, see debug for more infos.")
self._log.debug(
"Not an ack. | APDU : {} / {}".format((apdu, type(apdu)))
"Not an ack. | APDU : {} / {}".format(apdu, type(apdu))
)
return

Expand Down
2 changes: 1 addition & 1 deletion BAC0/core/functions/TimeSync.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def local_date(self):

def utcOffset(self) -> float:
"Returns UTC offset in minutes"
return round(self.now.astimezone().utcoffset().total_seconds() / 60)
return round(self.now.astimezone().utcoffset().total_seconds() / 60) # type: ignore[union-attr]

def is_dst(self) -> bool:
return self.timezone.dst(self.now) != dt.timedelta(0)
Expand Down
4 changes: 2 additions & 2 deletions BAC0/core/io/Write.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def write(self, args, vendor_id=0, timeout=10):
if not isinstance(apdu, SimpleAckPDU): # expect an ACK
self._log.warning("Not an ack, see debug for more infos.")
self._log.debug(
"Not an ack. | APDU : {} / {}".format((apdu, type(apdu)))
"Not an ack. | APDU : {} / {}".format(apdu, type(apdu))
)
return

Expand Down Expand Up @@ -280,7 +280,7 @@ def writeMultiple(self, addr=None, args=None, vendor_id=0, timeout=10):
if not isinstance(apdu, SimpleAckPDU): # expect an ACK
self._log.warning("Not an ack, see debug for more infos.")
self._log.debug(
"Not an ack. | APDU : {} / {}".format((apdu, type(apdu)))
"Not an ack. | APDU : {} / {}".format(apdu, type(apdu))
)
return

Expand Down
5 changes: 3 additions & 2 deletions BAC0/core/utils/notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
from collections import namedtuple
from datetime import datetime
import logging
from logging import FileHandler
from logging import FileHandler, Logger
import sys
import typing as t

import os
from os.path import expanduser, join
Expand All @@ -26,7 +27,7 @@


class LogList:
LOGGERS = []
LOGGERS: t.List[Logger] = []


def convert_level(level):
Expand Down
6 changes: 3 additions & 3 deletions BAC0/db/influxdb.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
try:
from influxdb_client import InfluxDBClient, Point, WriteOptions

from influxdb_client.client.write import WriteApi
except ImportError:
raise ImportError("Install influxdb to use this feature")

import pytz
from datetime import datetime


class InfluxDB:
Expand All @@ -21,7 +20,8 @@ class InfluxDB:
tags_file = None
username = None
password = None
client = None
client: InfluxDBClient
write_api: WriteApi

def __init__(self, params):
# params should be a dict with name=InfluxDB and bucket=valid_bucket_to_use.
Expand Down
4 changes: 2 additions & 2 deletions BAC0/db/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# Licensed under LGPLv3, see file LICENSE in this source tree.
#
"""
sql.py -
sql.py -
"""

# --- standard Python modules ---
Expand Down Expand Up @@ -271,7 +271,7 @@ def his_from_sql(self, db_name, point):
"""
Retrive point histories from SQL database
"""
his = self._read_from_sql('select * from "{}"'.format("history", db_name))
his = self._read_from_sql('select * from "{}"'.format("history"), db_name)
his.index = his["index"].apply(Timestamp)
return his.set_index("index")[point]

Expand Down
6 changes: 4 additions & 2 deletions BAC0/scripts/Base.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ def stopApp()
"""
import random
import sys
import typing as t

# --- standard Python modules ---
from threading import Thread
Expand All @@ -31,6 +32,7 @@ def stopApp()
from bacpypes.core import stop as stopBacnetIPApp
from bacpypes.local.device import LocalDeviceObject
from bacpypes.primitivedata import CharacterString
from bacpypes.pdu import Address

# --- this application's modules ---
from .. import infos
Expand Down Expand Up @@ -94,7 +96,7 @@ class Base:
:param segmentationSupported='segmentedBoth':
"""

_used_ips = set()
_used_ips: t.Set[Address] = set()

def __init__(
self,
Expand Down Expand Up @@ -164,7 +166,7 @@ def __init__(
self.modelName = modelName
self.description = description

self.discoveredDevices = None
self.discoveredDevices: t.Optional[t.Dict[t.Tuple[str, int], int]] = None
self.systemStatus = DeviceStatus(1)

self.bbmdAddress = bbmdAddress
Expand Down
Loading

0 comments on commit 8d521c7

Please sign in to comment.