-1

So I wrote this python code on my RPI to create a digital poster that talks with my crestron control processor. For some reason my code stops responding after a while. I dont know why. I dont know if my Pi is going to sleep but if anyone could point out anything in my code that could cause this please let me know.

EDIT: I FIGURED IT OUT ON MY OWN. Many thanks to everyone who commented.

I was creating a new FBI process every time i went through the loop, and i ended up using up all of the Pi's RAM until it came to a halt because it didnt have any left. I now kill the FBI process after loading the image which fixed that. Thanks for everyones help.

My Functions and Setup Stuff:

import socket
import os
import thread
import sys
import urllib
from time import ctime
from PIL import Image
import time
import random
import logging

frameBufferCommand = "sudo fbi -a -T 1 -d /dev/fb0 -noverbose "
moviePosterLocation = "/home/pi/movieposters/"
openBlackImage = "/home/pi/movieposters/special/black.jpg"
killFrameBuffer = "sudo killall fbi"
turnOffScreen = "sudo /opt/vc/bin/tvservice -o"
turnOnScreen = "sudo /opt/vc/bin/tvservice -p"

def splitString(input): 
    stringList = input.split("/x00/") 
    return stringList

def displayRandomPoster():
    displayingPoster = False
    fileCount = next(os.walk(moviePosterLocation))[2] #get the number of available posters
    print('Current # Of Posters in Directory: ' + str(len(fileCount)))

    attemptNumber = 0

    while not displayingPoster:
        posterToDisplay = random.randint(0, len(fileCount))
        print('Trying To Display A Random Poster')
        attemptNumber += 1

        try:
            image = Image.open(moviePosterLocation + fileCount[posterToDisplay]) #open the current image
            width, height = image.size
        except IndexError as msg:
            print("encountered an IndexError while opening an image")
            width = 0
            height = 0      
        except IOError as msg:
            print(msg)
        try:
            conn.send(msg)
        except socket.error as msg:
            print("Socket Error")


    if width > height:
        if attemptNumber > 5:
            print("Too Many Attempts, Stopping")
            break
        else:
            print("We Think This Isnt A Poster, Trying Again")               
            continue    
    else:
        try:
            conn.send("  Displaying Poster: " + str(fileCount[posterToDisplay]))
        except socket.error as msg:
            print msg                
        os.system(frameBufferCommand + moviePosterLocation + fileCount[posterToDisplay])
        displayingPoster = True
        return

The thread that is listening, and the main loop:

#-- CLIENT THREAD --

def client(conn):
    try:
        conn.send("Connected With Raspberry Pi")
        os.system(frameBufferCommand + openBlackImage)
    except socket.Error as msg:
        print(msg)

print(str(bindSuccess))

while 1:    
    dataReceived = conn.recv(1024)
    reply = "OK.. "
    conn.send(reply + dataReceived)
    dataList = splitString(dataReceived)
    print(dataList)
    if dataList[6] == "": 
        print("dataList[6] is empty, displaying a random poster")
        displayRandomPoster()
    else: 
        try:    
            moviePosterURL = dataList[6]            
            splitPosterURL = moviePosterURL.split("%")            
            moviePosterFilename = splitPosterURL[7]                
            urllib.urlretrieve(moviePosterURL, moviePosterLocation + moviePosterFilename)                
            conn.send("XBMC Movie Poster Downloading")
            conn.send("Movie Poster saved as: " + moviePosterLocation + moviePosterFilename)
            print("Movie Poster saved as: " + moviePosterLocation + moviePosterFilename)                            
        except socket.error:
            print("Encountered Socket Error While Downloading Poster - Line 80")            
        try:
            os.system(frameBufferCommand + moviePosterLocation + moviePosterFilename)
            print('Opening Downloaded Poster')
        except OSError as msg:
            print(str(msg[0]) + str(msg[1]))
    if not dataReceived:
        break
    time.sleep(1)


#-- MAIN FUNCTION --

host = ''
communicationPort = 5005

bindSuccess = False

crestronSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("Socket Created Successfully")

try:
    crestronSocket.bind((host, communicationPort))
    bindSuccess = True
except socket.Error as msg: 
    bindSuccess = False
    print("Socket Bind Error" + msg)
    sys.exit()

crestronSocket.listen(1)
print("Crestron Socket Listening")

while bindSuccess == True:
    #wait to accept a connection - blocking call
    conn, addr = crestronSocket.accept()
    print('Connected with Client: ' + addr[0] + ':' + str(addr[1]))      
    thread.start_new_thread(client , (conn,))
crestronSocket.close()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Way too much code. Try to trim it down to a [MVCE](http://stackoverflow.com/help/mcve). – Lex Scarisbrick Jun 07 '16 at 02:02
  • @LexScarisbrick do you mean for debugging purposes? – ryanjblajda Jun 07 '16 at 02:12
  • Please read the link in my other comment. The gist is the more code people have to sift through, the less likely you are to get an answer. – Lex Scarisbrick Jun 08 '16 at 05:07
  • "Code stops responding" - do you mean your server won't accept new connections, or that an existing connection stops working? In the ConnectionThread function, you should put some print statement where it exits and closes the connection, perhaps your code is going there? Otherwise yes far far far far too much code for anyone to easily grok in detail. Also far too application-specific - it is far easiest for someone to check your code out if they can run it themselves, so put yourself in a potential answerer's position, someone who has none of the images/bits you have available to you. – DisappointedByUnaccountableMod Jun 08 '16 at 06:05
  • @barny an existing connection stops responding. however i think i may have figured it out. i was just running the script as i was watching TV and i think i may have found the issue. In the displayRandomPoster() function i experienced an IOError because it tried to open a file that didnt save properly. I think thats the issue. But im not sure. – ryanjblajda Jun 08 '16 at 22:40
  • You should actually *use* the logging module. `tail -f ` or even better, install [lnav](http://lnav.org/) and `lnav `. If you've done something like `logger = logging.getLogger('postergen')` then you can do `logger.exception('Something bad happened')` in your exception handler and it will helpfully log the stack trace for you. Really all of your print statements should be `logger.debug` or `.info`. If you want to display to the console, just add a [streamHandler](https://docs.python.org/3/library/logging.handlers.html#logging.StreamHandler) – Wayne Werner Jul 15 '16 at 16:51
  • @WayneWerner I figured out what the issue was yesterday. I was creating a new FBI process every time I went through the loop, so it kept eating up ram incrementally until there was none left and the pi screeched to a halt. – ryanjblajda Jul 16 '16 at 17:53

1 Answers1

0

I was creating a new FBI process every time i went through the loop, and i ended up using up all of the Pi's RAM until it came to a halt because it didnt have any left. I now kill the FBI process after loading the image which fixed that. Thanks for everyones help.

I also figured out some other things that make it operate better/more seamlessly.