Tuesday, April 29, 2014

Pi-Side Script

As of right now, we are hosting our database on a central server.  Each PI needs to be able to connect to that database to check if it needs to turn on or off any of its lights.  We ran into some troubles writing the Python script that would accomplish this.

The script was not very long, and was laid out in the following manner.
  1. Establish a connection with the database.
  2. Query the database to check what state of the lights should be.
  3. Check the current state of the lights.
  4. Make any changes to the state of the lights if necessary.
  5. Repeat.
We had no problems except for steps number 3 and 4.  We were using a subprocess call to run a bash command that read in the current state of all our lights.  All we needed was a 1 or 0 to know if the lights was on of off, respectively.  After some time spent troubleshooting, we discovered that all the lights were always being read as off.

As it turns out, the subprocess call() function only returns if the call was successful or not.  Basically in layman's terms our Python script was telling bash to do something, then turning around and giving us a thumbs up that bash successfully did it.  We wanted to know the result of the command, not just that it was being done.

Well, the information we wanted from the command was being sent to stdout.  So how do we get that information into a variable in our script so we can make use of it?  File redirection.

What felt maybe a little dirty, and still looks a little strange perhaps, turned out to work pretty well.  We redirected stdout to a file in our current directory.  Then we had python jump into the file and read what was written there.  Finally, we had the information we needed!  That took care of most of our problems.

There was still a minor problem afterwords with step number 5.  In our script we are essentially running a while( true ) loop, and constantly checking the database/current-state and making changes if necessary with a few if statements.  The problem we ran into was because in Python you don't create your own data types.  You just say var = <whatever>.  Well, the information we were reading from our file was either a 0 or a 1.  A simple int.  Because it was coming from a file however, Python made it into a string.  In our if statements when we compared our string information to an int, we would get the wrong response.  It was a simple fix, simply casting the string to an int, but a problem that took a little bit of time to locate and really showed our inexperience with Python.

No comments:

Post a Comment