Skip to content

Commit

Permalink
Add Black
Browse files Browse the repository at this point in the history
  • Loading branch information
balloob committed Jul 31, 2019
1 parent 0490167 commit da05dfe
Show file tree
Hide file tree
Showing 16 changed files with 403 additions and 274 deletions.
4 changes: 4 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
"python.pythonPath": "/usr/local/bin/python",
"python.linting.pylintEnabled": true,
"python.linting.enabled": true,
"python.formatting.provider": "black",
"editor.formatOnPaste": false,
"editor.formatOnSave": true,
"editor.formatOnType": true,
"files.trimTrailingWhitespace": true,
"editor.rulers": [80],
"terminal.integrated.shell.linux": "/bin/bash",
Expand Down
8 changes: 8 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
repos:
- repo: https://github.com/python/black
rev: 19.3b0
hooks:
- id: black
args:
- --safe
- --quiet
17 changes: 16 additions & 1 deletion azure-pipelines-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ stages:
python -m venv venv
. venv/bin/activate
pip install -r requirements_test.txt
pip install -r requirements_test.txt -c homeassistant/package_constraints.txt
displayName: 'Setup Env'
- script: |
. venv/bin/activate
Expand All @@ -63,6 +63,21 @@ stages:
. venv/bin/activate
./script/gen_requirements_all.py validate
displayName: 'requirements_all validate'
- job: 'CheckFormat'
pool:
vmImage: 'ubuntu-latest'
container: $[ variables['PythonMain'] ]
steps:
- script: |
python -m venv venv
. venv/bin/activate
pip install -r requirements_test.txt -c homeassistant/package_constraints.txt
displayName: 'Setup Env'
- script: |
. venv/bin/activate
./script/check_format
displayName: 'Check Black formatting'
- stage: 'Tests'
dependsOn:
Expand Down
144 changes: 76 additions & 68 deletions homeassistant/components/rejseplanen/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,51 +21,52 @@

_LOGGER = logging.getLogger(__name__)

ATTR_STOP_ID = 'stop_id'
ATTR_STOP_NAME = 'stop'
ATTR_ROUTE = 'route'
ATTR_TYPE = 'type'
ATTR_STOP_ID = "stop_id"
ATTR_STOP_NAME = "stop"
ATTR_ROUTE = "route"
ATTR_TYPE = "type"
ATTR_DIRECTION = "direction"
ATTR_DUE_IN = 'due_in'
ATTR_DUE_AT = 'due_at'
ATTR_NEXT_UP = 'next_departures'
ATTR_DUE_IN = "due_in"
ATTR_DUE_AT = "due_at"
ATTR_NEXT_UP = "next_departures"

ATTRIBUTION = "Data provided by rejseplanen.dk"

CONF_STOP_ID = 'stop_id'
CONF_ROUTE = 'route'
CONF_DIRECTION = 'direction'
CONF_DEPARTURE_TYPE = 'departure_type'
CONF_STOP_ID = "stop_id"
CONF_ROUTE = "route"
CONF_DIRECTION = "direction"
CONF_DEPARTURE_TYPE = "departure_type"

DEFAULT_NAME = 'Next departure'
ICON = 'mdi:bus'
DEFAULT_NAME = "Next departure"
ICON = "mdi:bus"

SCAN_INTERVAL = timedelta(minutes=1)

BUS_TYPES = ['BUS', 'EXB', 'TB']
TRAIN_TYPES = ['LET', 'S', 'REG', 'IC', 'LYN', 'TOG']
METRO_TYPES = ['M']
BUS_TYPES = ["BUS", "EXB", "TB"]
TRAIN_TYPES = ["LET", "S", "REG", "IC", "LYN", "TOG"]
METRO_TYPES = ["M"]

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_STOP_ID): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_ROUTE, default=[]):
vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_DIRECTION, default=[]):
vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_DEPARTURE_TYPE, default=[]):
vol.All(cv.ensure_list,
[vol.In([*BUS_TYPES, *TRAIN_TYPES, *METRO_TYPES])])
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_STOP_ID): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_ROUTE, default=[]): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_DIRECTION, default=[]): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_DEPARTURE_TYPE, default=[]): vol.All(
cv.ensure_list, [vol.In([*BUS_TYPES, *TRAIN_TYPES, *METRO_TYPES])]
),
}
)


def due_in_minutes(timestamp):
"""Get the time in minutes from a timestamp.
The timestamp should be in the format day.month.year hour:minute
"""
diff = datetime.strptime(
timestamp, "%d.%m.%y %H:%M") - dt_util.now().replace(tzinfo=None)
diff = datetime.strptime(timestamp, "%d.%m.%y %H:%M") - dt_util.now().replace(
tzinfo=None
)

return int(diff.total_seconds() // 60)

Expand All @@ -79,8 +80,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
departure_type = config[CONF_DEPARTURE_TYPE]

data = PublicTransportData(stop_id, route, direction, departure_type)
add_devices([RejseplanenTransportSensor(
data, stop_id, route, direction, name)], True)
add_devices(
[RejseplanenTransportSensor(data, stop_id, route, direction, name)], True
)


class RejseplanenTransportSensor(Entity):
Expand Down Expand Up @@ -124,14 +126,14 @@ def device_state_attributes(self):
ATTR_STOP_NAME: self._times[0][ATTR_STOP_NAME],
ATTR_STOP_ID: self._stop_id,
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_NEXT_UP: next_up
ATTR_NEXT_UP: next_up,
}
return {k: v for k, v in params.items() if v}

@property
def unit_of_measurement(self):
"""Return the unit this state is expressed in."""
return 'min'
return "min"

@property
def icon(self):
Expand All @@ -148,7 +150,7 @@ def update(self):
pass


class PublicTransportData():
class PublicTransportData:
"""The Class for handling the data retrieval."""

def __init__(self, stop_id, route, direction, departure_type):
Expand All @@ -161,16 +163,21 @@ def __init__(self, stop_id, route, direction, departure_type):

def empty_result(self):
"""Object returned when no departures are found."""
return [{ATTR_DUE_IN: 'n/a',
ATTR_DUE_AT: 'n/a',
ATTR_TYPE: 'n/a',
ATTR_ROUTE: self.route,
ATTR_DIRECTION: 'n/a',
ATTR_STOP_NAME: 'n/a'}]
return [
{
ATTR_DUE_IN: "n/a",
ATTR_DUE_AT: "n/a",
ATTR_TYPE: "n/a",
ATTR_ROUTE: self.route,
ATTR_DIRECTION: "n/a",
ATTR_STOP_NAME: "n/a",
}
]

def update(self):
"""Get the latest data from rejseplanen."""
import rjpl

self.info = []

def intersection(lst1, lst2):
Expand All @@ -179,20 +186,17 @@ def intersection(lst1, lst2):

# Limit search to selected types, to get more results
all_types = not bool(self.departure_type)
use_train = all_types or bool(
intersection(TRAIN_TYPES, self.departure_type))
use_bus = all_types or bool(
intersection(BUS_TYPES, self.departure_type))
use_metro = all_types or bool(
intersection(METRO_TYPES, self.departure_type))
use_train = all_types or bool(intersection(TRAIN_TYPES, self.departure_type))
use_bus = all_types or bool(intersection(BUS_TYPES, self.departure_type))
use_metro = all_types or bool(intersection(METRO_TYPES, self.departure_type))

try:
results = rjpl.departureBoard(
int(self.stop_id),
timeout=5,
useTrain=use_train,
useBus=use_bus,
useMetro=use_metro
useMetro=use_metro,
)
except rjpl.rjplAPIError as error:
_LOGGER.debug("API returned error: %s", error)
Expand All @@ -204,36 +208,40 @@ def intersection(lst1, lst2):
return

# Filter result
results = [d for d in results if 'cancelled' not in d]
results = [d for d in results if "cancelled" not in d]
if self.route:
results = [d for d in results if d['name'] in self.route]
results = [d for d in results if d["name"] in self.route]
if self.direction:
results = [d for d in results if d['direction'] in self.direction]
results = [d for d in results if d["direction"] in self.direction]
if self.departure_type:
results = [d for d in results if d['type'] in self.departure_type]
results = [d for d in results if d["type"] in self.departure_type]

for item in results:
route = item.get('name')
route = item.get("name")

due_at_date = item.get('rtDate')
due_at_time = item.get('rtTime')
due_at_date = item.get("rtDate")
due_at_time = item.get("rtTime")

if due_at_date is None:
due_at_date = item.get('date') # Scheduled date
due_at_date = item.get("date") # Scheduled date
if due_at_time is None:
due_at_time = item.get('time') # Scheduled time

if (due_at_date is not None and
due_at_time is not None and
route is not None):
due_at = '{} {}'.format(due_at_date, due_at_time)

departure_data = {ATTR_DUE_IN: due_in_minutes(due_at),
ATTR_DUE_AT: due_at,
ATTR_TYPE: item.get('type'),
ATTR_ROUTE: route,
ATTR_DIRECTION: item.get('direction'),
ATTR_STOP_NAME: item.get('stop')}
due_at_time = item.get("time") # Scheduled time

if (
due_at_date is not None
and due_at_time is not None
and route is not None
):
due_at = "{} {}".format(due_at_date, due_at_time)

departure_data = {
ATTR_DUE_IN: due_in_minutes(due_at),
ATTR_DUE_AT: due_at,
ATTR_TYPE: item.get("type"),
ATTR_ROUTE: route,
ATTR_DIRECTION: item.get("direction"),
ATTR_STOP_NAME: item.get("stop"),
}
self.info.append(departure_data)

if not self.info:
Expand Down
Loading

0 comments on commit da05dfe

Please sign in to comment.