NEW UK bus & train component: Beta testers required

Hi all, have a UK bus and train status component in a working state, looking for beta testers. Enter a valid bus or train route and display the next departure on that route, its status, and other info such as platform for trains. Credit to Tim Nicholls for the base class and busses (TO MERGE).

The repo is at https://github.com/robmarkcole/TrasportAPI-HASS

3 Likes

Your project looks perfect for my needs. I will be adding it today. I had transportapi set up as a rest sensor. My issues was that I soon as I put a couple of sensors in I hit my rate limit of 1000 requests fairly quickly. Home Assistant sensor requests an update every 60 seconds making one sensor 1440 requests a day. What are you doing to rate limit the requests? Or could you add in a option to the sensor.yaml to manually set this?

Hi @michaelmcarthur you can set scan interval in config https://home-assistant.io/docs/configuration/platform_options/

1000/(60*24) = 0.69 therefore 1 sensor updating every minute will run into trouble at about 5pm daily, so recommend a scan_interval of 90 sec.

You can calc the max refresh rate for n sensors from rate_mins = 1000/(24n) e.g. 3 sensors can update every 1000/(243) =~ 14 minutes.

A is to only update the sensor in the windows of time about your daily commute. E.g. if you catch the same train every day and that is your main concern, just update the sensor in the hour up to and about that train.

OK, if the 1000 limit is too onerous another option is to scrape the national rail page, no API credentials and no rate limits http://ojp.nationalrail.co.uk/service/ldbboard/dep/MAL/WAT/To

thoughts?

It would be possible to scrape the national rail page but it is against its terms of use under “Permitted use of the web site”. It states that you can copy the information. You can display the page in a frame on a third party site.

I like the idea of limiting it to a persons commute. You could base it on location or time.

Thanks, it could be embedded as an iframe from the looks of things, but not really what I’m after.

With transportAPI the nearest station can be determined from lat-long coords, could be interesting

A solution I propose is to set in the config a window of time (around your daily commute for example) during which the status is polled every minute. Outside of this window the status can be polled at a lower rate set by the user, e.g. every 10 mins. There will also be an attribute which will display what fraction of your daily allowance of 1000 requests is being made by any one sensor, e.g. 25% (i.e. 250 requests) by commute sensor. This will make it easy to optimise the windows and rates. Thoughts?

1 Like

I like it, sounds good. Looking forward to try it out.

I have added your sensor to my config but Im having issues. When I copy over your example it works as expected. But when I try and make changes to stations it does not update. I put in my new departure and arrival stations into the sensor and in the template I changed the “wat” part of this template '{{states.sensor.next_train_to_wat.attributes.next_trains[0].status}}' to my destination code. In home assistant it shows the old information not the new updated info. I tried clearing all my browsing data in chrome and it still shows as the old info. I have this in my error log.

    _delta_mins, [train['scheduled'] for train in self._next_trains]
ValueError: min() arg is an empty sequence
17-06-13 19:55:54 ERROR (MainThread) [homeassistant.core] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/usr/lib/python3.4/asyncio/tasks.py", line 233, in _step
    result = coro.throw(exc)
  File "/usr/local/lib/python3.4/dist-packages/homeassistant/helpers/entity_component.py", line 361, in async_process_entity
    new_entity, self, update_before_add=update_before_add
  File "/usr/local/lib/python3.4/dist-packages/homeassistant/helpers/entity_component.py", line 191, in async_add_entity
    yield from self.hass.loop.run_in_executor(None, entity.update)
  File "/usr/lib/python3.4/asyncio/futures.py", line 388, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/lib/python3.4/asyncio/tasks.py", line 286, in _wakeup
    value = future.result()
  File "/usr/lib/python3.4/asyncio/futures.py", line 277, in result
    raise self._exception
  File "/usr/lib/python3.4/concurrent/futures/thread.py", line 54, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/pi/.homeassistant/custom_components/sensor/uk_transport.py", line 175, in update
    _delta_mins, [bus['scheduled'] for bus in self._next_buses]
ValueError: min() arg is an empty sequence```

I have tried this sensor in it's most basic form, just having the sensor not the template. It works with the stations you provided but when I change them it stops working.

What have you entered in config?
I’ve seen that error within invalid route in testing

I completed some testing. The sensor works if I put the first and last train on the scheduled route. If I put two intermediate stations on that route it does not work.

Yes the component can only handle a single route (where both stations are on the same line) and makes use of https://developer.transportapi.com/docs?raml=https://transportapi.com/v3/raml/transportapi.raml##request_uk_train_station_station_code_live_json
The actual query is query_url = 'train/station/{}/live.json'.format(station_code) with the parameters params = {'darwin': 'false', 'destination': self._destination_name, 'train_status': 'passenger'}
I suggest that for future debugging we use Github issues, and save this thread for general discussion and updates :slight_smile:

I have pushed a fix and opened an issue: https://github.com/robmarkcole/TrasportAPI-HASS/issues/1

Oh this is good news, thanks for the work. Any way to show the “train after the next one” as well as the next one?

For the next train:

Would change to

{{states.sensor.next_train_to_wat.attributes.next_trains[1].status}}

As next_train is a list of dicts.

Would be nice to add a table of upcoming trains to the front-end - not sure how to do this?

Yep a table of the next 3 or something would be very helpful

Created a feature request for tables on front end Table on front-end

I must be missing something here but i’m getting errors in my log and no updates

2017-06-14 14:51:31 WARNING (MainThread) [homeassistant.components.sensor.template] Could not render template Next train platform, the state is unknown.
2017-06-14 14:51:31 WARNING (MainThread) [homeassistant.components.sensor.template] Could not render template Next train status, the state is unknown.
2017-06-14 14:51:31 WARNING (MainThread) [homeassistant.components.sensor.template] Could not render template Next train estimated, the state is unknown.
2017-06-14 14:51:31 WARNING (MainThread) [homeassistant.components.sensor.template] Could not render template Next train origin, the state is unknown.
2017-06-14 14:51:31 WARNING (MainThread) [homeassistant.components.sensor.template] Could not render template Next train scheduled, the state is unknown.

@tristophe Whats in your config? Have you pulled the latest commit?

I’ve just checked again and it was a syntax error, completely my fault for not checking the YAML.

All working now.

Thanks for developing!

1 Like

Is it possible to specify an offset, or get the status of more than just the immediately next train?

I live about 20 minutes from my local station, and trains are every 15 minutes, so knowing the next train isn’t helpful, but knowing about the train more than 20 minutes from now, or the next 2 or 3 trains, that’s useful.