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_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"
def add_brother(self): """ Method that collects all the user entered data and then submits it to be entered into the database. """ chairman = '' speaker = '' coordinator = '' first_name = self.line_f_name.displayText() middle_name = self.line_m_name.displayText() last_name = self.line_l_name.displayText() phone = self.line_phone.displayText() email = self.line_email.displayText() # Combo box selection = self.combo_congregation.currentIndex() congregation = self.sorted_list[selection][0] responsibility = self.combo_publisher.itemText( self.combo_publisher.currentIndex()) # Brother's capacity radio buttons if self.check_chairman.isChecked(): chairman = 'True' if self.check_speaker.isChecked(): speaker = 'True' if self.check_talkC.isChecked(): coordinator = 'True' note = self.text_note.toPlainText() new_brother = Brother() new_brother.set_attribute(first_name, middle_name, last_name, email, phone, congregation, responsibility, speaker, chairman, coordinator, note) new_brother.add_brother() self.done(True)
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 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_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_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()
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, )
def populate_brothers(self, option_dic): """ Populate the brother item_list. item_list controls how many rows will be drawn on the table and etc. :param option_dic: A dictionary containing all of the user selected sorting options. """ self.tableWidget.setColumnCount(2) bro = Brother() # Take option_dic and export values of each key to a variable to then be # passed to the SQL command. sort_name = option_dic["Name"] resp = option_dic["Resp"] coord = option_dic["Coord"] cong = option_dic["Cong"] self.tableWidget.clearContents() item_list = bro.populate_table(sort_name, resp, coord, cong) item_list = (list(enumerate(item_list))) self.tableWidget.setRowCount(len(item_list)) # Add brothers from the database into TableWidget. # The brother_ids keeps track of the brothers placed in TableWidget in # the correct order. It's used to know which table ID to use when the # user selects an item in TableWidget. brother_ids = [] for item in item_list: brother_ids.append(item[1][0]) # Format names based on sorting option. if self.options_selected["Name"] == "first_name": # First name , middle name , and last name. name = QtGui.QTableWidgetItem("{} {} {}".format(item[1][1], item[1][2], item[1][3])) else: # Last name, first name, and middle name. name = QtGui.QTableWidgetItem("{}, {} {}".format(item[1][3], item[1][1], item[1][2])) congregation = QtGui.QTableWidgetItem("{Cong}".format(Cong=item[1][ 4])) self.tableWidget.setItem(int(item[0]), 0, name) self.tableWidget.setItem(int(item[0]), 1, congregation) # Return all of the brother database IDs in the correct order based # on the sort applied to BrotherWinow.brother_id_sorted. BrotherWindow.brother_id_sorted = brother_ids
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()
def populate_brothers(self, option_dic): """ Populate the brother item_list. item_list controls how many rows will be drawn on the table and etc. :param option_dic: A dictionary containing all of the user selected sorting options. """ self.tableWidget.setColumnCount(2) bro = Brother() # Take option_dic and export values of each key to a variable to then be # passed to the SQL command. sort_name = option_dic["Name"] resp = option_dic["Resp"] coord = option_dic["Coord"] cong = option_dic["Cong"] self.tableWidget.clearContents() item_list = bro.populate_table(sort_name, resp, coord, cong) item_list = (list(enumerate(item_list))) self.tableWidget.setRowCount(len(item_list)) # Add brothers from the database into TableWidget. # The brother_ids keeps track of the brothers placed in TableWidget in # the correct order. It's used to know which table ID to use when the # user selects an item in TableWidget. brother_ids = [] for item in item_list: brother_ids.append(item[1][0]) # Format names based on sorting option. if self.options_selected["Name"] == "first_name": # First name , middle name , and last name. name = QtGui.QTableWidgetItem("{} {} {}".format( item[1][1], item[1][2], item[1][3])) else: # Last name, first name, and middle name. name = QtGui.QTableWidgetItem("{}, {} {}".format( item[1][3], item[1][1], item[1][2])) congregation = QtGui.QTableWidgetItem( "{Cong}".format(Cong=item[1][4])) self.tableWidget.setItem(int(item[0]), 0, name) self.tableWidget.setItem(int(item[0]), 1, congregation) # Return all of the brother database IDs in the correct order based # on the sort applied to BrotherWinow.brother_id_sorted. BrotherWindow.brother_id_sorted = brother_ids
async def async_step_zeroconf( self, discovery_info: DiscoveryInfoType ) -> FlowResult: """Handle zeroconf discovery.""" # Hostname is format: brother.local. self.host = discovery_info["hostname"].rstrip(".") snmp_engine = get_snmp_engine(self.hass) self.brother = Brother(self.host, snmp_engine=snmp_engine) try: await self.brother.async_update() except (ConnectionError, SnmpError, UnsupportedModel): return self.async_abort(reason="cannot_connect") # Check if already configured await self.async_set_unique_id(self.brother.serial.lower()) self._abort_if_unique_id_configured() self.context.update( { "title_placeholders": { "serial_number": self.brother.serial, "model": self.brother.model, } } ) return await self.async_step_zeroconf_confirm()
async def async_step_zeroconf( self, discovery_info: zeroconf.ZeroconfServiceInfo) -> FlowResult: """Handle zeroconf discovery.""" # Hostname is format: brother.local. self.host = discovery_info[zeroconf.ATTR_HOSTNAME].rstrip(".") # Do not probe the device if the host is already configured self._async_abort_entries_match({CONF_HOST: self.host}) snmp_engine = get_snmp_engine(self.hass) model = discovery_info[zeroconf.ATTR_PROPERTIES].get("product") try: self.brother = Brother(self.host, snmp_engine=snmp_engine, model=model) await self.brother.async_update() except UnsupportedModel: return self.async_abort(reason="unsupported_model") except (ConnectionError, SnmpError): return self.async_abort(reason="cannot_connect") # Check if already configured await self.async_set_unique_id(self.brother.serial.lower()) self._abort_if_unique_id_configured() self.context.update({ "title_placeholders": { "serial_number": self.brother.serial, "model": self.brother.model, } }) return await self.async_step_zeroconf_confirm()
async def async_step_zeroconf(self, discovery_info): """Handle zeroconf discovery.""" if discovery_info is None: return self.async_abort(reason="cannot_connect") if not discovery_info.get( "name") or not discovery_info["name"].startswith("Brother"): return self.async_abort(reason="not_brother_printer") # Hostname is format: brother.local. self.host = discovery_info["hostname"].rstrip(".") snmp_engine = get_snmp_engine(self.hass) self.brother = Brother(self.host, snmp_engine=snmp_engine) try: await self.brother.async_update() except (ConnectionError, SnmpError, UnsupportedModel): return self.async_abort(reason="cannot_connect") # Check if already configured await self.async_set_unique_id(self.brother.serial.lower()) self._abort_if_unique_id_configured() # pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167 self.context.update({ "title_placeholders": { "serial_number": self.brother.serial, "model": self.brother.model, } }) return await self.async_step_zeroconf_confirm()
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_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_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_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 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
def submit_edits(self, row): """ Method that submits user made edits to be committed to the database. All the fields are submitted to the Brother.edit_brother method which will do various checks such as make sure all required fields are entered. Then from there it is passed off to the db module that will cause the database to be modified. :param row: The row (id) in the database that is being modified. """ first_name = self.line_f_name.displayText() middle_name = self.line_m_name.displayText() last_name = self.line_l_name.displayText() phone = self.line_phone.displayText() email = self.line_email.displayText() # Combo box selection = self.combo_congregation.currentIndex() congregation = self.sorted_list[selection][0] responsibility = self.combo_publisher.itemText( self.combo_publisher.currentIndex()) # Capacity radio buttons if self.check_chairman.isChecked(): chairman = 'True' else: chairman = 'False' if self.check_speaker.isChecked(): speaker = 'True' else: speaker = 'Flase' if self.check_talkC.isChecked(): coordinator = 'True' else: coordinator = 'False' note = self.text_note.toPlainText() edit = Brother() edit.set_attribute(first_name, middle_name, last_name, email, phone, congregation, responsibility, speaker, chairman, coordinator, note) edit.edit_brother(row) self.done(True)
def __init__(self, host, kind): """Initialize.""" self._brother = Brother(host, kind=kind) self.host = host self.model = None self.serial = None self.firmware = None self.available = False self.data = {} self.unavailable_logged = False
def __init__(self, hass, host, kind, snmp_engine): """Initialize.""" self.brother = Brother(host, kind=kind, snmp_engine=snmp_engine) super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL, )
async def test_empty_data(): """Test with empty data from printer.""" with patch("brother.Brother._get_data", return_value=None): brother = Brother(HOST) await brother.async_update() assert brother.available == False assert brother.model == None assert brother.firmware == None assert brother.serial == None
async def test_invalid_data(): """Test with invalid data from printer.""" with open("tests/data/invalid.json") as file: data = json.load(file) with patch("brother.Brother._get_data", return_value=data), pytest.raises(UnsupportedModel): brother = Brother(HOST) await brother.async_update()
def __init__(self, opp: OpenPeerPower, host: str, kind: str, snmp_engine: SnmpEngine) -> None: """Initialize.""" self.brother = Brother(host, kind=kind, snmp_engine=snmp_engine) super().__init__( opp, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL, )
async def test_incomplete_data(): """Test with incomplete data from printer.""" with open("tests/data/incomplete.json") as file: data = json.load(file) with patch("brother.Brother._get_data", return_value=data): brother = Brother(HOST) await brother.async_update() assert brother.available == True
def __init__(self, hass: HomeAssistant, host: str, kind: str, snmp_engine: SnmpEngine) -> None: """Initialize.""" self.brother = Brother(host, kind=kind, snmp_engine=snmp_engine) super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL, )
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 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
def add_brother(self): """ Method that collects all the user entered data and then submits it to be entered into the database. """ chairman = '' speaker = '' coordinator = '' first_name = self.line_f_name.displayText() middle_name = self.line_m_name.displayText() last_name = self.line_l_name.displayText() phone = self.line_phone.displayText() email = self.line_email.displayText() # Combo box selection = self.combo_congregation.currentIndex() congregation = self.sorted_list[selection][0] responsibility = self.combo_publisher.itemText( self.combo_publisher.currentIndex()) # Brother's capacity radio buttons if self.check_chairman.isChecked(): chairman = 'True' if self.check_speaker.isChecked(): speaker = 'True' if self.check_talkC.isChecked(): coordinator = 'True' note = self.text_note.toPlainText() new_brother = Brother() new_brother.set_attribute(first_name, middle_name, last_name, email, phone, congregation, responsibility, speaker, chairman, coordinator, note) new_brother.add_brother() self.done(True)
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}")