From ac0ca14c349e0d70d9f3a1aeb720f5e31f16d63e Mon Sep 17 00:00:00 2001
From: "Yaroslav Soroko (yaso)" <yaso@odoo.com>
Date: Tue, 11 Oct 2022 14:44:14 +0000
Subject: [PATCH] [FIX] hw_drivers: Printers disconnecting issue fix

This commit aims to solve the reported issue where printers are switching states from "connected" to "disconnected" and stay unreachable for 2 minutes. Now theavailable printers will be searched for multiple times before disconnecting them
task 2891909

Fixes 2687380
Fixes 2856101

closes odoo/odoo#103292

Signed-off-by: Quentin Lejeune (qle) <qle@odoo.com>
---
 .../interfaces/PrinterInterface.py             | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/addons/hw_drivers/iot_handlers/interfaces/PrinterInterface.py b/addons/hw_drivers/iot_handlers/interfaces/PrinterInterface.py
index 501cd740392c..54ba914a4816 100644
--- a/addons/hw_drivers/iot_handlers/interfaces/PrinterInterface.py
+++ b/addons/hw_drivers/iot_handlers/interfaces/PrinterInterface.py
@@ -14,9 +14,10 @@ cups_lock = Lock()  # We can only make one call to Cups at a time
 class PrinterInterface(Interface):
     _loop_delay = 120
     connection_type = 'printer'
+    printer_devices = {}
 
     def get_devices(self):
-        printer_devices = {}
+        discovered_devices = {}
         with cups_lock:
             printers = conn.getPrinters()
             devices = conn.getDevices()
@@ -35,8 +36,19 @@ class PrinterInterface(Interface):
             identifier = self.get_identifier(path)
             device.update({'identifier': identifier})
             device.update({'url': path})
-            printer_devices.update({identifier: device})
-        return printer_devices
+            device.update({'disconnect_counter': 0})
+            discovered_devices.update({identifier: device})
+        self.printer_devices.update(discovered_devices)
+        # Deal with devices which are on the list but were not found during this call of "get_devices"
+        # If they aren't detected 3 times consecutively, remove them from the list of available devices
+        for device in list(self.printer_devices):
+            if not discovered_devices.get(device):
+                disconnect_counter = self.printer_devices.get(device).get('disconnect_counter')
+                if disconnect_counter >= 2:
+                    self.printer_devices.pop(device, None)
+                else:
+                    self.printer_devices[device].update({'disconnect_counter': disconnect_counter + 1})
+        return dict(self.printer_devices)
 
     def get_identifier(self, path):
         if 'uuid=' in path:
-- 
GitLab