async def test_mfc_t910dw_model(): """Test with valid data from MFC-T910DW printer.""" with open("tests/fixtures/mfc-t910dw.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST, kind="ink") with patch("brother.Brother._get_data", return_value=data), patch("brother.Brother._init_device"): sensors = await brother.async_update() brother.shutdown() assert brother.model == "MFC-T910DW" assert brother.firmware == "M2009041848" assert brother.serial == "serial_number" assert getattr(sensors, "status") == "oczekiwanie" assert getattr(sensors, "page_counter") == 3384 assert getattr(sensors, "color_counter") == 3199 assert getattr(sensors, "b/w_counter") == 185 assert getattr(sensors, "duplex_unit_pages_counter") == 1445 assert getattr(sensors, "black_ink_status") == 1 assert getattr(sensors, "cyan_ink_status") == 1 assert getattr(sensors, "magenta_ink_status") == 1 assert getattr(sensors, "yellow_ink_status") == 1 try: getattr(sensors, "foo") except AttributeError as error: assert str(error) == "No such attribute: foo"
async def main(): host = argv[1] if len(argv) > 1 else HOST kind = argv[2] if len(argv) > 2 else "laser" # argument kind: laser - for laser printer # ink - for inkjet printer external_snmp = False if len(argv) > 3 and argv[3] == "use_external_snmp": external_snmp = True if external_snmp: print("Using external SNMP engine") snmp_engine = hlapi.SnmpEngine() brother = Brother(host, kind=kind, snmp_engine=snmp_engine) else: brother = Brother(host, kind=kind) try: data = await brother.async_update() except (ConnectionError, SnmpError, UnsupportedModel) as error: print(f"{error}") return brother.shutdown() print(f"Model: {brother.model}") print(f"Firmware: {brother.firmware}") if data: print(f"Status: {data.status}") print(f"Serial no: {data.serial}") print(f"Sensors data: {data}")
async def test_hl_l2340dw_model(): """Test with valid data from HL-L2340DW printer with invalid kind.""" with open("tests/fixtures/hl-l2340dw.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST, kind="foo") with patch("brother.Brother._get_data", return_value=data) as mock_update, patch( "brother.datetime", utcnow=Mock(return_value=TEST_TIME)), patch( "brother.Brother._init_device"): sensors = await brother.async_update() assert mock_update.call_count == 1 # second update to test uptime logic sensors = await brother.async_update() assert mock_update.call_count == 2 brother.shutdown() assert brother.model == "HL-L2340DW" assert brother.firmware == "1.17" assert brother.serial == "serial_number" assert getattr(sensors, "status") == "oczekiwanie" assert getattr(sensors, "black_toner") == 80 assert getattr(sensors, "page_counter") == 986 assert getattr(sensors, "uptime").isoformat() == "2019-09-24T12:14:56+00:00"
async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: try: if not host_valid(user_input[CONF_HOST]): raise InvalidHost() brother = Brother(user_input[CONF_HOST]) await brother.async_update() brother.shutdown() await self.async_set_unique_id(brother.serial.lower()) self._abort_if_unique_id_configured() title = f"{brother.model} {brother.serial}" return self.async_create_entry(title=title, data=user_input) except InvalidHost: errors[CONF_HOST] = "wrong_host" except ConnectionError: errors["base"] = "cannot_connect" except SnmpError: errors["base"] = "snmp_error" except UnsupportedModel: return self.async_abort(reason="unsupported_model") return self.async_show_form(step_id="user", data_schema=DATA_SCHEMA, errors=errors)
async def test_dcp_7070dw_model(): """Test with valid data from DCP-7070DW printer with status in Dutch.""" with open("tests/fixtures/dcp-7070dw.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST, kind="laser") with patch("brother.Brother._get_data", return_value=data), patch( "brother.datetime", utcnow=Mock(return_value=TEST_TIME)), patch( "brother.Brother._init_device"): sensors = await brother.async_update() assert brother.model == "DCP-7070DW" assert brother.firmware == "U1307022128VER.J" assert brother.serial == "serial_number" assert getattr(sensors, "status") == "stap. kopieën:01" assert getattr(sensors, "black_toner_remaining") == 72 assert getattr(sensors, "page_counter") == 2652 assert getattr(sensors, "drum_counter") == 1603 assert getattr(sensors, "drum_remaining_life") == 88 assert getattr(sensors, "drum_remaining_pages") == 10397 assert getattr(sensors, "uptime").isoformat() == "2018-11-30T13:43:26+00:00" # test uptime logic, uptime increased by 10 minutes data["1.3.6.1.2.1.1.3.0"] = "2987742561" with patch("brother.Brother._get_data", return_value=data), patch("brother.datetime", utcnow=Mock(return_value=TEST_TIME)): sensors = await brother.async_update() brother.shutdown() assert getattr(sensors, "uptime").isoformat() == "2018-11-30T13:53:26+00:00"
async def test_incomplete_data(): """Test with incomplete data from printer.""" with open("tests/fixtures/incomplete.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST) with patch("brother.Brother._get_data", return_value=data), patch("brother.Brother._init_device"): await brother.async_update() brother.shutdown()
async def test_snmp_error(): """Test with raise SnmpError.""" brother = Brother(HOST) with patch("brother.Brother._init_device", side_effect=SnmpError("SNMP Error")): try: await brother.async_update() except SnmpError as error: assert str(error.status) == "SNMP Error" brother.shutdown()
async def test_invalid_host(): """Test with invalid host.""" brother = Brother(INVALID_HOST) with patch("brother.Brother._init_device", side_effect=ConnectionError("Connection Error")): try: await brother.async_update() except ConnectionError as error: assert str(error) == "Connection Error" brother.shutdown()
async def test_empty_data(): """Test with empty data from printer.""" brother = Brother(HOST) with patch("brother.Brother._get_data", return_value=None), patch("brother.Brother._init_device"): try: await brother.async_update() except SnmpError as error: assert str(error) == "The printer did not return data" brother.shutdown()
async def test_mfc_j680dw_model(): """Test with valid data from MFC-J680DW printer with status in Turkish.""" with open("tests/fixtures/mfc-j680dw.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST, kind="ink") with patch("brother.Brother._get_data", return_value=data), patch("brother.Brother._init_device"): sensors = await brother.async_update() brother.shutdown() assert brother.model == "MFC-J680DW" assert brother.firmware == "U1804191714VER.J" assert brother.serial == "serial_number" assert getattr(sensors, "status") == "uyku" assert getattr(sensors, "black_ink") == 47 assert getattr(sensors, "color_counter") == 491
async def test_dcp_l2540dw_model(): """Test with valid data from DCP-L2540DN printer with status in Russian.""" with open("tests/fixtures/dcp-l2540dn.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST, kind="laser") with patch("brother.Brother._get_data", return_value=data), patch("brother.Brother._init_device"): sensors = await brother.async_update() brother.shutdown() assert brother.model == "DCP-L2540DN" assert brother.firmware == "R1906110243" assert brother.serial == "serial_number" assert getattr(sensors, "status") == "спящий режим" assert getattr(sensors, "black_toner_remaining") == 55 assert getattr(sensors, "page_counter") == 333
async def test_dcp_j132w_model(): """Test with valid data from DCP-J132W printer.""" with open("tests/fixtures/dcp-j132w.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST, kind="ink") with patch("brother.Brother._get_data", return_value=data), patch("brother.Brother._init_device"): sensors = await brother.async_update() brother.shutdown() assert brother.model == "DCP-J132W" assert brother.firmware == "Q1906110144" assert brother.serial == "serial_number" assert getattr(sensors, "status") == "ready" assert getattr(sensors, "black_ink") == 80 assert getattr(sensors, "page_counter") == 879
async def main(): if len(sys.argv) < 2: print(f"Usage: {sys.argv[0]} <hostname> [laser | ink]") sys.exit() host = sys.argv[1] kind = sys.argv[2] if len(sys.argv) > 2 else "laser" brother = Brother(host, kind=kind) try: await brother.async_update() except (ConnectionError, SnmpError, UnsupportedModel) as error: print(f"{error}") return brother.shutdown() if brother.available: print(json.dumps(brother.data, default=str))
async def test_hl_2270dw_model(): """Test with valid data from HL-2270DW printer.""" with open("tests/fixtures/hl-2270dw.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST, kind="laser") brother._counters = False # pylint:disable=protected-access with patch("brother.Brother._get_data", return_value=data), patch("brother.Brother._init_device"): sensors = await brother.async_update() brother.shutdown() assert brother.model == "HL-2270DW" assert brother.firmware == "1.16" assert brother.serial == "serial_number" assert getattr(sensors, "status") == "sleep" assert getattr(sensors, "page_counter") == 4191 assert getattr(sensors, "drum_remaining_pages") == 7809
async def test_dcp_9020cdw_model(): """Test with valid data from DCP-9020CDW printer.""" with open("tests/fixtures/dcp-9020cdw.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST, kind="laser") with patch("brother.Brother._get_data", return_value=data), patch("brother.Brother._init_device"): sensors = await brother.async_update() brother.shutdown() assert brother.model == "DCP-9020CDW" assert brother.firmware == "ZA1811191217" assert brother.serial == "E71833C4J372261" assert getattr(sensors, "status") == "tryb uśpienia" assert getattr(sensors, "cyan_drum_remaining_life") == 68 assert getattr(sensors, "cyan_drum_counter") == 4939 assert getattr(sensors, "cyan_drum_remaining_pages") == 10061
async def test_dcp_l3550cdw_model(): """Test with valid data from DCP-L3550CDW printer.""" with open("tests/fixtures/dcp-l3550cdw.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST) with patch("brother.Brother._get_data", return_value=data), patch("brother.Brother._init_device"): sensors = await brother.async_update() brother.shutdown() assert brother.model == "DCP-L3550CDW" assert brother.firmware == "J1906051424" assert brother.serial == "serial_number" assert getattr(sensors, "status") == "mało toneru (y)" assert getattr(sensors, "black_toner") == 30 assert getattr(sensors, "yellow_toner") == 10 assert getattr(sensors, "magenta_toner") == 10 assert getattr(sensors, "cyan_toner") == 10 assert getattr(sensors, "page_counter") == 1611
async def test_mfc_5490cn_model(): """Test with valid data from MFC-5490CN printer with no charset data.""" with open("tests/fixtures/mfc-5490cn.json", encoding="utf-8") as file: data = json.load(file) brother = Brother(HOST, kind="ink") brother._legacy = True # pylint:disable=protected-access with patch("brother.Brother._get_data", return_value=data), patch( "brother.datetime", utcnow=Mock(return_value=TEST_TIME)), patch( "brother.Brother._init_device"): sensors = await brother.async_update() brother.shutdown() assert brother.model == "MFC-5490CN" assert brother.firmware == "U1005271959VER.E" assert brother.serial == "serial_number" assert getattr(sensors, "status") == "sleep mode" assert getattr(sensors, "page_counter") == 8989 assert getattr(sensors, "uptime").isoformat() == "2019-11-02T23:44:02+00:00"
async def main(): host = argv[1] if len(argv) > 1 else HOST kind = argv[2] if len(argv) > 2 else "laser" # argument kind: laser - for laser printer # ink - for inkjet printer brother = Brother(host, kind=kind) try: await brother.async_update() except (ConnectionError, SnmpError, UnsupportedModel) as error: print(f"{error}") return brother.shutdown() if brother.available: print(f"Data available: {brother.available}") print(f"Model: {brother.model}") print(f"Firmware: {brother.firmware}") if brother.data.get("status"): print(f"Status: {brother.data['status']}") print(f"Serial no: {brother.serial}") print(f"Sensors data: {brother.data}")
class BrotherDataUpdateCoordinator(DataUpdateCoordinator): """Class to manage fetching Brother data from the printer.""" def __init__(self, hass, host, kind): """Initialize.""" self.brother = Brother(host, kind=kind) self._unsub_stop = hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, self._handle_ha_stop) super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL, ) async def _async_update_data(self): """Update data via library.""" # Race condition on shutdown. Stop all the fetches. if self._unsub_stop is None: return None try: await self.brother.async_update() except (ConnectionError, SnmpError, UnsupportedModel) as error: raise UpdateFailed(error) from error return self.brother.data def shutdown(self): """Shutdown the Brother coordinator.""" self._unsub_stop() self._unsub_stop = None self.brother.shutdown() def _handle_ha_stop(self, _): """Handle Home Assistant stopping.""" self.shutdown()