Search code examples
pythonbashautomationcron-task

Control TP-Link Kasa local switches with Bash


I installed the python-kasa library to control TPLink smart home devices from my local server. while issuing commands from the command line is simple, I'm trying to execute them in Bash based on result of the query. My dilemma is purely my coding ability and I'm looking for a push in the right direction. what I would like to do is along the lines of the following syntactically incorrect mess:

   if kasa --host 127.0.0.2 status on; then
        echo "already its on"
    else
        kasa --host 127.0.0.2 on
        echo "now its on"
    fi 

when you issue the command "kasa --host Device_IP state" you get the following results.

No --strip nor --bulb nor --plug given, discovering..
== Red light - HS210(US) ==
    Host: 127.0.0.2
    Device state: OFF

    == Generic information ==
    Time:         2021-05-23 21:16:31
    Hardware:     2.0
    Software:     1.1.4 Build 200821 Rel.092912
    MAC (rssi):   XX:XX:XX:XX:XX:XX (-33)
    Location:     {'latitude': XXXXXX, 'longitude': -XXXXXX}

    == Device specific information ==
    LED state: True
    On since: None

The core reason driving me to need a bash script to control devices is because I live in an area with horrible cable internet service that often requires a modem reboot which is simple when home but no so much when off site. I wanted to create a script that cron will run every ten minutes or so and check if internet is accessible and/or if the power is on for the cable modem. Basically if power is off then turn it on, if internet is down then power off and on to get it running again.


Solution

  • Something like this maybe?

    #!/usr/bin/env bash
    
    if kasa --host Device_IP state 2>&1 | grep -Fq 'Device state: OFF'; then
      : restart or start the device here
    elif kasa --host Device_IP state 2>&1 | grep -Fq 'Device state: ON'; then
      : device is already on
    fi