Set lamp colour depending on train status

Yes bud my 8.04 train I got on today.

Here is my code for trains_state.py

############################################
# Enter your your sensor name here.        #
############################################
entity_id = 'sensor.next_train_to_eus'
scheduled = False   # Check if train scheduled
train_time = '08:04'

if hass.states.get(entity_id).state == "No departures":
  logger.warn('No Departures')
else:
  attributes = hass.states.get(entity_id).attributes
  morning_train_status = hass.states.get('sensor.my_8_04_train').state
  try:
    for train in attributes['next_trains']:
      if train['scheduled'] == train_time:
          scheduled = True   # Check if train scheduled
          if train['status'] != my_8_04_train_status:
              hass.states.set('sensor.my_8_04_train', train['status'])

              if train['status'] == 'ON TIME':
                  hass.services.call('script', 'turn_on', { "entity_id" : 'script.bedroom_light_green' })
                  hass.services.call('notify', 'ahmed', { "title": "Train Status Update", "message": "The {} is scheduled to be on time.".format(train_time)})
              elif train['status'] == 'LATE':
                  hass.services.call('script', 'turn_on', { "entity_id" : 'script.bedroom_light_orange' })
                  hass.services.call('notify', 'ahmed', { "title": "Train Status Update", "message": "The {} will be late and is now sheduled at".format(train_time) + train$
              elif train['status'] == 'CANCELLED':
                  hass.services.call('script', 'turn_on', { "entity_id" : 'script.bedroom_light_red' })
                  hass.services.call('notify', 'ahmed', { "title": "Train Status Update", "message": "The {} has been cancelled.".format(train_time)})
          break
  except:
    logger.warn('Failed to get next trains')

if not scheduled:
    hass.states.set('sensor.my_8_04_train', 'No data')  # check no data
#logger.warn('Test complete')

I think if it worked yesterday then its an issue with the data source, prob reached requests limit or network issue.
Give it another shot tomorrow.
Cheers

do you think the code that I posted above is correct?

I will give a shot tomorrow.

Thanks buddy

Yes looks like mine :grin:

Right I have used a different train now and I get the same error as before i.e. failed to get next trains.

Trains are running fine.

UPDATE:

Just reverted back to the old code with 2 python files and everything seems to work fine.

There were no errors in the log?

Had the same error every 1 min saying: failed to get next trains

I’ve spotted your mistake… Hint whats morning_train_status doing?

Bwt when you post python code please format with ’ ``` python ’

Ah I see it should be sensor.my_8_04_train ?!

Have re-written script to make it easier to maintain.

https://github.com/robmarkcole/TrasportAPI-HASS/blob/master/lights_based_on_status/train_state.py

Used the new script above and everything worked perfectly thanks.

1 Like

OK now live on Hackster:

1 Like

Hi @robmarkcole

So the script has been working all fine but now I get an error and my lights do not change colour anymore.

The error I get is:

Traceback (most recent call last):
  File "trains_state.py", line 16, in <module>
    if hass.states.get(MAIN_ENTITY_ID).state == "No departures":
NameError: name 'hass' is not defined

Can you help please?

Hmm appears to not be finding the hass object. Are your other python scripts working?

Well I have got amother script and it gives me the following error/warning:

No handlers could be found for logger "bs4.dammit"

I have got python 3.6 and everything used to run fine.

Could be a problem with your install. I’m not getting any errors from that python script. Sorry

Hmm strange… I tried a different python script and it worked fine.

I suppose it’s something to do with HA and/or the location of the python scripts folder has been changed? Its definitely something to do with HA in relation to running python scripts.

I downgraded to 0.59.2 and have the same issue. I will try an older version of HA and see if it works like it did in the past.

If you didn’t edit your python script then thats all it can be I suppose

Yeah I haven’t touched it. I noticed the lights were not functioning as per the train status and that’s when I looked into it.

Here’s my version based on the scripts here (thanks for sharing!). It requires 0.61.0 which contains a fix to get time.strptime() to work.

I use a pair of automations which notify me via slack in the morning and afternoon to tell me about trains i’m interested in within a time window:

- action:
  - data:
      entity_id: sensor.next_train_to_abc
      notify_target: tom_slack
      window_start: 08:00
      window_end: 08:30
    service: python_script.trains_status
  alias: Morning Train Status
  condition: []
  id: '1514667558798'
  trigger:
  - at: 07:30
    platform: time

I’m also playing around with another pair that run when the train sensor changes between a time window to notify every couple of minutes if any trains are running late. The only problem is that if trains were late but become on time again, I wont know about it:

- action:
  - data:
      entity_id: sensor.next_train_to_abc
      late_only: 'True'
      notify_target: tom_slack
      throttle_mins: '2'
      window_end: 08:30
      window_start: 08:00
    service: python_script.trains_status
  alias: Morning Late Trains
  condition:
  - after: 07:30
    before: 08:30
    condition: time
  trigger:
  - entity_id: sensor.next_train_to_bsk
    platform: state
2 Likes