Battery Charting Script

Posted on
Tue Jan 14, 2020 2:59 pm
McJohn offline
User avatar
Posts: 631
Joined: Dec 18, 2012
Location: The Netherlands

Re: Battery Charting Script

Thanks for the colorful information, great tool!

Code: Select all
plt.figure(figsize=(0.5,0.5))


What is the smallest circle which could be made?
Because 0.1,01 give a square.

Posted on
Tue Jan 14, 2020 3:37 pm
DaveL17 offline
User avatar
Posts: 6739
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Re: Battery Charting Script

It's probably not a square per se; it's probably plotting a circle that's larger than the figure area.

If you reduce the figure size, you need to reduce the plot size too. Try playing with the s=300 bit.

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Posted on
Wed Jan 15, 2020 3:20 am
McJohn offline
User avatar
Posts: 631
Joined: Dec 18, 2012
Location: The Netherlands

Re: Battery Charting Script

Thanks for the hint!
Attachments
s=5,figsize0.2.png
s=5,figsize0.2.png (199 Bytes) Viewed 12018 times

Posted on
Wed May 06, 2020 1:53 pm
mikkyo offline
Posts: 8
Joined: Jan 09, 2017

Re: Battery Charting Script

I figured I'd try this, haven't done any scripting within Indigo yet..

Indigo 7.4.1
macOS Catalina 10.15.4

Created a New Schedule
Under Action Execute Script (Scripts and File Actions)
Copied the script from the git hub repo, tried it in an embedded script, got Invalid Syntax
Saved it to a file battery-charting-script.py in the /Library/Application Support/PerceptiveAutomation/Scripts, and choose it as the file to run, got
Script Error battery-charting-script.py: invalid syntax
Script Error around line 349 - "print(s, file=self.fileo)"

Posted on
Wed May 06, 2020 2:14 pm
DaveL17 offline
User avatar
Posts: 6739
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Re: Battery Charting Script

mikkyo wrote:
I figured I'd try this, haven't done any scripting within Indigo yet..

Indigo 7.4.1
macOS Catalina 10.15.4

Created a New Schedule
Under Action Execute Script (Scripts and File Actions)
Copied the script from the git hub repo, tried it in an embedded script, got Invalid Syntax
Saved it to a file battery-charting-script.py in the /Library/Application Support/PerceptiveAutomation/Scripts, and choose it as the file to run, got
Script Error battery-charting-script.py: invalid syntax
Script Error around line 349 - "print(s, file=self.fileo)"

Which script did you use? The one linked to in post 1 of this thread is only 143 lines long and I don't think it contains any print statements.

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Posted on
Thu May 07, 2020 3:47 pm
mikkyo offline
Posts: 8
Joined: Jan 09, 2017

Re: Battery Charting Script

That one for the first post.
https://github.com/DaveL17/indigo-scrip ... -script.py

yes it is only 143 lines long, very confusing.

Posted on
Thu May 07, 2020 7:27 pm
DaveL17 offline
User avatar
Posts: 6739
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Re: Battery Charting Script

I think something strange may be happening with the code that you pasted into the script window. I just copied the script from Github into a new embedded script window, changed the image file save path to Indigo 7.4 for my version, and selected run. The script ran without error and generated an image file to the target folder. Try copying this script instead:

Code: Select all
#! /usr/bin/env python
# -*- coding: utf-8 -*-

try:
    import sys
    import matplotlib.pyplot as plt
    import numpy as np
except ImportError, e:
    sys.exit(u"The matplotlib and numpy modules are required to use this script.")

# =================== User Settings ===================
output_file = '/Library/Application Support/Perceptive Automation/Indigo 7/IndigoWebServer/images/controls/static/battery_test.png'  # Indigo 7 installs

chart_title = 'Battery Health'
x_axis_title = ''
y_axis_title = ''

background_color = '#000000'
chart_height = 4.5
chart_width = 6
font_color = '#FFFFFF'
font_name = 'Lato Light'
font_size = 9
grid_color = '#888888'
grid_style = 'dotted'
show_data_labels = True
title_font_size = 9

battery_full_color = '#0000CC'
battery_caution_color = '#FFFF00'
battery_low_color = '#FF0000'
battery_caution_level = 10
battery_low_level = 5

# =================== kwarg Settings ===================
k_bar_fig = {'align': 'center',
             'alpha': 1.0,
             'height': 0.5,
             'zorder': 3
             }

k_grid_fig = {'which': 'major',
              'color': grid_color,
              'linestyle': grid_style,
              'zorder': 0
              }

k_plot_fig = {'bbox_extra_artists': None,
              'bbox_inches': 'tight',
              'dpi': 100,
              'edgecolor': background_color,
              'facecolor': background_color,
              'format': None,
              'frameon': None,
              'orientation': None,
              'pad_inches': 0.1,
              'papertype': None,
              'transparent': True,
              }

k_title_fig = {'fontname': font_name,
               'fontsize': title_font_size,
               'color': font_color,
               'position': (0.35, 1.0)
               }
# =====================================================

bar_colors = []
device_dict = {}
x_values = []
y_values = []

# Create a dictionary of battery powered devices and their battery levels
try:
    for dev in indigo.devices.itervalues():
        if dev.batteryLevel is not None:
            device_dict[dev.name] = dev.states['batteryLevel']

    if device_dict == {}:
        device_dict['No Battery Devices'] = 0

except Exception, e:
    indigo.server.log(u"Error reading battery devices: %s" % e)

# Parse the battery device dictionary for plotting.
try:
    for key, value in sorted(device_dict.iteritems(), reverse=True):
        try:
            x_values.append(float(value))
        except ValueError:
            x_values.append(0)
        y_values.append(key.replace(' - ', '\n'))  # This line is specific to my install, as I name devices "Room - Device Name"

        # Create a list of colors for the bars based on battery health
        try:
            battery_level = float(value)
        except ValueError:
            battery_level = 0

        if battery_level <= battery_low_level:
            bar_colors.append(battery_low_color)
        elif battery_low_level < battery_level <= battery_caution_level:
            bar_colors.append(battery_caution_color)
        else:
            bar_colors.append(battery_full_color)

except Exception, e:
    indigo.server.log(u"Error parsing chart data: {0}".format(e))

# Create a range of values to plot on the Y axis, since we can't plot on device names.
y_axis = np.arange(len(y_values))

# Plot the figure
plt.figure(figsize=(chart_width, chart_height))

# Adding 1 to the y_axis pushes the bar to spot 1 instead of spot 0 -- getting it off the axis.
plt.barh((y_axis + 1), x_values, color=bar_colors, **k_bar_fig)

if show_data_labels:
    for ii in range(len(y_axis)):
        plt.annotate("%3d" % x_values[ii], xy=((x_values[ii] - 5), (y_axis[ii]) + 0.88), xycoords='data', textcoords='data', fontsize=font_size, color=font_color)

# Chart
plt.title(chart_title, **k_title_fig)
plt.grid(**k_grid_fig)

# X Axis
plt.xticks(fontsize=font_size, color=font_color)
plt.xlabel(x_axis_title, fontsize=font_size, color=font_color)
plt.gca().xaxis.grid(True)
plt.xlim(xmin=0, xmax=100)

# Y Axis
# The addition of 0.05 to the y_axis better centers the labels on the bars
# (for 2-line labels.) For 1 line labels, change 1.05 to 1.0.
plt.yticks((y_axis + 1.05), y_values, fontsize=font_size, color=font_color)
plt.ylabel(y_axis_title, fontsize=font_size, color=font_color)
plt.gca().yaxis.grid(False)
plt.ylim(ymin=0)

# Output the file
plt.savefig(output_file, **k_plot_fig)
plt.close()

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Posted on
Fri May 08, 2020 4:12 pm
mikkyo offline
Posts: 8
Joined: Jan 09, 2017

Re: Battery Charting Script

Got the same error,
Maybe something to do with how Indigo is mapping running scripts in python and outputting the error info?

Posted on
Fri May 08, 2020 4:26 pm
DaveL17 offline
User avatar
Posts: 6739
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Re: Battery Charting Script

What version of Indigo are you running?

Also, please provide the entire error message. There's no print statement in the script, so I need more to go on.

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Posted on
Fri May 08, 2020 8:20 pm
mikkyo offline
Posts: 8
Joined: Jan 09, 2017

Re: Battery Charting Script

I think I figured it out..
leftover file from homebrew.
~/Library/Python/2.7/lib/python/site-packages /homebrew.pth

Removed that and it is working!

Now that I get an image, I assume I have to add a Control Page that uses that image or something?

Posted on
Fri May 08, 2020 9:56 pm
DaveL17 offline
User avatar
Posts: 6739
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Re: Battery Charting Script

Glad to hear you were able to find the cause of the problem. I would likely have never been able to figure out Homebrew was the culprit.

The purpose of the script is to generate an image for control pages, but that's not necessarily the only way to use the product of the script. For example, you could add the image as a shortcut to Safari (for periodic inspection), or email the image to yourself every so often using the Better Email plugin.

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Posted on
Thu Sep 02, 2021 12:55 pm
pxzel offline
Posts: 39
Joined: Jan 19, 2019
Location: Lombard, IL.

Re: Battery Charting Script

Edited: Whats the best way to get the script results (png) automatically sent through email?

Figured it out.... easy as drag and drop file location to email attachment entry.

Posted on
Thu Sep 02, 2021 2:01 pm
DaveL17 offline
User avatar
Posts: 6739
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Re: Battery Charting Script

Glad you were able to figure it out.

[Weirdly, I didn't get a notice of the post at 1:55 CT, but I did get one at 2:45 CT--presumably when you edited your original post.]

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Posted on
Sat Sep 04, 2021 1:32 pm
ryanbuckner offline
Posts: 1072
Joined: Oct 08, 2011
Location: Northern Virginia

Re: Battery Charting Script

DaveL17 wrote:
I think something strange may be happening with the code that you pasted into the script window. I just copied the script from Github into a new embedded script window, changed the image file save path to Indigo 7.4 for my version, and selected run. The script ran without error and generated an image file to the target folder. Try copying this script instead:



This worked for me right out of the box. I just updated for 2021.1 path

1 question, what if I wanted to sort the order by battery level low --> high ?

Posted on
Sat Sep 04, 2021 1:57 pm
ryanbuckner offline
Posts: 1072
Joined: Oct 08, 2011
Location: Northern Virginia

Re: Battery Charting Script

ryanbuckner wrote:
DaveL17 wrote:
I think something strange may be happening with the code that you pasted into the script window. I just copied the script from Github into a new embedded script window, changed the image file save path to Indigo 7.4 for my version, and selected run. The script ran without error and generated an image file to the target folder. Try copying this script instead:



This worked for me right out of the box. I just updated for 2021.1 path

1 question, what if I wanted to sort the order by battery level low --> high ?


I was able to achieve this by editing 1 line:

Code: Select all
# Parse the battery device dictionary for plotting.
try:
    for key, value in sorted(device_dict.iteritems(), key = lambda x : x[1], reverse=True):   # Edited this line to sort by battery level value

Who is online

Users browsing this forum: No registered users and 1 guest