Page 1 of 1

What is the simple way to write a variable to a text file?

PostPosted: Tue Nov 18, 2014 10:42 am
by jfeingold
Each time the variable changes I'd like its value written to a file that I can later open in Excel.

Is there a really easy way to do this? thanks, John.

(my usage would be something like monitoring the internal temperature of my weekend home every hour, storing the text file in dropbox, and occasionally opening it remotely and graphing it in Excel.. I'm looking for a simple solution, and reliable.

Re: What is the simple way to write a variable to a text fil

PostPosted: Tue Nov 18, 2014 11:48 am
by autolog
You could set-up an Action Group to execute a python script to be triggered when the variable changes.
The following code will write to a file:
Code: Select all
loggedDateTime = indigo.server.getTime().strftime("%Y-%m-%d %H:%M:%S")
temperature = indigo.variables[<YOUR VARIABLE ID>].value

file = open("/Users/<YOUR USER ID>/Documents/temperatureLog.csv","a")
file.write(str("%s,%s\n" % (loggedDateTime, temperature)))
file.close()
This will append a line to a csv file (in this case "temperatureLog.csv" in the Documents folder) the date and time from the server (e.g. "2014-11-18 17:37:37") and the value of the variable.

See here for different formats for the date and time.

Hope this helps :)

Re: What is the simple way to write a variable to a text fil

PostPosted: Tue Nov 18, 2014 12:41 pm
by DaveL17
@autolog beat me to it.

Here is a copy of a script that I use to write data to a CSV file for use with Gnuplot. The embedded formatting is for my benefit, but once you get the hang of this stuff, changing it comes pretty easily.

Code: Select all
#! /usr/bin/env python2.5
# -*- coding: utf-8 -*-
 
import os.path
from os import system
 
csvFilePath = "/Users/USERNAME/Dropbox/Public/barometric.csv"
csvHeaders = "Pressure,Pressure" + "\n"
csvColors = "Colors,Blue" + "\n"
dateTime = str(indigo.server.getTime())
 
pressure = (indigo.devices[1899035475].states["pressure"])
pressure = float(pressure)
pressure = str(pressure)
 
# Check and see if the file exists. If not, create and write the headers.
if not os.path.isfile(csvFilePath):
    csvFile = open(csvFilePath, "a")
    csvFile.write(csvHeaders)
    csvFile.write(csvColors)
 
# Write new values to the file.
csvFile = open(csvFilePath, "a")
element = dateTime + "," + pressure + "\n"
csvFile.write(element)
 
# Close the file.
csvFile.close()

Re: What is the simple way to write a variable to a text fil

PostPosted: Tue Nov 18, 2014 12:45 pm
by jfeingold
thank you both very much!