Command line sensor : get specific logs from the las X minutes

Hello everyone,

Due to recent changes in the Tesla API, we are now limited in the number of commands we can send to the car each day. I use my excess solar power to charge my car, which results in numerous commands being sent daily.

When this limit is reached, every command sent by Home Assistant fails, and the following kind of trace appears in the log:

2024-05-30 14:51:39.968 ERROR (MainThread) [homeassistant.core] Error executing service: <ServiceCall number.set_value (c:01HZ4RW0FQDBY0138RP91VDRGS): value=6.0, entity_id=['number.titine_charging_amps']>

My Goal

I am trying to set up a command line sensor that counts the number of these traces in the log and triggers an automation when the count reaches a certain threshold. So far, I have this for the sensor :

# 5. Command Line.
command_line:
  - sensor:
      name: Titine failed power adjustment
      command: 'grep "^$(busybox date -d@"$(( `busybox date +%s`))" "+%Y-%m-%d %H")" home-assistant.log | grep "Error executing service: <ServiceCall number.set_value" | grep "titine" | wc -l '

This works fairly well, but it only counts the number of errors present in the current hour, not for the past hour. For example, if the time is 2:20 PM, it counts the errors between 2:00 PM and 2:20 PM, instead of between 1:20 PM and 2:20 PM as I would prefer.

I have minimal knowledge of bash. I’ve tried reading about BusyBox, grep, awk, and other tools, but I’m quite lost.

Does anyone have an idea on how to improve my sensor?

What are you trying to achieve by counting the number of errors?

Good remark ^^.

Goal : stop the charge of my Tesla during the day, when it can’t receive anymore commands from HA.

Method : Detect a specific event published by HA, like stop_tesla_charging_using_ios, trigger a shortcut with my iphone to stop the charge (shortcut works even if the daily quota of commands is met).

Specific details :

  1. Have a sensor that counts the number of times the command set amps fails during the last X minutes. Typically, the optimizer tries to adjust the current every 10 mins.
  2. Trigger an automation when the count reaches above X. 3 for example. Conditions
    a. Optimizer is on.
    b. Vehicle is charging during daytime.
  3. Charge is stopped. I get notified.

Found a suitable solution, command is :

awk -v d="$(date -d "@$(( $(date +%s) - 3600))" "+%Y-%m-%d %H:%M:%S")" '$1" "$2>=d &&/ERROR(.*)number.set_value(.*)number.chonk_charging_amps/' home-assistant.log | wc -l

Adapt this part

/ERROR(.*)number.set_value(.*)number.chonk_charging_amps/

To the error you’re trying to catch. For me, it was an error in the tesla integration.