New Deluge Sensor Config

Is your switch working? I can pause (Turn off the switch) but the switch stays stuck in the on position even though it pauses deluge. If I manually go in and set the state to off, I can toggle the switch and the downloads resume.

Also, my “deluge status” does update. It changes from “up/down” to “idle” when nothing is downloading or uploading.

I had the same issue. It was because I had an existing automation that was active against all switches. Try commenting out any automation and see if it works.

EDIT: actually maybe not, it’s stopped working again… hmm

I had this same issue and I had to add a user to my deluge auth file.
I added this line (username:password - change if you want):

deluge:deluge:10

This was on Windows and the auth file was located here: C:\Users\Server\AppData\Roaming\deluge

Once I did this I restarted Deluge then restarted HA - worked a treat.

Hope this helps.

1 Like

hi Bit-River

Could you please provide the complete code of the group as you did to Deluge - I also want it to be displayed as nicely as you have

Hi,

They’ll work as shown, just copy & paste each section into customize.yaml, and group.yaml respectively :slight_smile:

The deluge_status sensor is still not worth bothering with, and it looks like some of the optional settings are really mandatory, anyway here’s a working sensors.yaml example that will work with the customize & group settings:

  - platform: deluge
    host: 192.168.1.100
    port: 58846
    username: "deluge"
    password: "deluge"
    monitored_variables:
      - 'current_status'
      - 'download_speed'
      - 'upload_speed'

Change the host, username & password as needed, the port value is standard as are the monitored variables.

The deluge switch is here:

I’ve been thinking of volunteering to update the documentation, so I think I’ll start with this component. And double-check which parts are really mandatory and optional.

Cheers for the reminder :slight_smile:

Thanks for the answer - sorry it took me a long time to answer.

I tried what you said and have a problem - you can see in the attached code

2018-05-16 09:23:42 WARNING (MainThread) [homeassistant.components.switch] Setup of platform deluge is taking over 10 seconds.

2018-05-16 09:23:52 ERROR (MainThread) [homeassistant.components.switch] Error while setting up platform deluge
Traceback (most recent call last):
File “/srv/homeassistant/lib/python3.6/site-packages/homeassistant/helpers/entity_platform.py”, line 129, in _async_setup_platform
SLOW_SETUP_MAX_WAIT, loop=hass.loop)
File “/usr/lib/python3.6/asyncio/tasks.py”, line 358, in wait_for
return fut.result()
File “/usr/lib/python3.6/concurrent/futures/thread.py”, line 56, in run
result = self.fn(*self.args, **self.kwargs)
File “/srv/homeassistant/lib/python3.6/site-packages/homeassistant/components/switch/deluge.py”, line 48, in setup_platform
deluge_api.connect()
File “/srv/homeassistant/lib/python3.6/site-packages/deluge_client/client.py”, line 63, in connect
self._connect()
File “/srv/homeassistant/lib/python3.6/site-packages/deluge_client/client.py”, line 77, in _connect
self._socket.connect((self.host, self.port))
File “/usr/lib/python3.6/ssl.py”, line 1100, in connect
self._real_connect(addr, False)
File “/usr/lib/python3.6/ssl.py”, line 1091, in _real_connect
self.do_handshake()
File “/usr/lib/python3.6/ssl.py”, line 1068, in do_handshake
self._sslobj.do_handshake()
File “/usr/lib/python3.6/ssl.py”, line 689, in do_handshake
self._sslobj.do_handshake()

Hi all,

Got it working once I modified the auth file.
deluge%20sensor

Was looking into this myself and found on the deluge support page all about authentication.

on linux based system (Im using a PI as a torrent box).

sudo nano .config/deluge/auth

add new line and add the following

deluge:deluge:10

or whatever user pass u choose.

save the file with CTRL+x , y ENTER.

deluge%20auth

reboot system and check the pi sensor on home assistant (reboot HA as well)

Check out my torrent server box tutorial.

GitHub
MY TORRENT MEDIA SERVER TUTORIAL

From Deluge Support

Authentication

The daemon looks at the file ​<config folder>/auth for doing authentication.

The format of this file is straightforward, each line contains a username:password:level tuple in plaintext.

There should always be a ‘localclient’ entry for use by the UIs running locally by your user.

Note: If you do not have an auth file in your config folder, first run the daemon to have it created for you.

Deluge 1.2.0 introduces different levels of authentication:

Level Name Level Value
None 0
Read Only 1
Normal 5
Admin 10

Note: In Deluge 1.3.3 authentication levels don’t do anything. In the future they will. In git master there is a multiuser option that makes use of authentication levels.

Example of an auth file:

localclient:a7bef72a890:10
andrew:password:10
user3:anotherpass:5

Example of adding a new user under Linux:

echo "username:password:level" &gt;&gt; ~/.config/deluge/auth

Info sourced from https://dev.deluge-torrent.org/wiki/UserGuide/Authentication

1 Like

I tried getting this to work however as I added a new user under the auth file however I am still getting errors. I am using unraid docker for home assistant and deluge. Any advice?

Tue Feb 26 2019 17:42:26 GMT-0500 (Eastern Standard Time)
Error while setting up platform deluge
Traceback (most recent call last):
  File "/usr/src/app/homeassistant/helpers/entity_platform.py", line 128, in _async_setup_platform
    SLOW_SETUP_MAX_WAIT, loop=hass.loop)
  File "/usr/local/lib/python3.7/asyncio/tasks.py", line 416, in wait_for
    return fut.result()
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/app/homeassistant/components/sensor/deluge.py", line 57, in setup_platform
    deluge_api.connect()
  File "/usr/local/lib/python3.7/site-packages/deluge_client/client.py", line 63, in connect
    self._connect()
  File "/usr/local/lib/python3.7/site-packages/deluge_client/client.py", line 77, in _connect
    self._socket.connect((self.host, self.port))
  File "/usr/local/lib/python3.7/ssl.py", line 1150, in connect
    self._real_connect(addr, False)
  File "/usr/local/lib/python3.7/ssl.py", line 1141, in _real_connect
    self.do_handshake()
  File "/usr/local/lib/python3.7/ssl.py", line 1117, in do_handshake
    self._sslobj.do_handshake()
socket.timeout: _ssl.c:1039: The handshake operation timed out
1 Like

Any updates on that? I’m currently facing the same issue as grangemd - I set up a new user in deluge, I’m running it on port 8112.

Error while setting up platform deluge
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 126, in _async_setup_platform
    SLOW_SETUP_MAX_WAIT)
  File "/usr/local/lib/python3.7/asyncio/tasks.py", line 442, in wait_for
    return fut.result()
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/homeassistant/homeassistant/components/deluge/sensor.py", line 50, in setup_platform
    deluge_api.connect()
  File "/usr/local/lib/python3.7/site-packages/deluge_client/client.py", line 78, in connect
    self._connect()
  File "/usr/local/lib/python3.7/site-packages/deluge_client/client.py", line 92, in _connect
    self._socket.connect((self.host, self.port))
  File "/usr/local/lib/python3.7/ssl.py", line 1172, in connect
    self._real_connect(addr, False)
  File "/usr/local/lib/python3.7/ssl.py", line 1163, in _real_connect
    self.do_handshake()
  File "/usr/local/lib/python3.7/ssl.py", line 1139, in do_handshake
    self._sslobj.do_handshake()
socket.timeout: _ssl.c:1059: The handshake operation timed out
sensor:
  - platform: deluge
    host: 192.168.178.xx
    port: 8112
    username: "deluge"
    password: "deluge"
    monitored_variables:
      - 'current_status'
      - 'download_speed'
      - 'upload_speed'

Did you ever get this working? I had it working a while ago, but decided to reformat my computer and after reinstalling Windows (and Deluge) I’m getting the same errors that you were.

Someone ever figured this out? i am facing the same issue. I try connecting to the deamon… remote is enabled in webinterface … I run deluge with vpn as docker image and port are exposed… my deamon config looks like this:

image

Wish I could say I’ve had some luck, but I haven’t. I’ve given up on it for now until I have time to figure it out, or find an alternative.

Thanks for your response… maybe the dev could throw an eye on it and explain exactly how to set this up as it seems docs are outdated/ wrong?

i think my problem was that my firewall was blocking the connection. try disabling firewall and restarting home assistant. maybe PC too.

Hi all,

I’ve been struggling getting the deluge integration to work, so I wrote an appdaemon script which monitors the download and upload speeds as well as torrent status (# of active, seeding, paused, queued, etc torrents). Idk if anyone has gotten the integration to work, but since it offers only speed monitoring, this was not sufficient in my case. Anyhow below is the code I wrote and can be easily extended to monitor additional variables of choice or even to actively modify torrent conditions (set speed limits, pause them etc.).

import hassapi as hass
import requests
from datetime import datetime

class Deluge(hass.Hass):
    prefix = 'deluge_'
    url = 'http://host-ip:8112/json'    
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
        }
    cookies = None
    handle = None
    
    def login(self):
        body = {
            "method": "auth.login", 
            "params": ["deluge"], 
            "id": 2
        }
        response = requests.post(
            self.url,
            json=body,
            headers=self.headers,
        )
        json_response = response.json()
        if(json_response['result']):
            return response.cookies
        else:
            self.log('Deluge: could not log in!')
            return json_response['result']

    def initialize(self):
        self.log("Starting Deluge")
        tm = datetime.now()
        if self.handle != None:
            self.handle = self.run_minutely(self.runMain, tm)
        else:
            self.cancel_timer(self.handle)
            self.handle = self.run_minutely(self.runMain, tm)
        

    def runMain(self, kwargs):
        if(self.isConnected()):
            res = self.updateWebUI()
            params = self.getParams(res)
            self.updateHAStates(params)
            self.log('Updated HA...')
        else:
            self.log('Connecting...')
            cookie = self.login()
            if(cookie):
                self.cookies = cookie

    def isConnected(self):
        body_con = {
            "method": "web.connected", 
            "params": [], 
            "id": 2
        }
        response = requests.post(
            self.url,
            cookies=self.cookies,
            json=body_con,
            headers=self.headers
        )
        json_response = response.json()
        return json_response['result']

    def updateWebUI(self):
        body_ui = {
            "method": "web.update_ui", 
            "params": [{},None], 
            "id": 2
        }
        response = requests.post(
            self.url,
            cookies=self.cookies,
            json=body_ui,
            headers=self.headers
        )
        json_response = response.json()
        return json_response['result']

    def getParams(self,res):
        dl = float(res['stats']['download_rate'])/1024
        ul = float(res['stats']['upload_rate'])/1024
        torrents_all = res['filters']['state'][0][1]
        torrents_active = res['filters']['state'][1][1]
        torrents_downloading = res['filters']['state'][4][1]
        torrents_seeding = res['filters']['state'][5][1]
        torrents_paused = res['filters']['state'][6][1]
        torrents_queued = res['filters']['state'][8][1]
        return {'dl': dl,
                'ul': ul,
                'torrents_all':torrents_all,
                'torrents_active':torrents_active,
                'torrents_downloading':torrents_downloading,
                'torrents_seeding':torrents_seeding,
                'torrents_paused':torrents_paused,
                'torrents_queued':torrents_queued
                }

    def updateHAStates(self,params):
        for ix,e in params.items():
            self.set_state("input_number."+self.prefix+ix, state=e)

The only things that you need to change in the script is the host-ip of the device running deluge and the password to the web-ui. Also you need to have the web-ui daemon running. The script runs minutely and upon completion will add a number of variables in the form of “input_number.deluge_variables” for download and upload speed and torrent statuses. Those can can be integrated within a visualization as such:
image

edit: as I was using the code, I noticed some inefficiencies and updated the code here with the latest revision.

Nice idea …I was thinking there would be something similar for qBittorrent with torrent names like for transmission add-on

Hi,

Great idea,

How do you achieve 2 lines in the sensor card?

I installed the standard deluge yesterday, works fine, but quite tricky to achieve through configuration, so I first checked if I could access deluge daemon from another computer, fixed all issues with firewall and public/private network, then works fine, for the limited options it provides…

Therefore looking to implement your script too!

Thanks

Hi, my script has changed a bit. Now I’m using the RPC API instead of the Web API as I found it to be more reliable. The Web API would often freeze and Appdaemon won’t be able to reconnect without restarting. Using the RPC API has been working without any hiccups for over a month now. Below is the updated and much cleaner looking script.

The code below returns the current upload/download speed from deluge as well as the number of torrents with the status of: ‘downloading’, ‘paused’, ‘seeding’, ‘queued’, ‘active’.

As to how to display two entities within the same chart, you can check here: History Graph Card - Home Assistant. Cheers.

import hassapi as hass
from deluge_client import DelugeRPCClient
import pytz
import datetime

class DelugeMonitor(hass.Hass):
    #Deluge params
    deluge_ip = '192.168.0.0' #host ip
    deluge_port = 58846 #deluge RPC port. needs to be exposed
    deluge_username = 'xxx' #username
    deluge_password = 'xxx' #password
    #HA params
    prefix = 'deluge_'
    #Timezone
    tz = pytz.timezone('Europe/Amsterdam')
    handle = None
	
    def initialize(self):
        self.log("Starting Deluge")
        if self.handle != None:
            self.handle = self.run_every(self.runMain, "now", 10)
        else:
            self.cancel_timer(self.handle)
            self.handle = self.run_every(self.runMain, "now", 10)

    def runMain(self, kwargs):
        speed,status = self.fetchData()
        self.updateSpeedState(speed)
        self.updateTorrentState(status)
        #last updated
        self.set_state("sensor."+self.prefix+"last_updated", state=datetime.datetime.now(self.tz))
        self.log(self.handle)

    def fetchData(self):
        status = {'downloading':0, 'paused':0, 'seeding':0, 'queued':0, 'active':0}
        speed = {'download':0,'upload':0}
        with DelugeRPCClient(self.deluge_ip, port=self.deluge_port, username=self.deluge_username, password=self.deluge_password) as client:
            torrents_list = client.call('core.get_torrents_status', {}, [])
            status['all'] = len(torrents_list)
            for torrent_id, torrent_data in torrents_list.items():
                status[torrent_data[b'state'].decode().lower()] += 1
                if torrent_data[b'peers']:
                    status['active'] += 1
                for peer in torrent_data[b'peers']:
                    speed['upload'] += peer[b'up_speed']
                    speed['download'] += peer[b'down_speed']
            speed['upload'] = speed['upload']/1024
            speed['download'] = speed['download']/1024
        return speed,status

    def updateSpeedState(self, speed):
        for ix,e in speed.items():
            self.set_state("sensor."+self.prefix+ix, state=e, attributes = {"unit_of_measurement": "KB"})
    def updateTorrentState(self, torrent):
        for ix,e in torrent.items():
            self.set_state("sensor."+self.prefix+ix, state=e, attributes = {"unit_of_measurement": "#"})

Hi, Do i just copy the contents into a new file called Appdaemon_Deluge.py, change the

  • deluge_ip

  • deluge_username

  • deluge_password

and save this file in /config/appdaemon/apps/appdaemon-deluge folder.

Restart home assistant.

Do i need to do anything else?

Sorry to bump this from the dead, but I can’t find reference to the deluge_client module anywhere online. Am I missing something to get this working? Right now, it’s spitting an error that it doesn’t recognize the module.

Figured it out. Needed to add deluge-client to the list of Python packages installed on container start.