armyofme
Posts: 41
Joined: Sat Jan 12, 2013 11:28 am

Python script crashes if it can't connect

Fri Aug 30, 2019 9:56 am

I set up a touchphat hat which adds some buttons to my Pi zero and it works well on the whole. The only issue I have with it is the Python script that works with it. My script switches on and off my amplifier over Telnet and this works well most of the time. But if for some reason there is a problem with the amp...it could be that the telnet session hadn't closed properly or that the amp is powered off for some reason...then the script exits with an error.

Is there anyway I can add to the code in the script and tell it to carry on even if there is a problem connecting over telnet? Tell it to just ignore the issue. Otherwise I have to get my laptop, log into the pi zero and restart the script....which is obviously not ideal when the idea is to simplify the processes with buttons and no screen.

Here is my script:

Code: Select all

#!/usr/bin/env python

import signal
import time
import touchphat
import os
import telnetlib
from kodijson import Kodi
#from time import sleep

my_kodi = Kodi('http://192.168.0.8:8080/jsonrpc')
tn = telnetlib.Telnet('192.168.0.2')

@touchphat.on_release(['A'])
def handle_touch(event):
    print("Kitchen Amp Off")
    time.sleep(.1)

    tn.close()
    time.sleep(.2)
    tn.open('192.168.0.2')
    tn.write("ST04OFF\r\n")
    tn.close()
    time.sleep(.2)

@touchphat.on_touch(['A'])
def handle_touch(event):
    print("Kitchen Room Amp On")
    my_kodi.Settings.SetSettingValue({ "setting":"audiooutput.audiodevice","value":"ALSA:sysdefault:CARD=IQaudIODAC" })
    time.sleep(.1)

   tn.close()
    time.sleep(.2)
    tn.open('192.168.0.2')
    tn.write("ST04ASIG\r\n")
    tn.close()
    time.sleep(.2)

signal.pause()

And here is the error message I get when the script has 'crashed':

Code: Select all

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/dist-packages/cap1xxx.py", line 231, in run
    if self.todo() == False:
  File "/usr/lib/python2.7/dist-packages/cap1xxx.py", line 457, in _poll
    self._handle_alert()
  File "/usr/lib/python2.7/dist-packages/cap1xxx.py", line 450, in _handle_alert
    self._trigger_handler(x, inputs[x])
  File "/usr/lib/python2.7/dist-packages/cap1xxx.py", line 464, in _trigger_handler
    self.handlers[event][channel](CapTouchEvent(channel, event, self.input_delta                                                                                                             [channel]))
  File "/usr/lib/python2.7/dist-packages/touchphat/__init__.py", line 103, in _h                                                                                                             andle_press
    _on_press[channel](event)
  File "kitchen.py", line 72, in handle_touch
    my_kodi.Settings.SetSettingValue({ "setting":"audiooutput.audiodevice","valu                                                                                                             e":"ALSA:sysdefault:CARD=IQaudIODAC" })
  File "/home/pi/.local/lib/python2.7/site-packages/kodijson/kodijson.py", line                                                                                                              121, in hook
    return self.kodi.execute(kodimethod, *args, **kwargs)
  File "/home/pi/.local/lib/python2.7/site-packages/kodijson/kodijson.py", line  71, in execute
    auth=(self.username, self.password))
  File "/home/pi/.local/lib/python2.7/site-packages/requests/api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/home/pi/.local/lib/python2.7/site-packages/requests/api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "/home/pi/.local/lib/python2.7/site-packages/requests/sessions.py", line                                                                                                              508, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/pi/.local/lib/python2.7/site-packages/requests/sessions.py", line                                                                                                              618, in send
    r = adapter.send(request, **kwargs)
  File "/home/pi/.local/lib/python2.7/site-packages/requests/adapters.py", line                                                                                                              508, in send
    raise ConnectionError(e, request=request)
ConnectionError: HTTPConnectionPool(host='192.168.0.8', port=8080): Max retries                                                                                                              exceeded with url: /jsonrpc (Caused by NewConnectionError('<urllib3.connection.H                                                                                                             TTPConnection object at 0xb5a97790>: Failed to establish a new connection: [Errno 111] Connection refused',))

^CTraceback (most recent call last):
  File "kitchen.py", line 149, in <module>
    signal.pause()

User avatar
MrYsLab
Posts: 376
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: Python script crashes if it can't connect

Fri Aug 30, 2019 12:30 pm

Take a look at this article on exceptions https://realpython.com/python-exceptions/, especially the "The try and except Block: Handling Exceptions" section. Also, I do not see a signal handler or where you are setting up which signals to trap. This article may help with this https://pymotw.com/3/signal/.

armyofme
Posts: 41
Joined: Sat Jan 12, 2013 11:28 am

Re: Python script crashes if it can't connect

Fri Aug 30, 2019 3:48 pm

Thank you MrYsLab ever so much! That link really helped and I seemed to have solved my problem! :)

Now my code is:

Code: Select all

@touchphat.on_release(['B'])
def handle_touch(event):
    print ("Party Time")
    try:
        my_kodi.Player.Open({"item":{"partymode":"music"}})
    except:
        pass
And so far....so good!

armyofme
Posts: 41
Joined: Sat Jan 12, 2013 11:28 am

Re: Python script crashes if it can't connect

Fri Aug 30, 2019 4:26 pm

And so I rejoiced too soon! My problem is mostly solved. The only issue is with buttons I use for the amp where they have a command linked to each press eg ontouch switches the amp on and then onrelease switches it off, so one button does both off and on. Well now the when I press the relevant button it does both! I suspect it's because the 'pass' bit in the code passes straight on to the next thing without stopping? Maybe?

Here's the relevant part in the script:

Code: Select all

@touchphat.on_release(['A'])
def handle_touch(event):
    print("Kitchen Amp Off")
    try:
        time.sleep(.1)
        tn.close()
        time.sleep(.2)
        tn.open('192.168.0.2')
        tn.write("ST04OFF\r\n")
        tn.close()
        time.sleep(.2)
    except:
        pass

@touchphat.on_touch(['A'])
def handle_touch(event):
    print("Kitchen Room Amp On")
    try:
        my_kodi.Settings.SetSettingValue({ "setting":"audiooutput.audiodevice","value":"ALSA:sysdefault:CARD=IQaudIODAC" })
        time.sleep(.1)
        tn.close()
        time.sleep(.2)
        tn.open('192.168.0.2')
        tn.write("ST04ASIG\r\n")
        tn.close()
        time.sleep(.2)
    except:
        pass

armyofme
Posts: 41
Joined: Sat Jan 12, 2013 11:28 am

Re: Python script crashes if it can't connect

Fri Aug 30, 2019 4:56 pm

I put a 'time.sleep(.2)' after the 'pass' and that seems to have stopped the problem :)

Return to “Python”