id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
227,300
nabla-c0d3/sslyze
sslyze/plugins/plugins_repository.py
PluginsRepository.get_plugin_class_for_command
def get_plugin_class_for_command(self, scan_command: PluginScanCommand) -> Type[Plugin]: """Get the class of the plugin implementing the supplied scan command. """ return self._scan_command_classes_to_plugin_classes[scan_command.__class__]
python
def get_plugin_class_for_command(self, scan_command: PluginScanCommand) -> Type[Plugin]: """Get the class of the plugin implementing the supplied scan command. """ return self._scan_command_classes_to_plugin_classes[scan_command.__class__]
[ "def", "get_plugin_class_for_command", "(", "self", ",", "scan_command", ":", "PluginScanCommand", ")", "->", "Type", "[", "Plugin", "]", ":", "return", "self", ".", "_scan_command_classes_to_plugin_classes", "[", "scan_command", ".", "__class__", "]" ]
Get the class of the plugin implementing the supplied scan command.
[ "Get", "the", "class", "of", "the", "plugin", "implementing", "the", "supplied", "scan", "command", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/plugins_repository.py#L44-L47
227,301
nabla-c0d3/sslyze
sslyze/utils/http_response_parser.py
HttpResponseParser._parse
def _parse(read_method: Callable) -> HTTPResponse: """Trick to standardize the API between sockets and SSLConnection objects. """ response = read_method(4096) while b'HTTP/' not in response or b'\r\n\r\n' not in response: # Parse until the end of the headers response += read_method(4096) fake_sock = _FakeSocket(response) response = HTTPResponse(fake_sock) # type: ignore response.begin() return response
python
def _parse(read_method: Callable) -> HTTPResponse: """Trick to standardize the API between sockets and SSLConnection objects. """ response = read_method(4096) while b'HTTP/' not in response or b'\r\n\r\n' not in response: # Parse until the end of the headers response += read_method(4096) fake_sock = _FakeSocket(response) response = HTTPResponse(fake_sock) # type: ignore response.begin() return response
[ "def", "_parse", "(", "read_method", ":", "Callable", ")", "->", "HTTPResponse", ":", "response", "=", "read_method", "(", "4096", ")", "while", "b'HTTP/'", "not", "in", "response", "or", "b'\\r\\n\\r\\n'", "not", "in", "response", ":", "# Parse until the end of the headers", "response", "+=", "read_method", "(", "4096", ")", "fake_sock", "=", "_FakeSocket", "(", "response", ")", "response", "=", "HTTPResponse", "(", "fake_sock", ")", "# type: ignore", "response", ".", "begin", "(", ")", "return", "response" ]
Trick to standardize the API between sockets and SSLConnection objects.
[ "Trick", "to", "standardize", "the", "API", "between", "sockets", "and", "SSLConnection", "objects", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/http_response_parser.py#L26-L37
227,302
nabla-c0d3/sslyze
sslyze/utils/thread_pool.py
_work_function
def _work_function(job_q: Queue, result_q: Queue, error_q: Queue) -> None: """Work function expected to run within threads. """ while True: job = job_q.get() if isinstance(job, _ThreadPoolSentinel): # All the work is done, get out result_q.put(_ThreadPoolSentinel()) error_q.put(_ThreadPoolSentinel()) job_q.task_done() break work_function = job[0] args = job[1] try: result = work_function(*args) except Exception as e: error_q.put((job, e)) else: result_q.put((job, result)) finally: job_q.task_done()
python
def _work_function(job_q: Queue, result_q: Queue, error_q: Queue) -> None: """Work function expected to run within threads. """ while True: job = job_q.get() if isinstance(job, _ThreadPoolSentinel): # All the work is done, get out result_q.put(_ThreadPoolSentinel()) error_q.put(_ThreadPoolSentinel()) job_q.task_done() break work_function = job[0] args = job[1] try: result = work_function(*args) except Exception as e: error_q.put((job, e)) else: result_q.put((job, result)) finally: job_q.task_done()
[ "def", "_work_function", "(", "job_q", ":", "Queue", ",", "result_q", ":", "Queue", ",", "error_q", ":", "Queue", ")", "->", "None", ":", "while", "True", ":", "job", "=", "job_q", ".", "get", "(", ")", "if", "isinstance", "(", "job", ",", "_ThreadPoolSentinel", ")", ":", "# All the work is done, get out", "result_q", ".", "put", "(", "_ThreadPoolSentinel", "(", ")", ")", "error_q", ".", "put", "(", "_ThreadPoolSentinel", "(", ")", ")", "job_q", ".", "task_done", "(", ")", "break", "work_function", "=", "job", "[", "0", "]", "args", "=", "job", "[", "1", "]", "try", ":", "result", "=", "work_function", "(", "*", "args", ")", "except", "Exception", "as", "e", ":", "error_q", ".", "put", "(", "(", "job", ",", "e", ")", ")", "else", ":", "result_q", ".", "put", "(", "(", "job", ",", "result", ")", ")", "finally", ":", "job_q", ".", "task_done", "(", ")" ]
Work function expected to run within threads.
[ "Work", "function", "expected", "to", "run", "within", "threads", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/thread_pool.py#L93-L115
227,303
nabla-c0d3/sslyze
sslyze/plugins/session_resumption_plugin.py
SessionResumptionPlugin._resume_with_session_id
def _resume_with_session_id( self, server_info: ServerConnectivityInfo, ssl_version_to_use: OpenSslVersionEnum ) -> bool: """Perform one session resumption using Session IDs. """ session1 = self._resume_ssl_session(server_info, ssl_version_to_use) try: # Recover the session ID session1_id = self._extract_session_id(session1) except IndexError: # Session ID not assigned return False if session1_id == '': # Session ID empty return False # Try to resume that SSL session session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1) try: # Recover the session ID session2_id = self._extract_session_id(session2) except IndexError: # Session ID not assigned return False # Finally, compare the two Session IDs if session1_id != session2_id: # Session ID assigned but not accepted return False return True
python
def _resume_with_session_id( self, server_info: ServerConnectivityInfo, ssl_version_to_use: OpenSslVersionEnum ) -> bool: """Perform one session resumption using Session IDs. """ session1 = self._resume_ssl_session(server_info, ssl_version_to_use) try: # Recover the session ID session1_id = self._extract_session_id(session1) except IndexError: # Session ID not assigned return False if session1_id == '': # Session ID empty return False # Try to resume that SSL session session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1) try: # Recover the session ID session2_id = self._extract_session_id(session2) except IndexError: # Session ID not assigned return False # Finally, compare the two Session IDs if session1_id != session2_id: # Session ID assigned but not accepted return False return True
[ "def", "_resume_with_session_id", "(", "self", ",", "server_info", ":", "ServerConnectivityInfo", ",", "ssl_version_to_use", ":", "OpenSslVersionEnum", ")", "->", "bool", ":", "session1", "=", "self", ".", "_resume_ssl_session", "(", "server_info", ",", "ssl_version_to_use", ")", "try", ":", "# Recover the session ID", "session1_id", "=", "self", ".", "_extract_session_id", "(", "session1", ")", "except", "IndexError", ":", "# Session ID not assigned", "return", "False", "if", "session1_id", "==", "''", ":", "# Session ID empty", "return", "False", "# Try to resume that SSL session", "session2", "=", "self", ".", "_resume_ssl_session", "(", "server_info", ",", "ssl_version_to_use", ",", "session1", ")", "try", ":", "# Recover the session ID", "session2_id", "=", "self", ".", "_extract_session_id", "(", "session2", ")", "except", "IndexError", ":", "# Session ID not assigned", "return", "False", "# Finally, compare the two Session IDs", "if", "session1_id", "!=", "session2_id", ":", "# Session ID assigned but not accepted", "return", "False", "return", "True" ]
Perform one session resumption using Session IDs.
[ "Perform", "one", "session", "resumption", "using", "Session", "IDs", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L151-L184
227,304
nabla-c0d3/sslyze
sslyze/plugins/session_resumption_plugin.py
SessionResumptionPlugin._resume_with_session_ticket
def _resume_with_session_ticket( self, server_info: ServerConnectivityInfo, ssl_version_to_use: OpenSslVersionEnum, ) -> TslSessionTicketSupportEnum: """Perform one session resumption using TLS Session Tickets. """ # Connect to the server and keep the SSL session try: session1 = self._resume_ssl_session(server_info, ssl_version_to_use, should_enable_tls_ticket=True) except SslHandshakeRejected: if server_info.highest_ssl_version_supported >= OpenSslVersionEnum.TLSV1_3: return TslSessionTicketSupportEnum.FAILED_ONLY_TLS_1_3_SUPPORTED else: raise try: # Recover the TLS ticket session1_tls_ticket = self._extract_tls_session_ticket(session1) except IndexError: return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED # Try to resume that session using the TLS ticket session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1, should_enable_tls_ticket=True) try: # Recover the TLS ticket session2_tls_ticket = self._extract_tls_session_ticket(session2) except IndexError: return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED # Finally, compare the two TLS Tickets if session1_tls_ticket != session2_tls_ticket: return TslSessionTicketSupportEnum.FAILED_TICKED_IGNORED return TslSessionTicketSupportEnum.SUCCEEDED
python
def _resume_with_session_ticket( self, server_info: ServerConnectivityInfo, ssl_version_to_use: OpenSslVersionEnum, ) -> TslSessionTicketSupportEnum: """Perform one session resumption using TLS Session Tickets. """ # Connect to the server and keep the SSL session try: session1 = self._resume_ssl_session(server_info, ssl_version_to_use, should_enable_tls_ticket=True) except SslHandshakeRejected: if server_info.highest_ssl_version_supported >= OpenSslVersionEnum.TLSV1_3: return TslSessionTicketSupportEnum.FAILED_ONLY_TLS_1_3_SUPPORTED else: raise try: # Recover the TLS ticket session1_tls_ticket = self._extract_tls_session_ticket(session1) except IndexError: return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED # Try to resume that session using the TLS ticket session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1, should_enable_tls_ticket=True) try: # Recover the TLS ticket session2_tls_ticket = self._extract_tls_session_ticket(session2) except IndexError: return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED # Finally, compare the two TLS Tickets if session1_tls_ticket != session2_tls_ticket: return TslSessionTicketSupportEnum.FAILED_TICKED_IGNORED return TslSessionTicketSupportEnum.SUCCEEDED
[ "def", "_resume_with_session_ticket", "(", "self", ",", "server_info", ":", "ServerConnectivityInfo", ",", "ssl_version_to_use", ":", "OpenSslVersionEnum", ",", ")", "->", "TslSessionTicketSupportEnum", ":", "# Connect to the server and keep the SSL session", "try", ":", "session1", "=", "self", ".", "_resume_ssl_session", "(", "server_info", ",", "ssl_version_to_use", ",", "should_enable_tls_ticket", "=", "True", ")", "except", "SslHandshakeRejected", ":", "if", "server_info", ".", "highest_ssl_version_supported", ">=", "OpenSslVersionEnum", ".", "TLSV1_3", ":", "return", "TslSessionTicketSupportEnum", ".", "FAILED_ONLY_TLS_1_3_SUPPORTED", "else", ":", "raise", "try", ":", "# Recover the TLS ticket", "session1_tls_ticket", "=", "self", ".", "_extract_tls_session_ticket", "(", "session1", ")", "except", "IndexError", ":", "return", "TslSessionTicketSupportEnum", ".", "FAILED_TICKET_NOT_ASSIGNED", "# Try to resume that session using the TLS ticket", "session2", "=", "self", ".", "_resume_ssl_session", "(", "server_info", ",", "ssl_version_to_use", ",", "session1", ",", "should_enable_tls_ticket", "=", "True", ")", "try", ":", "# Recover the TLS ticket", "session2_tls_ticket", "=", "self", ".", "_extract_tls_session_ticket", "(", "session2", ")", "except", "IndexError", ":", "return", "TslSessionTicketSupportEnum", ".", "FAILED_TICKET_NOT_ASSIGNED", "# Finally, compare the two TLS Tickets", "if", "session1_tls_ticket", "!=", "session2_tls_ticket", ":", "return", "TslSessionTicketSupportEnum", ".", "FAILED_TICKED_IGNORED", "return", "TslSessionTicketSupportEnum", ".", "SUCCEEDED" ]
Perform one session resumption using TLS Session Tickets.
[ "Perform", "one", "session", "resumption", "using", "TLS", "Session", "Tickets", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L186-L220
227,305
nabla-c0d3/sslyze
sslyze/plugins/session_resumption_plugin.py
SessionResumptionPlugin._extract_session_id
def _extract_session_id(ssl_session: nassl._nassl.SSL_SESSION) -> str: """Extract the SSL session ID from a SSL session object or raises IndexError if the session ID was not set. """ session_string = ((ssl_session.as_text()).split('Session-ID:'))[1] session_id = (session_string.split('Session-ID-ctx:'))[0].strip() return session_id
python
def _extract_session_id(ssl_session: nassl._nassl.SSL_SESSION) -> str: """Extract the SSL session ID from a SSL session object or raises IndexError if the session ID was not set. """ session_string = ((ssl_session.as_text()).split('Session-ID:'))[1] session_id = (session_string.split('Session-ID-ctx:'))[0].strip() return session_id
[ "def", "_extract_session_id", "(", "ssl_session", ":", "nassl", ".", "_nassl", ".", "SSL_SESSION", ")", "->", "str", ":", "session_string", "=", "(", "(", "ssl_session", ".", "as_text", "(", ")", ")", ".", "split", "(", "'Session-ID:'", ")", ")", "[", "1", "]", "session_id", "=", "(", "session_string", ".", "split", "(", "'Session-ID-ctx:'", ")", ")", "[", "0", "]", ".", "strip", "(", ")", "return", "session_id" ]
Extract the SSL session ID from a SSL session object or raises IndexError if the session ID was not set.
[ "Extract", "the", "SSL", "session", "ID", "from", "a", "SSL", "session", "object", "or", "raises", "IndexError", "if", "the", "session", "ID", "was", "not", "set", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L223-L228
227,306
nabla-c0d3/sslyze
sslyze/plugins/session_resumption_plugin.py
SessionResumptionPlugin._extract_tls_session_ticket
def _extract_tls_session_ticket(ssl_session: nassl._nassl.SSL_SESSION) -> str: """Extract the TLS session ticket from a SSL session object or raises IndexError if the ticket was not set. """ session_string = ((ssl_session.as_text()).split('TLS session ticket:'))[1] session_tls_ticket = (session_string.split('Compression:'))[0] return session_tls_ticket
python
def _extract_tls_session_ticket(ssl_session: nassl._nassl.SSL_SESSION) -> str: """Extract the TLS session ticket from a SSL session object or raises IndexError if the ticket was not set. """ session_string = ((ssl_session.as_text()).split('TLS session ticket:'))[1] session_tls_ticket = (session_string.split('Compression:'))[0] return session_tls_ticket
[ "def", "_extract_tls_session_ticket", "(", "ssl_session", ":", "nassl", ".", "_nassl", ".", "SSL_SESSION", ")", "->", "str", ":", "session_string", "=", "(", "(", "ssl_session", ".", "as_text", "(", ")", ")", ".", "split", "(", "'TLS session ticket:'", ")", ")", "[", "1", "]", "session_tls_ticket", "=", "(", "session_string", ".", "split", "(", "'Compression:'", ")", ")", "[", "0", "]", "return", "session_tls_ticket" ]
Extract the TLS session ticket from a SSL session object or raises IndexError if the ticket was not set.
[ "Extract", "the", "TLS", "session", "ticket", "from", "a", "SSL", "session", "object", "or", "raises", "IndexError", "if", "the", "ticket", "was", "not", "set", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L231-L236
227,307
nabla-c0d3/sslyze
sslyze/plugins/session_resumption_plugin.py
SessionResumptionPlugin._resume_ssl_session
def _resume_ssl_session( server_info: ServerConnectivityInfo, ssl_version_to_use: OpenSslVersionEnum, ssl_session: Optional[nassl._nassl.SSL_SESSION] = None, should_enable_tls_ticket: bool = False ) -> nassl._nassl.SSL_SESSION: """Connect to the server and returns the session object that was assigned for that connection. If ssl_session is given, tries to resume that session. """ ssl_connection = server_info.get_preconfigured_ssl_connection(override_ssl_version=ssl_version_to_use) if not should_enable_tls_ticket: # Need to disable TLS tickets to test session IDs, according to rfc5077: # If a ticket is presented by the client, the server MUST NOT attempt # to use the Session ID in the ClientHello for stateful session resumption ssl_connection.ssl_client.disable_stateless_session_resumption() # Turning off TLS tickets. if ssl_session: ssl_connection.ssl_client.set_session(ssl_session) try: # Perform the SSL handshake ssl_connection.connect() new_session = ssl_connection.ssl_client.get_session() # Get session data finally: ssl_connection.close() return new_session
python
def _resume_ssl_session( server_info: ServerConnectivityInfo, ssl_version_to_use: OpenSslVersionEnum, ssl_session: Optional[nassl._nassl.SSL_SESSION] = None, should_enable_tls_ticket: bool = False ) -> nassl._nassl.SSL_SESSION: """Connect to the server and returns the session object that was assigned for that connection. If ssl_session is given, tries to resume that session. """ ssl_connection = server_info.get_preconfigured_ssl_connection(override_ssl_version=ssl_version_to_use) if not should_enable_tls_ticket: # Need to disable TLS tickets to test session IDs, according to rfc5077: # If a ticket is presented by the client, the server MUST NOT attempt # to use the Session ID in the ClientHello for stateful session resumption ssl_connection.ssl_client.disable_stateless_session_resumption() # Turning off TLS tickets. if ssl_session: ssl_connection.ssl_client.set_session(ssl_session) try: # Perform the SSL handshake ssl_connection.connect() new_session = ssl_connection.ssl_client.get_session() # Get session data finally: ssl_connection.close() return new_session
[ "def", "_resume_ssl_session", "(", "server_info", ":", "ServerConnectivityInfo", ",", "ssl_version_to_use", ":", "OpenSslVersionEnum", ",", "ssl_session", ":", "Optional", "[", "nassl", ".", "_nassl", ".", "SSL_SESSION", "]", "=", "None", ",", "should_enable_tls_ticket", ":", "bool", "=", "False", ")", "->", "nassl", ".", "_nassl", ".", "SSL_SESSION", ":", "ssl_connection", "=", "server_info", ".", "get_preconfigured_ssl_connection", "(", "override_ssl_version", "=", "ssl_version_to_use", ")", "if", "not", "should_enable_tls_ticket", ":", "# Need to disable TLS tickets to test session IDs, according to rfc5077:", "# If a ticket is presented by the client, the server MUST NOT attempt", "# to use the Session ID in the ClientHello for stateful session resumption", "ssl_connection", ".", "ssl_client", ".", "disable_stateless_session_resumption", "(", ")", "# Turning off TLS tickets.", "if", "ssl_session", ":", "ssl_connection", ".", "ssl_client", ".", "set_session", "(", "ssl_session", ")", "try", ":", "# Perform the SSL handshake", "ssl_connection", ".", "connect", "(", ")", "new_session", "=", "ssl_connection", ".", "ssl_client", ".", "get_session", "(", ")", "# Get session data", "finally", ":", "ssl_connection", ".", "close", "(", ")", "return", "new_session" ]
Connect to the server and returns the session object that was assigned for that connection. If ssl_session is given, tries to resume that session.
[ "Connect", "to", "the", "server", "and", "returns", "the", "session", "object", "that", "was", "assigned", "for", "that", "connection", ".", "If", "ssl_session", "is", "given", "tries", "to", "resume", "that", "session", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L239-L265
227,308
nabla-c0d3/sslyze
sslyze/cli/json_output.py
_object_to_json_dict
def _object_to_json_dict(obj: Any) -> Union[bool, int, float, str, Dict[str, Any]]: """Convert an object to a dictionary suitable for the JSON output. """ if isinstance(obj, Enum): # Properly serialize Enums (such as OpenSslVersionEnum) result = obj.name elif isinstance(obj, ObjectIdentifier): # Use dotted string representation for OIDs result = obj.dotted_string elif isinstance(obj, x509._Certificate): # Properly serialize certificates certificate = obj result = { # type: ignore # Add general info 'as_pem': obj.public_bytes(Encoding.PEM).decode('ascii'), 'hpkp_pin': CertificateUtils.get_hpkp_pin(obj), # Add some of the fields of the cert 'subject': CertificateUtils.get_name_as_text(certificate.subject), 'issuer': CertificateUtils.get_name_as_text(certificate.issuer), 'serialNumber': str(certificate.serial_number), 'notBefore': certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"), 'notAfter': certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"), 'signatureAlgorithm': certificate.signature_hash_algorithm.name, 'publicKey': { 'algorithm': CertificateUtils.get_public_key_type(certificate) }, } dns_alt_names = CertificateUtils.get_dns_subject_alternative_names(certificate) if dns_alt_names: result['subjectAlternativeName'] = {'DNS': dns_alt_names} # type: ignore # Add some info about the public key public_key = certificate.public_key() if isinstance(public_key, EllipticCurvePublicKey): result['publicKey']['size'] = str(public_key.curve.key_size) # type: ignore result['publicKey']['curve'] = public_key.curve.name # type: ignore else: result['publicKey']['size'] = str(public_key.key_size) result['publicKey']['exponent'] = str(public_key.public_numbers().e) elif isinstance(obj, object): # Some objects (like str) don't have a __dict__ if hasattr(obj, '__dict__'): result = {} for key, value in obj.__dict__.items(): # Remove private attributes if key.startswith('_'): continue result[key] = _object_to_json_dict(value) else: # Simple object like a bool result = obj else: raise TypeError('Unknown type: {}'.format(repr(obj))) return result
python
def _object_to_json_dict(obj: Any) -> Union[bool, int, float, str, Dict[str, Any]]: """Convert an object to a dictionary suitable for the JSON output. """ if isinstance(obj, Enum): # Properly serialize Enums (such as OpenSslVersionEnum) result = obj.name elif isinstance(obj, ObjectIdentifier): # Use dotted string representation for OIDs result = obj.dotted_string elif isinstance(obj, x509._Certificate): # Properly serialize certificates certificate = obj result = { # type: ignore # Add general info 'as_pem': obj.public_bytes(Encoding.PEM).decode('ascii'), 'hpkp_pin': CertificateUtils.get_hpkp_pin(obj), # Add some of the fields of the cert 'subject': CertificateUtils.get_name_as_text(certificate.subject), 'issuer': CertificateUtils.get_name_as_text(certificate.issuer), 'serialNumber': str(certificate.serial_number), 'notBefore': certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"), 'notAfter': certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"), 'signatureAlgorithm': certificate.signature_hash_algorithm.name, 'publicKey': { 'algorithm': CertificateUtils.get_public_key_type(certificate) }, } dns_alt_names = CertificateUtils.get_dns_subject_alternative_names(certificate) if dns_alt_names: result['subjectAlternativeName'] = {'DNS': dns_alt_names} # type: ignore # Add some info about the public key public_key = certificate.public_key() if isinstance(public_key, EllipticCurvePublicKey): result['publicKey']['size'] = str(public_key.curve.key_size) # type: ignore result['publicKey']['curve'] = public_key.curve.name # type: ignore else: result['publicKey']['size'] = str(public_key.key_size) result['publicKey']['exponent'] = str(public_key.public_numbers().e) elif isinstance(obj, object): # Some objects (like str) don't have a __dict__ if hasattr(obj, '__dict__'): result = {} for key, value in obj.__dict__.items(): # Remove private attributes if key.startswith('_'): continue result[key] = _object_to_json_dict(value) else: # Simple object like a bool result = obj else: raise TypeError('Unknown type: {}'.format(repr(obj))) return result
[ "def", "_object_to_json_dict", "(", "obj", ":", "Any", ")", "->", "Union", "[", "bool", ",", "int", ",", "float", ",", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "if", "isinstance", "(", "obj", ",", "Enum", ")", ":", "# Properly serialize Enums (such as OpenSslVersionEnum)", "result", "=", "obj", ".", "name", "elif", "isinstance", "(", "obj", ",", "ObjectIdentifier", ")", ":", "# Use dotted string representation for OIDs", "result", "=", "obj", ".", "dotted_string", "elif", "isinstance", "(", "obj", ",", "x509", ".", "_Certificate", ")", ":", "# Properly serialize certificates", "certificate", "=", "obj", "result", "=", "{", "# type: ignore", "# Add general info", "'as_pem'", ":", "obj", ".", "public_bytes", "(", "Encoding", ".", "PEM", ")", ".", "decode", "(", "'ascii'", ")", ",", "'hpkp_pin'", ":", "CertificateUtils", ".", "get_hpkp_pin", "(", "obj", ")", ",", "# Add some of the fields of the cert", "'subject'", ":", "CertificateUtils", ".", "get_name_as_text", "(", "certificate", ".", "subject", ")", ",", "'issuer'", ":", "CertificateUtils", ".", "get_name_as_text", "(", "certificate", ".", "issuer", ")", ",", "'serialNumber'", ":", "str", "(", "certificate", ".", "serial_number", ")", ",", "'notBefore'", ":", "certificate", ".", "not_valid_before", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ")", ",", "'notAfter'", ":", "certificate", ".", "not_valid_after", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ")", ",", "'signatureAlgorithm'", ":", "certificate", ".", "signature_hash_algorithm", ".", "name", ",", "'publicKey'", ":", "{", "'algorithm'", ":", "CertificateUtils", ".", "get_public_key_type", "(", "certificate", ")", "}", ",", "}", "dns_alt_names", "=", "CertificateUtils", ".", "get_dns_subject_alternative_names", "(", "certificate", ")", "if", "dns_alt_names", ":", "result", "[", "'subjectAlternativeName'", "]", "=", "{", "'DNS'", ":", "dns_alt_names", "}", "# type: ignore", "# Add some info about the public key", "public_key", "=", "certificate", ".", "public_key", "(", ")", "if", "isinstance", "(", "public_key", ",", "EllipticCurvePublicKey", ")", ":", "result", "[", "'publicKey'", "]", "[", "'size'", "]", "=", "str", "(", "public_key", ".", "curve", ".", "key_size", ")", "# type: ignore", "result", "[", "'publicKey'", "]", "[", "'curve'", "]", "=", "public_key", ".", "curve", ".", "name", "# type: ignore", "else", ":", "result", "[", "'publicKey'", "]", "[", "'size'", "]", "=", "str", "(", "public_key", ".", "key_size", ")", "result", "[", "'publicKey'", "]", "[", "'exponent'", "]", "=", "str", "(", "public_key", ".", "public_numbers", "(", ")", ".", "e", ")", "elif", "isinstance", "(", "obj", ",", "object", ")", ":", "# Some objects (like str) don't have a __dict__", "if", "hasattr", "(", "obj", ",", "'__dict__'", ")", ":", "result", "=", "{", "}", "for", "key", ",", "value", "in", "obj", ".", "__dict__", ".", "items", "(", ")", ":", "# Remove private attributes", "if", "key", ".", "startswith", "(", "'_'", ")", ":", "continue", "result", "[", "key", "]", "=", "_object_to_json_dict", "(", "value", ")", "else", ":", "# Simple object like a bool", "result", "=", "obj", "else", ":", "raise", "TypeError", "(", "'Unknown type: {}'", ".", "format", "(", "repr", "(", "obj", ")", ")", ")", "return", "result" ]
Convert an object to a dictionary suitable for the JSON output.
[ "Convert", "an", "object", "to", "a", "dictionary", "suitable", "for", "the", "JSON", "output", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/cli/json_output.py#L84-L145
227,309
nabla-c0d3/sslyze
sslyze/plugins/certificate_info_plugin.py
CertificateInfoPlugin._get_and_verify_certificate_chain
def _get_and_verify_certificate_chain( server_info: ServerConnectivityInfo, trust_store: TrustStore ) -> Tuple[List[Certificate], str, Optional[OcspResponse]]: """Connects to the target server and uses the supplied trust store to validate the server's certificate. Returns the server's certificate and OCSP response. """ ssl_connection = server_info.get_preconfigured_ssl_connection(ssl_verify_locations=trust_store.path) # Enable OCSP stapling ssl_connection.ssl_client.set_tlsext_status_ocsp() try: # Perform the SSL handshake ssl_connection.connect() ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp() x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain() (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result() except ClientCertificateRequested: # The server asked for a client cert # We can get the server cert anyway ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp() x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain() (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result() finally: ssl_connection.close() # Parse the certificates using the cryptography module parsed_x509_chain = [load_pem_x509_certificate(x509_cert.as_pem().encode('ascii'), backend=default_backend()) for x509_cert in x509_cert_chain] return parsed_x509_chain, verify_str, ocsp_response
python
def _get_and_verify_certificate_chain( server_info: ServerConnectivityInfo, trust_store: TrustStore ) -> Tuple[List[Certificate], str, Optional[OcspResponse]]: """Connects to the target server and uses the supplied trust store to validate the server's certificate. Returns the server's certificate and OCSP response. """ ssl_connection = server_info.get_preconfigured_ssl_connection(ssl_verify_locations=trust_store.path) # Enable OCSP stapling ssl_connection.ssl_client.set_tlsext_status_ocsp() try: # Perform the SSL handshake ssl_connection.connect() ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp() x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain() (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result() except ClientCertificateRequested: # The server asked for a client cert # We can get the server cert anyway ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp() x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain() (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result() finally: ssl_connection.close() # Parse the certificates using the cryptography module parsed_x509_chain = [load_pem_x509_certificate(x509_cert.as_pem().encode('ascii'), backend=default_backend()) for x509_cert in x509_cert_chain] return parsed_x509_chain, verify_str, ocsp_response
[ "def", "_get_and_verify_certificate_chain", "(", "server_info", ":", "ServerConnectivityInfo", ",", "trust_store", ":", "TrustStore", ")", "->", "Tuple", "[", "List", "[", "Certificate", "]", ",", "str", ",", "Optional", "[", "OcspResponse", "]", "]", ":", "ssl_connection", "=", "server_info", ".", "get_preconfigured_ssl_connection", "(", "ssl_verify_locations", "=", "trust_store", ".", "path", ")", "# Enable OCSP stapling", "ssl_connection", ".", "ssl_client", ".", "set_tlsext_status_ocsp", "(", ")", "try", ":", "# Perform the SSL handshake", "ssl_connection", ".", "connect", "(", ")", "ocsp_response", "=", "ssl_connection", ".", "ssl_client", ".", "get_tlsext_status_ocsp_resp", "(", ")", "x509_cert_chain", "=", "ssl_connection", ".", "ssl_client", ".", "get_peer_cert_chain", "(", ")", "(", "_", ",", "verify_str", ")", "=", "ssl_connection", ".", "ssl_client", ".", "get_certificate_chain_verify_result", "(", ")", "except", "ClientCertificateRequested", ":", "# The server asked for a client cert", "# We can get the server cert anyway", "ocsp_response", "=", "ssl_connection", ".", "ssl_client", ".", "get_tlsext_status_ocsp_resp", "(", ")", "x509_cert_chain", "=", "ssl_connection", ".", "ssl_client", ".", "get_peer_cert_chain", "(", ")", "(", "_", ",", "verify_str", ")", "=", "ssl_connection", ".", "ssl_client", ".", "get_certificate_chain_verify_result", "(", ")", "finally", ":", "ssl_connection", ".", "close", "(", ")", "# Parse the certificates using the cryptography module", "parsed_x509_chain", "=", "[", "load_pem_x509_certificate", "(", "x509_cert", ".", "as_pem", "(", ")", ".", "encode", "(", "'ascii'", ")", ",", "backend", "=", "default_backend", "(", ")", ")", "for", "x509_cert", "in", "x509_cert_chain", "]", "return", "parsed_x509_chain", ",", "verify_str", ",", "ocsp_response" ]
Connects to the target server and uses the supplied trust store to validate the server's certificate. Returns the server's certificate and OCSP response.
[ "Connects", "to", "the", "target", "server", "and", "uses", "the", "supplied", "trust", "store", "to", "validate", "the", "server", "s", "certificate", ".", "Returns", "the", "server", "s", "certificate", "and", "OCSP", "response", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/certificate_info_plugin.py#L171-L202
227,310
nabla-c0d3/sslyze
sslyze/plugins/plugin_base.py
PluginScanCommand.get_description
def get_description(cls) -> str: """The description is expected to be the command class' docstring. """ if cls.__doc__ is None: raise ValueError('No docstring found for {}'.format(cls.__name__)) return cls.__doc__.strip()
python
def get_description(cls) -> str: """The description is expected to be the command class' docstring. """ if cls.__doc__ is None: raise ValueError('No docstring found for {}'.format(cls.__name__)) return cls.__doc__.strip()
[ "def", "get_description", "(", "cls", ")", "->", "str", ":", "if", "cls", ".", "__doc__", "is", "None", ":", "raise", "ValueError", "(", "'No docstring found for {}'", ".", "format", "(", "cls", ".", "__name__", ")", ")", "return", "cls", ".", "__doc__", ".", "strip", "(", ")" ]
The description is expected to be the command class' docstring.
[ "The", "description", "is", "expected", "to", "be", "the", "command", "class", "docstring", "." ]
0fb3ae668453d7ecf616d0755f237ca7be9f62fa
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/plugin_base.py#L30-L35
227,311
kennethreitz/inbox.py
inbox.py
Inbox.serve
def serve(self, port=None, address=None): """Serves the SMTP server on the given port and address.""" port = port or self.port address = address or self.address log.info('Starting SMTP server at {0}:{1}'.format(address, port)) server = InboxServer(self.collator, (address, port), None) try: asyncore.loop() except KeyboardInterrupt: log.info('Cleaning up')
python
def serve(self, port=None, address=None): """Serves the SMTP server on the given port and address.""" port = port or self.port address = address or self.address log.info('Starting SMTP server at {0}:{1}'.format(address, port)) server = InboxServer(self.collator, (address, port), None) try: asyncore.loop() except KeyboardInterrupt: log.info('Cleaning up')
[ "def", "serve", "(", "self", ",", "port", "=", "None", ",", "address", "=", "None", ")", ":", "port", "=", "port", "or", "self", ".", "port", "address", "=", "address", "or", "self", ".", "address", "log", ".", "info", "(", "'Starting SMTP server at {0}:{1}'", ".", "format", "(", "address", ",", "port", ")", ")", "server", "=", "InboxServer", "(", "self", ".", "collator", ",", "(", "address", ",", "port", ")", ",", "None", ")", "try", ":", "asyncore", ".", "loop", "(", ")", "except", "KeyboardInterrupt", ":", "log", ".", "info", "(", "'Cleaning up'", ")" ]
Serves the SMTP server on the given port and address.
[ "Serves", "the", "SMTP", "server", "on", "the", "given", "port", "and", "address", "." ]
493f8d9834a41ac9012f13da5693697efdcb1826
https://github.com/kennethreitz/inbox.py/blob/493f8d9834a41ac9012f13da5693697efdcb1826/inbox.py#L41-L53
227,312
kennethreitz/inbox.py
inbox.py
Inbox.dispatch
def dispatch(self): """Command-line dispatch.""" parser = argparse.ArgumentParser(description='Run an Inbox server.') parser.add_argument('addr', metavar='addr', type=str, help='addr to bind to') parser.add_argument('port', metavar='port', type=int, help='port to bind to') args = parser.parse_args() self.serve(port=args.port, address=args.addr)
python
def dispatch(self): """Command-line dispatch.""" parser = argparse.ArgumentParser(description='Run an Inbox server.') parser.add_argument('addr', metavar='addr', type=str, help='addr to bind to') parser.add_argument('port', metavar='port', type=int, help='port to bind to') args = parser.parse_args() self.serve(port=args.port, address=args.addr)
[ "def", "dispatch", "(", "self", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Run an Inbox server.'", ")", "parser", ".", "add_argument", "(", "'addr'", ",", "metavar", "=", "'addr'", ",", "type", "=", "str", ",", "help", "=", "'addr to bind to'", ")", "parser", ".", "add_argument", "(", "'port'", ",", "metavar", "=", "'port'", ",", "type", "=", "int", ",", "help", "=", "'port to bind to'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "self", ".", "serve", "(", "port", "=", "args", ".", "port", ",", "address", "=", "args", ".", "addr", ")" ]
Command-line dispatch.
[ "Command", "-", "line", "dispatch", "." ]
493f8d9834a41ac9012f13da5693697efdcb1826
https://github.com/kennethreitz/inbox.py/blob/493f8d9834a41ac9012f13da5693697efdcb1826/inbox.py#L55-L64
227,313
securestate/termineter
lib/c1219/data.py
format_ltime
def format_ltime(endianess, tm_format, data): """ Return data formatted into a human readable time stamp. :param str endianess: The endianess to use when packing values ('>' or '<') :param int tm_format: The format that the data is packed in, this typically corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4) :param bytes data: The packed and machine-formatted data to parse :rtype: str """ if tm_format == 0: return '' elif tm_format == 1 or tm_format == 2: # I can't find solid documentation on the BCD data-type y = data[0] year = '????' if 90 <= y <= 99: year = '19' + str(y) elif 0 <= y <= 9: year = '200' + str(y) elif 10 <= y <= 89: year = '20' + str(y) month = data[1] day = data[2] hour = data[3] minute = data[4] second = data[5] elif tm_format == 3 or tm_format == 4: if tm_format == 3: u_time = float(struct.unpack(endianess + 'I', data[0:4])[0]) second = float(data[4]) final_time = time.gmtime((u_time * 60) + second) elif tm_format == 4: final_time = time.gmtime(float(struct.unpack(endianess + 'I', data[0:4])[0])) year = str(final_time.tm_year) month = str(final_time.tm_mon) day = str(final_time.tm_mday) hour = str(final_time.tm_hour) minute = str(final_time.tm_min) second = str(final_time.tm_sec) return "{0} {1} {2} {3}:{4}:{5}".format((MONTHS.get(month) or 'UNKNOWN'), day, year, hour, minute, second)
python
def format_ltime(endianess, tm_format, data): """ Return data formatted into a human readable time stamp. :param str endianess: The endianess to use when packing values ('>' or '<') :param int tm_format: The format that the data is packed in, this typically corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4) :param bytes data: The packed and machine-formatted data to parse :rtype: str """ if tm_format == 0: return '' elif tm_format == 1 or tm_format == 2: # I can't find solid documentation on the BCD data-type y = data[0] year = '????' if 90 <= y <= 99: year = '19' + str(y) elif 0 <= y <= 9: year = '200' + str(y) elif 10 <= y <= 89: year = '20' + str(y) month = data[1] day = data[2] hour = data[3] minute = data[4] second = data[5] elif tm_format == 3 or tm_format == 4: if tm_format == 3: u_time = float(struct.unpack(endianess + 'I', data[0:4])[0]) second = float(data[4]) final_time = time.gmtime((u_time * 60) + second) elif tm_format == 4: final_time = time.gmtime(float(struct.unpack(endianess + 'I', data[0:4])[0])) year = str(final_time.tm_year) month = str(final_time.tm_mon) day = str(final_time.tm_mday) hour = str(final_time.tm_hour) minute = str(final_time.tm_min) second = str(final_time.tm_sec) return "{0} {1} {2} {3}:{4}:{5}".format((MONTHS.get(month) or 'UNKNOWN'), day, year, hour, minute, second)
[ "def", "format_ltime", "(", "endianess", ",", "tm_format", ",", "data", ")", ":", "if", "tm_format", "==", "0", ":", "return", "''", "elif", "tm_format", "==", "1", "or", "tm_format", "==", "2", ":", "# I can't find solid documentation on the BCD data-type", "y", "=", "data", "[", "0", "]", "year", "=", "'????'", "if", "90", "<=", "y", "<=", "99", ":", "year", "=", "'19'", "+", "str", "(", "y", ")", "elif", "0", "<=", "y", "<=", "9", ":", "year", "=", "'200'", "+", "str", "(", "y", ")", "elif", "10", "<=", "y", "<=", "89", ":", "year", "=", "'20'", "+", "str", "(", "y", ")", "month", "=", "data", "[", "1", "]", "day", "=", "data", "[", "2", "]", "hour", "=", "data", "[", "3", "]", "minute", "=", "data", "[", "4", "]", "second", "=", "data", "[", "5", "]", "elif", "tm_format", "==", "3", "or", "tm_format", "==", "4", ":", "if", "tm_format", "==", "3", ":", "u_time", "=", "float", "(", "struct", ".", "unpack", "(", "endianess", "+", "'I'", ",", "data", "[", "0", ":", "4", "]", ")", "[", "0", "]", ")", "second", "=", "float", "(", "data", "[", "4", "]", ")", "final_time", "=", "time", ".", "gmtime", "(", "(", "u_time", "*", "60", ")", "+", "second", ")", "elif", "tm_format", "==", "4", ":", "final_time", "=", "time", ".", "gmtime", "(", "float", "(", "struct", ".", "unpack", "(", "endianess", "+", "'I'", ",", "data", "[", "0", ":", "4", "]", ")", "[", "0", "]", ")", ")", "year", "=", "str", "(", "final_time", ".", "tm_year", ")", "month", "=", "str", "(", "final_time", ".", "tm_mon", ")", "day", "=", "str", "(", "final_time", ".", "tm_mday", ")", "hour", "=", "str", "(", "final_time", ".", "tm_hour", ")", "minute", "=", "str", "(", "final_time", ".", "tm_min", ")", "second", "=", "str", "(", "final_time", ".", "tm_sec", ")", "return", "\"{0} {1} {2} {3}:{4}:{5}\"", ".", "format", "(", "(", "MONTHS", ".", "get", "(", "month", ")", "or", "'UNKNOWN'", ")", ",", "day", ",", "year", ",", "hour", ",", "minute", ",", "second", ")" ]
Return data formatted into a human readable time stamp. :param str endianess: The endianess to use when packing values ('>' or '<') :param int tm_format: The format that the data is packed in, this typically corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4) :param bytes data: The packed and machine-formatted data to parse :rtype: str
[ "Return", "data", "formatted", "into", "a", "human", "readable", "time", "stamp", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L40-L80
227,314
securestate/termineter
lib/c1219/data.py
get_history_entry_record
def get_history_entry_record(endianess, hist_date_time_flag, tm_format, event_number_flag, hist_seq_nbr_flag, data): """ Return data formatted into a log entry. :param str endianess: The endianess to use when packing values ('>' or '<') :param bool hist_date_time_flag: Whether or not a time stamp is included. :param int tm_format: The format that the data is packed in, this typically corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4) :param bool event_number_flag: Whether or not an event number is included. :param bool hist_seq_nbr_flag: Whether or not an history sequence number is included. :param str data: The packed and machine-formatted data to parse :rtype: dict """ rcd = {} if hist_date_time_flag: tmstmp = format_ltime(endianess, tm_format, data[0:LTIME_LENGTH.get(tm_format)]) if tmstmp: rcd['Time'] = tmstmp data = data[LTIME_LENGTH.get(tm_format):] if event_number_flag: rcd['Event Number'] = struct.unpack(endianess + 'H', data[:2])[0] data = data[2:] if hist_seq_nbr_flag: rcd['History Sequence Number'] = struct.unpack(endianess + 'H', data[:2])[0] data = data[2:] rcd['User ID'] = struct.unpack(endianess + 'H', data[:2])[0] rcd['Procedure Number'], rcd['Std vs Mfg'] = get_table_idbb_field(endianess, data[2:4])[:2] rcd['Arguments'] = data[4:] return rcd
python
def get_history_entry_record(endianess, hist_date_time_flag, tm_format, event_number_flag, hist_seq_nbr_flag, data): """ Return data formatted into a log entry. :param str endianess: The endianess to use when packing values ('>' or '<') :param bool hist_date_time_flag: Whether or not a time stamp is included. :param int tm_format: The format that the data is packed in, this typically corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4) :param bool event_number_flag: Whether or not an event number is included. :param bool hist_seq_nbr_flag: Whether or not an history sequence number is included. :param str data: The packed and machine-formatted data to parse :rtype: dict """ rcd = {} if hist_date_time_flag: tmstmp = format_ltime(endianess, tm_format, data[0:LTIME_LENGTH.get(tm_format)]) if tmstmp: rcd['Time'] = tmstmp data = data[LTIME_LENGTH.get(tm_format):] if event_number_flag: rcd['Event Number'] = struct.unpack(endianess + 'H', data[:2])[0] data = data[2:] if hist_seq_nbr_flag: rcd['History Sequence Number'] = struct.unpack(endianess + 'H', data[:2])[0] data = data[2:] rcd['User ID'] = struct.unpack(endianess + 'H', data[:2])[0] rcd['Procedure Number'], rcd['Std vs Mfg'] = get_table_idbb_field(endianess, data[2:4])[:2] rcd['Arguments'] = data[4:] return rcd
[ "def", "get_history_entry_record", "(", "endianess", ",", "hist_date_time_flag", ",", "tm_format", ",", "event_number_flag", ",", "hist_seq_nbr_flag", ",", "data", ")", ":", "rcd", "=", "{", "}", "if", "hist_date_time_flag", ":", "tmstmp", "=", "format_ltime", "(", "endianess", ",", "tm_format", ",", "data", "[", "0", ":", "LTIME_LENGTH", ".", "get", "(", "tm_format", ")", "]", ")", "if", "tmstmp", ":", "rcd", "[", "'Time'", "]", "=", "tmstmp", "data", "=", "data", "[", "LTIME_LENGTH", ".", "get", "(", "tm_format", ")", ":", "]", "if", "event_number_flag", ":", "rcd", "[", "'Event Number'", "]", "=", "struct", ".", "unpack", "(", "endianess", "+", "'H'", ",", "data", "[", ":", "2", "]", ")", "[", "0", "]", "data", "=", "data", "[", "2", ":", "]", "if", "hist_seq_nbr_flag", ":", "rcd", "[", "'History Sequence Number'", "]", "=", "struct", ".", "unpack", "(", "endianess", "+", "'H'", ",", "data", "[", ":", "2", "]", ")", "[", "0", "]", "data", "=", "data", "[", "2", ":", "]", "rcd", "[", "'User ID'", "]", "=", "struct", ".", "unpack", "(", "endianess", "+", "'H'", ",", "data", "[", ":", "2", "]", ")", "[", "0", "]", "rcd", "[", "'Procedure Number'", "]", ",", "rcd", "[", "'Std vs Mfg'", "]", "=", "get_table_idbb_field", "(", "endianess", ",", "data", "[", "2", ":", "4", "]", ")", "[", ":", "2", "]", "rcd", "[", "'Arguments'", "]", "=", "data", "[", "4", ":", "]", "return", "rcd" ]
Return data formatted into a log entry. :param str endianess: The endianess to use when packing values ('>' or '<') :param bool hist_date_time_flag: Whether or not a time stamp is included. :param int tm_format: The format that the data is packed in, this typically corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4) :param bool event_number_flag: Whether or not an event number is included. :param bool hist_seq_nbr_flag: Whether or not an history sequence number is included. :param str data: The packed and machine-formatted data to parse :rtype: dict
[ "Return", "data", "formatted", "into", "a", "log", "entry", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L82-L111
227,315
securestate/termineter
lib/c1219/data.py
get_table_idbb_field
def get_table_idbb_field(endianess, data): """ Return data from a packed TABLE_IDB_BFLD bit-field. :param str endianess: The endianess to use when packing values ('>' or '<') :param str data: The packed and machine-formatted data to parse :rtype: tuple :return: Tuple of (proc_nbr, std_vs_mfg) """ bfld = struct.unpack(endianess + 'H', data[:2])[0] proc_nbr = bfld & 0x7ff std_vs_mfg = bool(bfld & 0x800) selector = (bfld & 0xf000) >> 12 return (proc_nbr, std_vs_mfg, selector)
python
def get_table_idbb_field(endianess, data): """ Return data from a packed TABLE_IDB_BFLD bit-field. :param str endianess: The endianess to use when packing values ('>' or '<') :param str data: The packed and machine-formatted data to parse :rtype: tuple :return: Tuple of (proc_nbr, std_vs_mfg) """ bfld = struct.unpack(endianess + 'H', data[:2])[0] proc_nbr = bfld & 0x7ff std_vs_mfg = bool(bfld & 0x800) selector = (bfld & 0xf000) >> 12 return (proc_nbr, std_vs_mfg, selector)
[ "def", "get_table_idbb_field", "(", "endianess", ",", "data", ")", ":", "bfld", "=", "struct", ".", "unpack", "(", "endianess", "+", "'H'", ",", "data", "[", ":", "2", "]", ")", "[", "0", "]", "proc_nbr", "=", "bfld", "&", "0x7ff", "std_vs_mfg", "=", "bool", "(", "bfld", "&", "0x800", ")", "selector", "=", "(", "bfld", "&", "0xf000", ")", ">>", "12", "return", "(", "proc_nbr", ",", "std_vs_mfg", ",", "selector", ")" ]
Return data from a packed TABLE_IDB_BFLD bit-field. :param str endianess: The endianess to use when packing values ('>' or '<') :param str data: The packed and machine-formatted data to parse :rtype: tuple :return: Tuple of (proc_nbr, std_vs_mfg)
[ "Return", "data", "from", "a", "packed", "TABLE_IDB_BFLD", "bit", "-", "field", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L113-L126
227,316
securestate/termineter
lib/c1219/data.py
get_table_idcb_field
def get_table_idcb_field(endianess, data): """ Return data from a packed TABLE_IDC_BFLD bit-field. :param str endianess: The endianess to use when packing values ('>' or '<') :param str data: The packed and machine-formatted data to parse :rtype: tuple :return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3) """ bfld = struct.unpack(endianess + 'H', data[:2])[0] proc_nbr = bfld & 2047 std_vs_mfg = bool(bfld & 2048) proc_flag = bool(bfld & 4096) flag1 = bool(bfld & 8192) flag2 = bool(bfld & 16384) flag3 = bool(bfld & 32768) return (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3)
python
def get_table_idcb_field(endianess, data): """ Return data from a packed TABLE_IDC_BFLD bit-field. :param str endianess: The endianess to use when packing values ('>' or '<') :param str data: The packed and machine-formatted data to parse :rtype: tuple :return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3) """ bfld = struct.unpack(endianess + 'H', data[:2])[0] proc_nbr = bfld & 2047 std_vs_mfg = bool(bfld & 2048) proc_flag = bool(bfld & 4096) flag1 = bool(bfld & 8192) flag2 = bool(bfld & 16384) flag3 = bool(bfld & 32768) return (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3)
[ "def", "get_table_idcb_field", "(", "endianess", ",", "data", ")", ":", "bfld", "=", "struct", ".", "unpack", "(", "endianess", "+", "'H'", ",", "data", "[", ":", "2", "]", ")", "[", "0", "]", "proc_nbr", "=", "bfld", "&", "2047", "std_vs_mfg", "=", "bool", "(", "bfld", "&", "2048", ")", "proc_flag", "=", "bool", "(", "bfld", "&", "4096", ")", "flag1", "=", "bool", "(", "bfld", "&", "8192", ")", "flag2", "=", "bool", "(", "bfld", "&", "16384", ")", "flag3", "=", "bool", "(", "bfld", "&", "32768", ")", "return", "(", "proc_nbr", ",", "std_vs_mfg", ",", "proc_flag", ",", "flag1", ",", "flag2", ",", "flag3", ")" ]
Return data from a packed TABLE_IDC_BFLD bit-field. :param str endianess: The endianess to use when packing values ('>' or '<') :param str data: The packed and machine-formatted data to parse :rtype: tuple :return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3)
[ "Return", "data", "from", "a", "packed", "TABLE_IDC_BFLD", "bit", "-", "field", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L128-L144
227,317
securestate/termineter
lib/termineter/utilities.py
unique
def unique(seq, idfunc=None): """ Unique a list or tuple and preserve the order @type idfunc: Function or None @param idfunc: If idfunc is provided it will be called during the comparison process. """ if idfunc is None: idfunc = lambda x: x preserved_type = type(seq) seen = {} result = [] for item in seq: marker = idfunc(item) if marker in seen: continue seen[marker] = 1 result.append(item) return preserved_type(result)
python
def unique(seq, idfunc=None): """ Unique a list or tuple and preserve the order @type idfunc: Function or None @param idfunc: If idfunc is provided it will be called during the comparison process. """ if idfunc is None: idfunc = lambda x: x preserved_type = type(seq) seen = {} result = [] for item in seq: marker = idfunc(item) if marker in seen: continue seen[marker] = 1 result.append(item) return preserved_type(result)
[ "def", "unique", "(", "seq", ",", "idfunc", "=", "None", ")", ":", "if", "idfunc", "is", "None", ":", "idfunc", "=", "lambda", "x", ":", "x", "preserved_type", "=", "type", "(", "seq", ")", "seen", "=", "{", "}", "result", "=", "[", "]", "for", "item", "in", "seq", ":", "marker", "=", "idfunc", "(", "item", ")", "if", "marker", "in", "seen", ":", "continue", "seen", "[", "marker", "]", "=", "1", "result", ".", "append", "(", "item", ")", "return", "preserved_type", "(", "result", ")" ]
Unique a list or tuple and preserve the order @type idfunc: Function or None @param idfunc: If idfunc is provided it will be called during the comparison process.
[ "Unique", "a", "list", "or", "tuple", "and", "preserve", "the", "order" ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/utilities.py#L63-L82
227,318
securestate/termineter
lib/termineter/interface.py
InteractiveInterpreter.do_ipy
def do_ipy(self, args): """Start an interactive Python interpreter""" import c1218.data import c1219.data from c1219.access.general import C1219GeneralAccess from c1219.access.security import C1219SecurityAccess from c1219.access.log import C1219LogAccess from c1219.access.telephone import C1219TelephoneAccess vars = { 'termineter.__version__': termineter.__version__, 'C1218Packet': c1218.data.C1218Packet, 'C1218ReadRequest': c1218.data.C1218ReadRequest, 'C1218WriteRequest': c1218.data.C1218WriteRequest, 'C1219ProcedureInit': c1219.data.C1219ProcedureInit, 'C1219GeneralAccess': C1219GeneralAccess, 'C1219SecurityAccess': C1219SecurityAccess, 'C1219LogAccess': C1219LogAccess, 'C1219TelephoneAccess': C1219TelephoneAccess, 'frmwk': self.frmwk, 'os': os, 'sys': sys } banner = 'Python ' + sys.version + ' on ' + sys.platform + os.linesep banner += os.linesep banner += 'The framework instance is in the \'frmwk\' variable.' if self.frmwk.is_serial_connected(): vars['conn'] = self.frmwk.serial_connection banner += os.linesep banner += 'The connection instance is in the \'conn\' variable.' try: import IPython.terminal.embed except ImportError: pyconsole = code.InteractiveConsole(vars) savestdin = os.dup(sys.stdin.fileno()) savestdout = os.dup(sys.stdout.fileno()) savestderr = os.dup(sys.stderr.fileno()) try: pyconsole.interact(banner) except SystemExit: sys.stdin = os.fdopen(savestdin, 'r', 0) sys.stdout = os.fdopen(savestdout, 'w', 0) sys.stderr = os.fdopen(savestderr, 'w', 0) else: self.print_line(banner) pyconsole = IPython.terminal.embed.InteractiveShellEmbed( ipython_dir=os.path.join(self.frmwk.directories.user_data, 'ipython') ) pyconsole.mainloop(vars)
python
def do_ipy(self, args): """Start an interactive Python interpreter""" import c1218.data import c1219.data from c1219.access.general import C1219GeneralAccess from c1219.access.security import C1219SecurityAccess from c1219.access.log import C1219LogAccess from c1219.access.telephone import C1219TelephoneAccess vars = { 'termineter.__version__': termineter.__version__, 'C1218Packet': c1218.data.C1218Packet, 'C1218ReadRequest': c1218.data.C1218ReadRequest, 'C1218WriteRequest': c1218.data.C1218WriteRequest, 'C1219ProcedureInit': c1219.data.C1219ProcedureInit, 'C1219GeneralAccess': C1219GeneralAccess, 'C1219SecurityAccess': C1219SecurityAccess, 'C1219LogAccess': C1219LogAccess, 'C1219TelephoneAccess': C1219TelephoneAccess, 'frmwk': self.frmwk, 'os': os, 'sys': sys } banner = 'Python ' + sys.version + ' on ' + sys.platform + os.linesep banner += os.linesep banner += 'The framework instance is in the \'frmwk\' variable.' if self.frmwk.is_serial_connected(): vars['conn'] = self.frmwk.serial_connection banner += os.linesep banner += 'The connection instance is in the \'conn\' variable.' try: import IPython.terminal.embed except ImportError: pyconsole = code.InteractiveConsole(vars) savestdin = os.dup(sys.stdin.fileno()) savestdout = os.dup(sys.stdout.fileno()) savestderr = os.dup(sys.stderr.fileno()) try: pyconsole.interact(banner) except SystemExit: sys.stdin = os.fdopen(savestdin, 'r', 0) sys.stdout = os.fdopen(savestdout, 'w', 0) sys.stderr = os.fdopen(savestderr, 'w', 0) else: self.print_line(banner) pyconsole = IPython.terminal.embed.InteractiveShellEmbed( ipython_dir=os.path.join(self.frmwk.directories.user_data, 'ipython') ) pyconsole.mainloop(vars)
[ "def", "do_ipy", "(", "self", ",", "args", ")", ":", "import", "c1218", ".", "data", "import", "c1219", ".", "data", "from", "c1219", ".", "access", ".", "general", "import", "C1219GeneralAccess", "from", "c1219", ".", "access", ".", "security", "import", "C1219SecurityAccess", "from", "c1219", ".", "access", ".", "log", "import", "C1219LogAccess", "from", "c1219", ".", "access", ".", "telephone", "import", "C1219TelephoneAccess", "vars", "=", "{", "'termineter.__version__'", ":", "termineter", ".", "__version__", ",", "'C1218Packet'", ":", "c1218", ".", "data", ".", "C1218Packet", ",", "'C1218ReadRequest'", ":", "c1218", ".", "data", ".", "C1218ReadRequest", ",", "'C1218WriteRequest'", ":", "c1218", ".", "data", ".", "C1218WriteRequest", ",", "'C1219ProcedureInit'", ":", "c1219", ".", "data", ".", "C1219ProcedureInit", ",", "'C1219GeneralAccess'", ":", "C1219GeneralAccess", ",", "'C1219SecurityAccess'", ":", "C1219SecurityAccess", ",", "'C1219LogAccess'", ":", "C1219LogAccess", ",", "'C1219TelephoneAccess'", ":", "C1219TelephoneAccess", ",", "'frmwk'", ":", "self", ".", "frmwk", ",", "'os'", ":", "os", ",", "'sys'", ":", "sys", "}", "banner", "=", "'Python '", "+", "sys", ".", "version", "+", "' on '", "+", "sys", ".", "platform", "+", "os", ".", "linesep", "banner", "+=", "os", ".", "linesep", "banner", "+=", "'The framework instance is in the \\'frmwk\\' variable.'", "if", "self", ".", "frmwk", ".", "is_serial_connected", "(", ")", ":", "vars", "[", "'conn'", "]", "=", "self", ".", "frmwk", ".", "serial_connection", "banner", "+=", "os", ".", "linesep", "banner", "+=", "'The connection instance is in the \\'conn\\' variable.'", "try", ":", "import", "IPython", ".", "terminal", ".", "embed", "except", "ImportError", ":", "pyconsole", "=", "code", ".", "InteractiveConsole", "(", "vars", ")", "savestdin", "=", "os", ".", "dup", "(", "sys", ".", "stdin", ".", "fileno", "(", ")", ")", "savestdout", "=", "os", ".", "dup", "(", "sys", ".", "stdout", ".", "fileno", "(", ")", ")", "savestderr", "=", "os", ".", "dup", "(", "sys", ".", "stderr", ".", "fileno", "(", ")", ")", "try", ":", "pyconsole", ".", "interact", "(", "banner", ")", "except", "SystemExit", ":", "sys", ".", "stdin", "=", "os", ".", "fdopen", "(", "savestdin", ",", "'r'", ",", "0", ")", "sys", ".", "stdout", "=", "os", ".", "fdopen", "(", "savestdout", ",", "'w'", ",", "0", ")", "sys", ".", "stderr", "=", "os", ".", "fdopen", "(", "savestderr", ",", "'w'", ",", "0", ")", "else", ":", "self", ".", "print_line", "(", "banner", ")", "pyconsole", "=", "IPython", ".", "terminal", ".", "embed", ".", "InteractiveShellEmbed", "(", "ipython_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "frmwk", ".", "directories", ".", "user_data", ",", "'ipython'", ")", ")", "pyconsole", ".", "mainloop", "(", "vars", ")" ]
Start an interactive Python interpreter
[ "Start", "an", "interactive", "Python", "interpreter" ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/interface.py#L308-L355
227,319
securestate/termineter
lib/termineter/interface.py
InteractiveInterpreter.do_reload
def do_reload(self, args): """Reload a module in to the framework""" if args.module is not None: if args.module not in self.frmwk.modules: self.print_error('Invalid Module Selected.') return module = self.frmwk.modules[args.module] elif self.frmwk.current_module: module = self.frmwk.current_module else: self.print_error('Must \'use\' module first') return self.reload_module(module)
python
def do_reload(self, args): """Reload a module in to the framework""" if args.module is not None: if args.module not in self.frmwk.modules: self.print_error('Invalid Module Selected.') return module = self.frmwk.modules[args.module] elif self.frmwk.current_module: module = self.frmwk.current_module else: self.print_error('Must \'use\' module first') return self.reload_module(module)
[ "def", "do_reload", "(", "self", ",", "args", ")", ":", "if", "args", ".", "module", "is", "not", "None", ":", "if", "args", ".", "module", "not", "in", "self", ".", "frmwk", ".", "modules", ":", "self", ".", "print_error", "(", "'Invalid Module Selected.'", ")", "return", "module", "=", "self", ".", "frmwk", ".", "modules", "[", "args", ".", "module", "]", "elif", "self", ".", "frmwk", ".", "current_module", ":", "module", "=", "self", ".", "frmwk", ".", "current_module", "else", ":", "self", ".", "print_error", "(", "'Must \\'use\\' module first'", ")", "return", "self", ".", "reload_module", "(", "module", ")" ]
Reload a module in to the framework
[ "Reload", "a", "module", "in", "to", "the", "framework" ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/interface.py#L428-L440
227,320
securestate/termineter
lib/c1218/connection.py
ConnectionBase.send
def send(self, data): """ This sends a raw C12.18 frame and waits checks for an ACK response. In the event that a NACK is received, this function will attempt to resend the frame up to 3 times. :param data: the data to be transmitted :type data: str, :py:class:`~c1218.data.C1218Packet` """ if not isinstance(data, C1218Packet): data = C1218Packet(data) if self.toggle_control: # bit wise, fuck yeah if self._toggle_bit: data.set_control(ord(data.control) | 0x20) self._toggle_bit = False elif not self._toggle_bit: if ord(data.control) & 0x20: data.set_control(ord(data.control) ^ 0x20) self._toggle_bit = True elif self.toggle_control and not isinstance(data, C1218Packet): self.loggerio.warning('toggle bit is on but the data is not a C1218Packet instance') data = data.build() self.loggerio.debug("sending frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8'))) for pktcount in range(0, 3): self.write(data) response = self.serial_h.read(1) if response == NACK: self.loggerio.warning('received a NACK after writing data') time.sleep(0.10) elif len(response) == 0: self.loggerio.error('received empty response after writing data') time.sleep(0.10) elif response != ACK: self.loggerio.error('received unknown response: ' + hex(ord(response)) + ' after writing data') else: return self.loggerio.critical('failed 3 times to correctly send a frame') raise C1218IOError('failed 3 times to correctly send a frame')
python
def send(self, data): """ This sends a raw C12.18 frame and waits checks for an ACK response. In the event that a NACK is received, this function will attempt to resend the frame up to 3 times. :param data: the data to be transmitted :type data: str, :py:class:`~c1218.data.C1218Packet` """ if not isinstance(data, C1218Packet): data = C1218Packet(data) if self.toggle_control: # bit wise, fuck yeah if self._toggle_bit: data.set_control(ord(data.control) | 0x20) self._toggle_bit = False elif not self._toggle_bit: if ord(data.control) & 0x20: data.set_control(ord(data.control) ^ 0x20) self._toggle_bit = True elif self.toggle_control and not isinstance(data, C1218Packet): self.loggerio.warning('toggle bit is on but the data is not a C1218Packet instance') data = data.build() self.loggerio.debug("sending frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8'))) for pktcount in range(0, 3): self.write(data) response = self.serial_h.read(1) if response == NACK: self.loggerio.warning('received a NACK after writing data') time.sleep(0.10) elif len(response) == 0: self.loggerio.error('received empty response after writing data') time.sleep(0.10) elif response != ACK: self.loggerio.error('received unknown response: ' + hex(ord(response)) + ' after writing data') else: return self.loggerio.critical('failed 3 times to correctly send a frame') raise C1218IOError('failed 3 times to correctly send a frame')
[ "def", "send", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "C1218Packet", ")", ":", "data", "=", "C1218Packet", "(", "data", ")", "if", "self", ".", "toggle_control", ":", "# bit wise, fuck yeah", "if", "self", ".", "_toggle_bit", ":", "data", ".", "set_control", "(", "ord", "(", "data", ".", "control", ")", "|", "0x20", ")", "self", ".", "_toggle_bit", "=", "False", "elif", "not", "self", ".", "_toggle_bit", ":", "if", "ord", "(", "data", ".", "control", ")", "&", "0x20", ":", "data", ".", "set_control", "(", "ord", "(", "data", ".", "control", ")", "^", "0x20", ")", "self", ".", "_toggle_bit", "=", "True", "elif", "self", ".", "toggle_control", "and", "not", "isinstance", "(", "data", ",", "C1218Packet", ")", ":", "self", ".", "loggerio", ".", "warning", "(", "'toggle bit is on but the data is not a C1218Packet instance'", ")", "data", "=", "data", ".", "build", "(", ")", "self", ".", "loggerio", ".", "debug", "(", "\"sending frame, length: {0:<3} data: {1}\"", ".", "format", "(", "len", "(", "data", ")", ",", "binascii", ".", "b2a_hex", "(", "data", ")", ".", "decode", "(", "'utf-8'", ")", ")", ")", "for", "pktcount", "in", "range", "(", "0", ",", "3", ")", ":", "self", ".", "write", "(", "data", ")", "response", "=", "self", ".", "serial_h", ".", "read", "(", "1", ")", "if", "response", "==", "NACK", ":", "self", ".", "loggerio", ".", "warning", "(", "'received a NACK after writing data'", ")", "time", ".", "sleep", "(", "0.10", ")", "elif", "len", "(", "response", ")", "==", "0", ":", "self", ".", "loggerio", ".", "error", "(", "'received empty response after writing data'", ")", "time", ".", "sleep", "(", "0.10", ")", "elif", "response", "!=", "ACK", ":", "self", ".", "loggerio", ".", "error", "(", "'received unknown response: '", "+", "hex", "(", "ord", "(", "response", ")", ")", "+", "' after writing data'", ")", "else", ":", "return", "self", ".", "loggerio", ".", "critical", "(", "'failed 3 times to correctly send a frame'", ")", "raise", "C1218IOError", "(", "'failed 3 times to correctly send a frame'", ")" ]
This sends a raw C12.18 frame and waits checks for an ACK response. In the event that a NACK is received, this function will attempt to resend the frame up to 3 times. :param data: the data to be transmitted :type data: str, :py:class:`~c1218.data.C1218Packet`
[ "This", "sends", "a", "raw", "C12", ".", "18", "frame", "and", "waits", "checks", "for", "an", "ACK", "response", ".", "In", "the", "event", "that", "a", "NACK", "is", "received", "this", "function", "will", "attempt", "to", "resend", "the", "frame", "up", "to", "3", "times", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L120-L157
227,321
securestate/termineter
lib/c1218/connection.py
ConnectionBase.recv
def recv(self, full_frame=False): """ Receive a C1218Packet, the payload data is returned. :param bool full_frame: If set to True, the entire C1218 frame is returned instead of just the payload. """ payloadbuffer = b'' tries = 3 while tries: tmpbuffer = self.serial_h.read(1) if tmpbuffer != b'\xee': self.loggerio.error('did not receive \\xee as the first byte of the frame') self.loggerio.debug('received \\x' + binascii.b2a_hex(tmpbuffer).decode('utf-8') + ' instead') tries -= 1 continue tmpbuffer += self.serial_h.read(5) sequence, length = struct.unpack('>xxxBH', tmpbuffer) payload = self.serial_h.read(length) tmpbuffer += payload chksum = self.serial_h.read(2) if chksum == packet_checksum(tmpbuffer): self.serial_h.write(ACK) data = tmpbuffer + chksum self.loggerio.debug("received frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8'))) payloadbuffer += payload if sequence == 0: if full_frame: payloadbuffer = data if sys.version_info[0] == 2: payloadbuffer = bytearray(payloadbuffer) return payloadbuffer else: tries = 3 else: self.serial_h.write(NACK) self.loggerio.warning('crc does not match on received frame') tries -= 1 self.loggerio.critical('failed 3 times to correctly receive a frame') raise C1218IOError('failed 3 times to correctly receive a frame')
python
def recv(self, full_frame=False): """ Receive a C1218Packet, the payload data is returned. :param bool full_frame: If set to True, the entire C1218 frame is returned instead of just the payload. """ payloadbuffer = b'' tries = 3 while tries: tmpbuffer = self.serial_h.read(1) if tmpbuffer != b'\xee': self.loggerio.error('did not receive \\xee as the first byte of the frame') self.loggerio.debug('received \\x' + binascii.b2a_hex(tmpbuffer).decode('utf-8') + ' instead') tries -= 1 continue tmpbuffer += self.serial_h.read(5) sequence, length = struct.unpack('>xxxBH', tmpbuffer) payload = self.serial_h.read(length) tmpbuffer += payload chksum = self.serial_h.read(2) if chksum == packet_checksum(tmpbuffer): self.serial_h.write(ACK) data = tmpbuffer + chksum self.loggerio.debug("received frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8'))) payloadbuffer += payload if sequence == 0: if full_frame: payloadbuffer = data if sys.version_info[0] == 2: payloadbuffer = bytearray(payloadbuffer) return payloadbuffer else: tries = 3 else: self.serial_h.write(NACK) self.loggerio.warning('crc does not match on received frame') tries -= 1 self.loggerio.critical('failed 3 times to correctly receive a frame') raise C1218IOError('failed 3 times to correctly receive a frame')
[ "def", "recv", "(", "self", ",", "full_frame", "=", "False", ")", ":", "payloadbuffer", "=", "b''", "tries", "=", "3", "while", "tries", ":", "tmpbuffer", "=", "self", ".", "serial_h", ".", "read", "(", "1", ")", "if", "tmpbuffer", "!=", "b'\\xee'", ":", "self", ".", "loggerio", ".", "error", "(", "'did not receive \\\\xee as the first byte of the frame'", ")", "self", ".", "loggerio", ".", "debug", "(", "'received \\\\x'", "+", "binascii", ".", "b2a_hex", "(", "tmpbuffer", ")", ".", "decode", "(", "'utf-8'", ")", "+", "' instead'", ")", "tries", "-=", "1", "continue", "tmpbuffer", "+=", "self", ".", "serial_h", ".", "read", "(", "5", ")", "sequence", ",", "length", "=", "struct", ".", "unpack", "(", "'>xxxBH'", ",", "tmpbuffer", ")", "payload", "=", "self", ".", "serial_h", ".", "read", "(", "length", ")", "tmpbuffer", "+=", "payload", "chksum", "=", "self", ".", "serial_h", ".", "read", "(", "2", ")", "if", "chksum", "==", "packet_checksum", "(", "tmpbuffer", ")", ":", "self", ".", "serial_h", ".", "write", "(", "ACK", ")", "data", "=", "tmpbuffer", "+", "chksum", "self", ".", "loggerio", ".", "debug", "(", "\"received frame, length: {0:<3} data: {1}\"", ".", "format", "(", "len", "(", "data", ")", ",", "binascii", ".", "b2a_hex", "(", "data", ")", ".", "decode", "(", "'utf-8'", ")", ")", ")", "payloadbuffer", "+=", "payload", "if", "sequence", "==", "0", ":", "if", "full_frame", ":", "payloadbuffer", "=", "data", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "payloadbuffer", "=", "bytearray", "(", "payloadbuffer", ")", "return", "payloadbuffer", "else", ":", "tries", "=", "3", "else", ":", "self", ".", "serial_h", ".", "write", "(", "NACK", ")", "self", ".", "loggerio", ".", "warning", "(", "'crc does not match on received frame'", ")", "tries", "-=", "1", "self", ".", "loggerio", ".", "critical", "(", "'failed 3 times to correctly receive a frame'", ")", "raise", "C1218IOError", "(", "'failed 3 times to correctly receive a frame'", ")" ]
Receive a C1218Packet, the payload data is returned. :param bool full_frame: If set to True, the entire C1218 frame is returned instead of just the payload.
[ "Receive", "a", "C1218Packet", "the", "payload", "data", "is", "returned", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L159-L198
227,322
securestate/termineter
lib/c1218/connection.py
ConnectionBase.read
def read(self, size): """ Read raw data from the serial connection. This function is not meant to be called directly. :param int size: The number of bytes to read from the serial connection. """ data = self.serial_h.read(size) self.logger.debug('read data, length: ' + str(len(data)) + ' data: ' + binascii.b2a_hex(data).decode('utf-8')) self.serial_h.write(ACK) if sys.version_info[0] == 2: data = bytearray(data) return data
python
def read(self, size): """ Read raw data from the serial connection. This function is not meant to be called directly. :param int size: The number of bytes to read from the serial connection. """ data = self.serial_h.read(size) self.logger.debug('read data, length: ' + str(len(data)) + ' data: ' + binascii.b2a_hex(data).decode('utf-8')) self.serial_h.write(ACK) if sys.version_info[0] == 2: data = bytearray(data) return data
[ "def", "read", "(", "self", ",", "size", ")", ":", "data", "=", "self", ".", "serial_h", ".", "read", "(", "size", ")", "self", ".", "logger", ".", "debug", "(", "'read data, length: '", "+", "str", "(", "len", "(", "data", ")", ")", "+", "' data: '", "+", "binascii", ".", "b2a_hex", "(", "data", ")", ".", "decode", "(", "'utf-8'", ")", ")", "self", ".", "serial_h", ".", "write", "(", "ACK", ")", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "data", "=", "bytearray", "(", "data", ")", "return", "data" ]
Read raw data from the serial connection. This function is not meant to be called directly. :param int size: The number of bytes to read from the serial connection.
[ "Read", "raw", "data", "from", "the", "serial", "connection", ".", "This", "function", "is", "not", "meant", "to", "be", "called", "directly", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L210-L222
227,323
securestate/termineter
lib/c1218/connection.py
ConnectionBase.close
def close(self): """ Send a terminate request and then disconnect from the serial device. """ if self._initialized: self.stop() self.logged_in = False return self.serial_h.close()
python
def close(self): """ Send a terminate request and then disconnect from the serial device. """ if self._initialized: self.stop() self.logged_in = False return self.serial_h.close()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_initialized", ":", "self", ".", "stop", "(", ")", "self", ".", "logged_in", "=", "False", "return", "self", ".", "serial_h", ".", "close", "(", ")" ]
Send a terminate request and then disconnect from the serial device.
[ "Send", "a", "terminate", "request", "and", "then", "disconnect", "from", "the", "serial", "device", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L224-L231
227,324
securestate/termineter
lib/c1218/connection.py
Connection.start
def start(self): """ Send an identity request and then a negotiation request. """ self.serial_h.flushOutput() self.serial_h.flushInput() self.send(C1218IdentRequest()) data = self.recv() if data[0] != 0x00: self.logger.error('received incorrect response to identification service request') return False self._initialized = True self.send(C1218NegotiateRequest(self.c1218_pktsize, self.c1218_nbrpkts, baudrate=9600)) data = self.recv() if data[0] != 0x00: self.logger.error('received incorrect response to negotiate service request') self.stop() raise C1218NegotiateError('received incorrect response to negotiate service request', data[0]) return True
python
def start(self): """ Send an identity request and then a negotiation request. """ self.serial_h.flushOutput() self.serial_h.flushInput() self.send(C1218IdentRequest()) data = self.recv() if data[0] != 0x00: self.logger.error('received incorrect response to identification service request') return False self._initialized = True self.send(C1218NegotiateRequest(self.c1218_pktsize, self.c1218_nbrpkts, baudrate=9600)) data = self.recv() if data[0] != 0x00: self.logger.error('received incorrect response to negotiate service request') self.stop() raise C1218NegotiateError('received incorrect response to negotiate service request', data[0]) return True
[ "def", "start", "(", "self", ")", ":", "self", ".", "serial_h", ".", "flushOutput", "(", ")", "self", ".", "serial_h", ".", "flushInput", "(", ")", "self", ".", "send", "(", "C1218IdentRequest", "(", ")", ")", "data", "=", "self", ".", "recv", "(", ")", "if", "data", "[", "0", "]", "!=", "0x00", ":", "self", ".", "logger", ".", "error", "(", "'received incorrect response to identification service request'", ")", "return", "False", "self", ".", "_initialized", "=", "True", "self", ".", "send", "(", "C1218NegotiateRequest", "(", "self", ".", "c1218_pktsize", ",", "self", ".", "c1218_nbrpkts", ",", "baudrate", "=", "9600", ")", ")", "data", "=", "self", ".", "recv", "(", ")", "if", "data", "[", "0", "]", "!=", "0x00", ":", "self", ".", "logger", ".", "error", "(", "'received incorrect response to negotiate service request'", ")", "self", ".", "stop", "(", ")", "raise", "C1218NegotiateError", "(", "'received incorrect response to negotiate service request'", ",", "data", "[", "0", "]", ")", "return", "True" ]
Send an identity request and then a negotiation request.
[ "Send", "an", "identity", "request", "and", "then", "a", "negotiation", "request", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L278-L297
227,325
securestate/termineter
lib/c1218/connection.py
Connection.stop
def stop(self, force=False): """ Send a terminate request. :param bool force: ignore the remote devices response """ if self._initialized: self.send(C1218TerminateRequest()) data = self.recv() if data == b'\x00' or force: self._initialized = False self._toggle_bit = False return True return False
python
def stop(self, force=False): """ Send a terminate request. :param bool force: ignore the remote devices response """ if self._initialized: self.send(C1218TerminateRequest()) data = self.recv() if data == b'\x00' or force: self._initialized = False self._toggle_bit = False return True return False
[ "def", "stop", "(", "self", ",", "force", "=", "False", ")", ":", "if", "self", ".", "_initialized", ":", "self", ".", "send", "(", "C1218TerminateRequest", "(", ")", ")", "data", "=", "self", ".", "recv", "(", ")", "if", "data", "==", "b'\\x00'", "or", "force", ":", "self", ".", "_initialized", "=", "False", "self", ".", "_toggle_bit", "=", "False", "return", "True", "return", "False" ]
Send a terminate request. :param bool force: ignore the remote devices response
[ "Send", "a", "terminate", "request", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L299-L312
227,326
securestate/termineter
lib/c1218/connection.py
Connection.login
def login(self, username='0000', userid=0, password=None): """ Log into the connected device. :param str username: the username to log in with (len(username) <= 10) :param int userid: the userid to log in with (0x0000 <= userid <= 0xffff) :param str password: password to log in with (len(password) <= 20) :rtype: bool """ if password and len(password) > 20: self.logger.error('password longer than 20 characters received') raise Exception('password longer than 20 characters, login failed') self.send(C1218LogonRequest(username, userid)) data = self.recv() if data != b'\x00': self.logger.warning('login failed, username and user id rejected') return False if password is not None: self.send(C1218SecurityRequest(password)) data = self.recv() if data != b'\x00': self.logger.warning('login failed, password rejected') return False self.logged_in = True return True
python
def login(self, username='0000', userid=0, password=None): """ Log into the connected device. :param str username: the username to log in with (len(username) <= 10) :param int userid: the userid to log in with (0x0000 <= userid <= 0xffff) :param str password: password to log in with (len(password) <= 20) :rtype: bool """ if password and len(password) > 20: self.logger.error('password longer than 20 characters received') raise Exception('password longer than 20 characters, login failed') self.send(C1218LogonRequest(username, userid)) data = self.recv() if data != b'\x00': self.logger.warning('login failed, username and user id rejected') return False if password is not None: self.send(C1218SecurityRequest(password)) data = self.recv() if data != b'\x00': self.logger.warning('login failed, password rejected') return False self.logged_in = True return True
[ "def", "login", "(", "self", ",", "username", "=", "'0000'", ",", "userid", "=", "0", ",", "password", "=", "None", ")", ":", "if", "password", "and", "len", "(", "password", ")", ">", "20", ":", "self", ".", "logger", ".", "error", "(", "'password longer than 20 characters received'", ")", "raise", "Exception", "(", "'password longer than 20 characters, login failed'", ")", "self", ".", "send", "(", "C1218LogonRequest", "(", "username", ",", "userid", ")", ")", "data", "=", "self", ".", "recv", "(", ")", "if", "data", "!=", "b'\\x00'", ":", "self", ".", "logger", ".", "warning", "(", "'login failed, username and user id rejected'", ")", "return", "False", "if", "password", "is", "not", "None", ":", "self", ".", "send", "(", "C1218SecurityRequest", "(", "password", ")", ")", "data", "=", "self", ".", "recv", "(", ")", "if", "data", "!=", "b'\\x00'", ":", "self", ".", "logger", ".", "warning", "(", "'login failed, password rejected'", ")", "return", "False", "self", ".", "logged_in", "=", "True", "return", "True" ]
Log into the connected device. :param str username: the username to log in with (len(username) <= 10) :param int userid: the userid to log in with (0x0000 <= userid <= 0xffff) :param str password: password to log in with (len(password) <= 20) :rtype: bool
[ "Log", "into", "the", "connected", "device", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L314-L341
227,327
securestate/termineter
lib/c1218/connection.py
Connection.logoff
def logoff(self): """ Send a logoff request. :rtype: bool """ self.send(C1218LogoffRequest()) data = self.recv() if data == b'\x00': self._initialized = False return True return False
python
def logoff(self): """ Send a logoff request. :rtype: bool """ self.send(C1218LogoffRequest()) data = self.recv() if data == b'\x00': self._initialized = False return True return False
[ "def", "logoff", "(", "self", ")", ":", "self", ".", "send", "(", "C1218LogoffRequest", "(", ")", ")", "data", "=", "self", ".", "recv", "(", ")", "if", "data", "==", "b'\\x00'", ":", "self", ".", "_initialized", "=", "False", "return", "True", "return", "False" ]
Send a logoff request. :rtype: bool
[ "Send", "a", "logoff", "request", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L343-L354
227,328
securestate/termineter
lib/c1218/connection.py
Connection.get_table_data
def get_table_data(self, tableid, octetcount=None, offset=None): """ Read data from a table. If successful, all of the data from the requested table will be returned. :param int tableid: The table number to read from (0x0000 <= tableid <= 0xffff) :param int octetcount: Limit the amount of data read, only works if the meter supports this type of reading. :param int offset: The offset at which to start to read the data from. """ if self.caching_enabled and tableid in self._cacheable_tables and tableid in self._table_cache.keys(): self.logger.info('returning cached table #' + str(tableid)) return self._table_cache[tableid] self.send(C1218ReadRequest(tableid, offset, octetcount)) data = self.recv() status = data[0] if status != 0x00: status = status details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code') self.logger.error('could not read table id: ' + str(tableid) + ', error: ' + details) raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: ' + details, status) if len(data) < 4: if len(data) == 0: self.logger.error('could not read table id: ' + str(tableid) + ', error: no data was returned') raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: no data was returned') self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)') raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)') length = struct.unpack('>H', data[1:3])[0] chksum = data[-1] data = data[3:-1] if len(data) != length: self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length') raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length') if not check_data_checksum(data, chksum): self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid check sum') raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid checksum') if self.caching_enabled and tableid in self._cacheable_tables and not tableid in self._table_cache.keys(): self.logger.info('caching table #' + str(tableid)) self._table_cache[tableid] = data return data
python
def get_table_data(self, tableid, octetcount=None, offset=None): """ Read data from a table. If successful, all of the data from the requested table will be returned. :param int tableid: The table number to read from (0x0000 <= tableid <= 0xffff) :param int octetcount: Limit the amount of data read, only works if the meter supports this type of reading. :param int offset: The offset at which to start to read the data from. """ if self.caching_enabled and tableid in self._cacheable_tables and tableid in self._table_cache.keys(): self.logger.info('returning cached table #' + str(tableid)) return self._table_cache[tableid] self.send(C1218ReadRequest(tableid, offset, octetcount)) data = self.recv() status = data[0] if status != 0x00: status = status details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code') self.logger.error('could not read table id: ' + str(tableid) + ', error: ' + details) raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: ' + details, status) if len(data) < 4: if len(data) == 0: self.logger.error('could not read table id: ' + str(tableid) + ', error: no data was returned') raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: no data was returned') self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)') raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)') length = struct.unpack('>H', data[1:3])[0] chksum = data[-1] data = data[3:-1] if len(data) != length: self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length') raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length') if not check_data_checksum(data, chksum): self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid check sum') raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid checksum') if self.caching_enabled and tableid in self._cacheable_tables and not tableid in self._table_cache.keys(): self.logger.info('caching table #' + str(tableid)) self._table_cache[tableid] = data return data
[ "def", "get_table_data", "(", "self", ",", "tableid", ",", "octetcount", "=", "None", ",", "offset", "=", "None", ")", ":", "if", "self", ".", "caching_enabled", "and", "tableid", "in", "self", ".", "_cacheable_tables", "and", "tableid", "in", "self", ".", "_table_cache", ".", "keys", "(", ")", ":", "self", ".", "logger", ".", "info", "(", "'returning cached table #'", "+", "str", "(", "tableid", ")", ")", "return", "self", ".", "_table_cache", "[", "tableid", "]", "self", ".", "send", "(", "C1218ReadRequest", "(", "tableid", ",", "offset", ",", "octetcount", ")", ")", "data", "=", "self", ".", "recv", "(", ")", "status", "=", "data", "[", "0", "]", "if", "status", "!=", "0x00", ":", "status", "=", "status", "details", "=", "(", "C1218_RESPONSE_CODES", ".", "get", "(", "status", ")", "or", "'unknown response code'", ")", "self", ".", "logger", ".", "error", "(", "'could not read table id: '", "+", "str", "(", "tableid", ")", "+", "', error: '", "+", "details", ")", "raise", "C1218ReadTableError", "(", "'could not read table id: '", "+", "str", "(", "tableid", ")", "+", "', error: '", "+", "details", ",", "status", ")", "if", "len", "(", "data", ")", "<", "4", ":", "if", "len", "(", "data", ")", "==", "0", ":", "self", ".", "logger", ".", "error", "(", "'could not read table id: '", "+", "str", "(", "tableid", ")", "+", "', error: no data was returned'", ")", "raise", "C1218ReadTableError", "(", "'could not read table id: '", "+", "str", "(", "tableid", ")", "+", "', error: no data was returned'", ")", "self", ".", "logger", ".", "error", "(", "'could not read table id: '", "+", "str", "(", "tableid", ")", "+", "', error: data read was corrupt, invalid length (less than 4)'", ")", "raise", "C1218ReadTableError", "(", "'could not read table id: '", "+", "str", "(", "tableid", ")", "+", "', error: data read was corrupt, invalid length (less than 4)'", ")", "length", "=", "struct", ".", "unpack", "(", "'>H'", ",", "data", "[", "1", ":", "3", "]", ")", "[", "0", "]", "chksum", "=", "data", "[", "-", "1", "]", "data", "=", "data", "[", "3", ":", "-", "1", "]", "if", "len", "(", "data", ")", "!=", "length", ":", "self", ".", "logger", ".", "error", "(", "'could not read table id: '", "+", "str", "(", "tableid", ")", "+", "', error: data read was corrupt, invalid length'", ")", "raise", "C1218ReadTableError", "(", "'could not read table id: '", "+", "str", "(", "tableid", ")", "+", "', error: data read was corrupt, invalid length'", ")", "if", "not", "check_data_checksum", "(", "data", ",", "chksum", ")", ":", "self", ".", "logger", ".", "error", "(", "'could not read table id: '", "+", "str", "(", "tableid", ")", "+", "', error: data read was corrupt, invalid check sum'", ")", "raise", "C1218ReadTableError", "(", "'could not read table id: '", "+", "str", "(", "tableid", ")", "+", "', error: data read was corrupt, invalid checksum'", ")", "if", "self", ".", "caching_enabled", "and", "tableid", "in", "self", ".", "_cacheable_tables", "and", "not", "tableid", "in", "self", ".", "_table_cache", ".", "keys", "(", ")", ":", "self", ".", "logger", ".", "info", "(", "'caching table #'", "+", "str", "(", "tableid", ")", ")", "self", ".", "_table_cache", "[", "tableid", "]", "=", "data", "return", "data" ]
Read data from a table. If successful, all of the data from the requested table will be returned. :param int tableid: The table number to read from (0x0000 <= tableid <= 0xffff) :param int octetcount: Limit the amount of data read, only works if the meter supports this type of reading. :param int offset: The offset at which to start to read the data from.
[ "Read", "data", "from", "a", "table", ".", "If", "successful", "all", "of", "the", "data", "from", "the", "requested", "table", "will", "be", "returned", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L356-L396
227,329
securestate/termineter
lib/c1218/connection.py
Connection.set_table_data
def set_table_data(self, tableid, data, offset=None): """ Write data to a table. :param int tableid: The table number to write to (0x0000 <= tableid <= 0xffff) :param str data: The data to write into the table. :param int offset: The offset at which to start to write the data (0x000000 <= octetcount <= 0xffffff). """ self.send(C1218WriteRequest(tableid, data, offset)) data = self.recv() if data[0] != 0x00: status = data[0] details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code') self.logger.error('could not write data to the table, error: ' + details) raise C1218WriteTableError('could not write data to the table, error: ' + details, status) return
python
def set_table_data(self, tableid, data, offset=None): """ Write data to a table. :param int tableid: The table number to write to (0x0000 <= tableid <= 0xffff) :param str data: The data to write into the table. :param int offset: The offset at which to start to write the data (0x000000 <= octetcount <= 0xffffff). """ self.send(C1218WriteRequest(tableid, data, offset)) data = self.recv() if data[0] != 0x00: status = data[0] details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code') self.logger.error('could not write data to the table, error: ' + details) raise C1218WriteTableError('could not write data to the table, error: ' + details, status) return
[ "def", "set_table_data", "(", "self", ",", "tableid", ",", "data", ",", "offset", "=", "None", ")", ":", "self", ".", "send", "(", "C1218WriteRequest", "(", "tableid", ",", "data", ",", "offset", ")", ")", "data", "=", "self", ".", "recv", "(", ")", "if", "data", "[", "0", "]", "!=", "0x00", ":", "status", "=", "data", "[", "0", "]", "details", "=", "(", "C1218_RESPONSE_CODES", ".", "get", "(", "status", ")", "or", "'unknown response code'", ")", "self", ".", "logger", ".", "error", "(", "'could not write data to the table, error: '", "+", "details", ")", "raise", "C1218WriteTableError", "(", "'could not write data to the table, error: '", "+", "details", ",", "status", ")", "return" ]
Write data to a table. :param int tableid: The table number to write to (0x0000 <= tableid <= 0xffff) :param str data: The data to write into the table. :param int offset: The offset at which to start to write the data (0x000000 <= octetcount <= 0xffffff).
[ "Write", "data", "to", "a", "table", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L398-L413
227,330
securestate/termineter
lib/c1218/connection.py
Connection.run_procedure
def run_procedure(self, process_number, std_vs_mfg, params=''): """ Initiate a C1219 procedure, the request is written to table 7 and the response is read from table 8. :param int process_number: The numeric procedure identifier (0 <= process_number <= 2047). :param bool std_vs_mfg: Whether the procedure is manufacturer specified or not. True is manufacturer specified. :param bytes params: The parameters to pass to the procedure initiation request. :return: A tuple of the result code and the response data. :rtype: tuple """ seqnum = random.randint(2, 254) self.logger.info('starting procedure: ' + str(process_number) + ' (' + hex(process_number) + ') sequence number: ' + str(seqnum) + ' (' + hex(seqnum) + ')') procedure_request = C1219ProcedureInit(self.c1219_endian, process_number, std_vs_mfg, 0, seqnum, params).build() self.set_table_data(7, procedure_request) response = self.get_table_data(8) if response[:3] == procedure_request[:3]: return response[3], response[4:] else: self.logger.error('invalid response from procedure response table (table #8)') raise C1219ProcedureError('invalid response from procedure response table (table #8)')
python
def run_procedure(self, process_number, std_vs_mfg, params=''): """ Initiate a C1219 procedure, the request is written to table 7 and the response is read from table 8. :param int process_number: The numeric procedure identifier (0 <= process_number <= 2047). :param bool std_vs_mfg: Whether the procedure is manufacturer specified or not. True is manufacturer specified. :param bytes params: The parameters to pass to the procedure initiation request. :return: A tuple of the result code and the response data. :rtype: tuple """ seqnum = random.randint(2, 254) self.logger.info('starting procedure: ' + str(process_number) + ' (' + hex(process_number) + ') sequence number: ' + str(seqnum) + ' (' + hex(seqnum) + ')') procedure_request = C1219ProcedureInit(self.c1219_endian, process_number, std_vs_mfg, 0, seqnum, params).build() self.set_table_data(7, procedure_request) response = self.get_table_data(8) if response[:3] == procedure_request[:3]: return response[3], response[4:] else: self.logger.error('invalid response from procedure response table (table #8)') raise C1219ProcedureError('invalid response from procedure response table (table #8)')
[ "def", "run_procedure", "(", "self", ",", "process_number", ",", "std_vs_mfg", ",", "params", "=", "''", ")", ":", "seqnum", "=", "random", ".", "randint", "(", "2", ",", "254", ")", "self", ".", "logger", ".", "info", "(", "'starting procedure: '", "+", "str", "(", "process_number", ")", "+", "' ('", "+", "hex", "(", "process_number", ")", "+", "') sequence number: '", "+", "str", "(", "seqnum", ")", "+", "' ('", "+", "hex", "(", "seqnum", ")", "+", "')'", ")", "procedure_request", "=", "C1219ProcedureInit", "(", "self", ".", "c1219_endian", ",", "process_number", ",", "std_vs_mfg", ",", "0", ",", "seqnum", ",", "params", ")", ".", "build", "(", ")", "self", ".", "set_table_data", "(", "7", ",", "procedure_request", ")", "response", "=", "self", ".", "get_table_data", "(", "8", ")", "if", "response", "[", ":", "3", "]", "==", "procedure_request", "[", ":", "3", "]", ":", "return", "response", "[", "3", "]", ",", "response", "[", "4", ":", "]", "else", ":", "self", ".", "logger", ".", "error", "(", "'invalid response from procedure response table (table #8)'", ")", "raise", "C1219ProcedureError", "(", "'invalid response from procedure response table (table #8)'", ")" ]
Initiate a C1219 procedure, the request is written to table 7 and the response is read from table 8. :param int process_number: The numeric procedure identifier (0 <= process_number <= 2047). :param bool std_vs_mfg: Whether the procedure is manufacturer specified or not. True is manufacturer specified. :param bytes params: The parameters to pass to the procedure initiation request. :return: A tuple of the result code and the response data. :rtype: tuple
[ "Initiate", "a", "C1219", "procedure", "the", "request", "is", "written", "to", "table", "7", "and", "the", "response", "is", "read", "from", "table", "8", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L415-L437
227,331
securestate/termineter
lib/termineter/options.py
Options.add_string
def add_string(self, name, help, required=True, default=None): """ Add a new option with a type of String. :param str name: The name of the option, how it will be referenced. :param str help: The string returned as help to describe how the option is used. :param bool required: Whether to require that this option be set or not. :param str default: The default value for this option. If required is True and the user must specify it, set to anything but None. """ self._options[name] = Option(name, 'str', help, required, default=default)
python
def add_string(self, name, help, required=True, default=None): """ Add a new option with a type of String. :param str name: The name of the option, how it will be referenced. :param str help: The string returned as help to describe how the option is used. :param bool required: Whether to require that this option be set or not. :param str default: The default value for this option. If required is True and the user must specify it, set to anything but None. """ self._options[name] = Option(name, 'str', help, required, default=default)
[ "def", "add_string", "(", "self", ",", "name", ",", "help", ",", "required", "=", "True", ",", "default", "=", "None", ")", ":", "self", ".", "_options", "[", "name", "]", "=", "Option", "(", "name", ",", "'str'", ",", "help", ",", "required", ",", "default", "=", "default", ")" ]
Add a new option with a type of String. :param str name: The name of the option, how it will be referenced. :param str help: The string returned as help to describe how the option is used. :param bool required: Whether to require that this option be set or not. :param str default: The default value for this option. If required is True and the user must specify it, set to anything but None.
[ "Add", "a", "new", "option", "with", "a", "type", "of", "String", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/options.py#L80-L89
227,332
securestate/termineter
lib/termineter/options.py
Options.set_option_value
def set_option_value(self, name, value): """ Set an option's value. :param str name: The name of the option to set the value for. :param str value: The value to set the option to, it will be converted from a string. :return: The previous value for the specified option. """ option = self.get_option(name) old_value = option.value if option.type in ('str', 'rfile'): option.value = value elif option.type == 'int': value = value.lower() if not value.isdigit(): if value.startswith('0x') and string_is_hex(value[2:]): value = int(value[2:], 16) else: raise TypeError('invalid value type') option.value = int(value) elif option.type == 'flt': if value.count('.') > 1: raise TypeError('invalid value type') if not value.replace('.', '').isdigit(): raise TypeError('invalid value type') option.value = float(value) elif option.type == 'bool': if value.lower() in ['true', '1', 'on']: option.value = True elif value.lower() in ['false', '0', 'off']: option.value = False else: raise TypeError('invalid value type') else: raise Exception('unknown value type') if option.callback and not option.callback(value, old_value): option.value = old_value return False return True
python
def set_option_value(self, name, value): """ Set an option's value. :param str name: The name of the option to set the value for. :param str value: The value to set the option to, it will be converted from a string. :return: The previous value for the specified option. """ option = self.get_option(name) old_value = option.value if option.type in ('str', 'rfile'): option.value = value elif option.type == 'int': value = value.lower() if not value.isdigit(): if value.startswith('0x') and string_is_hex(value[2:]): value = int(value[2:], 16) else: raise TypeError('invalid value type') option.value = int(value) elif option.type == 'flt': if value.count('.') > 1: raise TypeError('invalid value type') if not value.replace('.', '').isdigit(): raise TypeError('invalid value type') option.value = float(value) elif option.type == 'bool': if value.lower() in ['true', '1', 'on']: option.value = True elif value.lower() in ['false', '0', 'off']: option.value = False else: raise TypeError('invalid value type') else: raise Exception('unknown value type') if option.callback and not option.callback(value, old_value): option.value = old_value return False return True
[ "def", "set_option_value", "(", "self", ",", "name", ",", "value", ")", ":", "option", "=", "self", ".", "get_option", "(", "name", ")", "old_value", "=", "option", ".", "value", "if", "option", ".", "type", "in", "(", "'str'", ",", "'rfile'", ")", ":", "option", ".", "value", "=", "value", "elif", "option", ".", "type", "==", "'int'", ":", "value", "=", "value", ".", "lower", "(", ")", "if", "not", "value", ".", "isdigit", "(", ")", ":", "if", "value", ".", "startswith", "(", "'0x'", ")", "and", "string_is_hex", "(", "value", "[", "2", ":", "]", ")", ":", "value", "=", "int", "(", "value", "[", "2", ":", "]", ",", "16", ")", "else", ":", "raise", "TypeError", "(", "'invalid value type'", ")", "option", ".", "value", "=", "int", "(", "value", ")", "elif", "option", ".", "type", "==", "'flt'", ":", "if", "value", ".", "count", "(", "'.'", ")", ">", "1", ":", "raise", "TypeError", "(", "'invalid value type'", ")", "if", "not", "value", ".", "replace", "(", "'.'", ",", "''", ")", ".", "isdigit", "(", ")", ":", "raise", "TypeError", "(", "'invalid value type'", ")", "option", ".", "value", "=", "float", "(", "value", ")", "elif", "option", ".", "type", "==", "'bool'", ":", "if", "value", ".", "lower", "(", ")", "in", "[", "'true'", ",", "'1'", ",", "'on'", "]", ":", "option", ".", "value", "=", "True", "elif", "value", ".", "lower", "(", ")", "in", "[", "'false'", ",", "'0'", ",", "'off'", "]", ":", "option", ".", "value", "=", "False", "else", ":", "raise", "TypeError", "(", "'invalid value type'", ")", "else", ":", "raise", "Exception", "(", "'unknown value type'", ")", "if", "option", ".", "callback", "and", "not", "option", ".", "callback", "(", "value", ",", "old_value", ")", ":", "option", ".", "value", "=", "old_value", "return", "False", "return", "True" ]
Set an option's value. :param str name: The name of the option to set the value for. :param str value: The value to set the option to, it will be converted from a string. :return: The previous value for the specified option.
[ "Set", "an", "option", "s", "value", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/options.py#L153-L191
227,333
securestate/termineter
lib/termineter/options.py
Options.get_missing_options
def get_missing_options(self): """ Get a list of options that are required, but with default values of None. """ return [option.name for option in self._options.values() if option.required and option.value is None]
python
def get_missing_options(self): """ Get a list of options that are required, but with default values of None. """ return [option.name for option in self._options.values() if option.required and option.value is None]
[ "def", "get_missing_options", "(", "self", ")", ":", "return", "[", "option", ".", "name", "for", "option", "in", "self", ".", "_options", ".", "values", "(", ")", "if", "option", ".", "required", "and", "option", ".", "value", "is", "None", "]" ]
Get a list of options that are required, but with default values of None.
[ "Get", "a", "list", "of", "options", "that", "are", "required", "but", "with", "default", "values", "of", "None", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/options.py#L193-L198
227,334
securestate/termineter
lib/termineter/__init__.py
get_revision
def get_revision(): """ Retrieve the current git revision identifier. If the git binary can not be found or the repository information is unavailable, None will be returned. :return: The git revision tag if it's available. :rtype: str """ git_bin = smoke_zephyr.utilities.which('git') if not git_bin: return None proc_h = subprocess.Popen( (git_bin, 'rev-parse', 'HEAD'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=os.path.dirname(os.path.abspath(__file__)) ) rev = proc_h.stdout.read().strip() proc_h.wait() if not len(rev): return None return rev.decode('utf-8')
python
def get_revision(): """ Retrieve the current git revision identifier. If the git binary can not be found or the repository information is unavailable, None will be returned. :return: The git revision tag if it's available. :rtype: str """ git_bin = smoke_zephyr.utilities.which('git') if not git_bin: return None proc_h = subprocess.Popen( (git_bin, 'rev-parse', 'HEAD'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=os.path.dirname(os.path.abspath(__file__)) ) rev = proc_h.stdout.read().strip() proc_h.wait() if not len(rev): return None return rev.decode('utf-8')
[ "def", "get_revision", "(", ")", ":", "git_bin", "=", "smoke_zephyr", ".", "utilities", ".", "which", "(", "'git'", ")", "if", "not", "git_bin", ":", "return", "None", "proc_h", "=", "subprocess", ".", "Popen", "(", "(", "git_bin", ",", "'rev-parse'", ",", "'HEAD'", ")", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "close_fds", "=", "True", ",", "cwd", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ")", "rev", "=", "proc_h", ".", "stdout", ".", "read", "(", ")", ".", "strip", "(", ")", "proc_h", ".", "wait", "(", ")", "if", "not", "len", "(", "rev", ")", ":", "return", "None", "return", "rev", ".", "decode", "(", "'utf-8'", ")" ]
Retrieve the current git revision identifier. If the git binary can not be found or the repository information is unavailable, None will be returned. :return: The git revision tag if it's available. :rtype: str
[ "Retrieve", "the", "current", "git", "revision", "identifier", ".", "If", "the", "git", "binary", "can", "not", "be", "found", "or", "the", "repository", "information", "is", "unavailable", "None", "will", "be", "returned", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/__init__.py#L42-L64
227,335
securestate/termineter
lib/termineter/core.py
Framework.reload_module
def reload_module(self, module_path=None): """ Reloads a module into the framework. If module_path is not specified, then the current_module variable is used. Returns True on success, False on error. @type module_path: String @param module_path: The name of the module to reload """ if module_path is None: if self.current_module is not None: module_path = self.current_module.name else: self.logger.warning('must specify module if not module is currently being used') return False if module_path not in self.module: self.logger.error('invalid module requested for reload') raise termineter.errors.FrameworkRuntimeError('invalid module requested for reload') self.logger.info('reloading module: ' + module_path) module_instance = self.import_module(module_path, reload_module=True) if not isinstance(module_instance, termineter.module.TermineterModule): self.logger.error('module: ' + module_path + ' is not derived from the TermineterModule class') raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' is not derived from the TermineterModule class') if not hasattr(module_instance, 'run'): self.logger.error('module: ' + module_path + ' has no run() method') raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' has no run() method') if not isinstance(module_instance.options, termineter.options.Options) or not isinstance(module_instance.advanced_options, termineter.options.Options): self.logger.error('module: ' + module_path + ' options and advanced_options must be termineter.options.Options instances') raise termineter.errors.FrameworkRuntimeError('options and advanced_options must be termineter.options.Options instances') module_instance.name = module_path.split('/')[-1] module_instance.path = module_path self.modules[module_path] = module_instance if self.current_module is not None: if self.current_module.path == module_instance.path: self.current_module = module_instance return True
python
def reload_module(self, module_path=None): """ Reloads a module into the framework. If module_path is not specified, then the current_module variable is used. Returns True on success, False on error. @type module_path: String @param module_path: The name of the module to reload """ if module_path is None: if self.current_module is not None: module_path = self.current_module.name else: self.logger.warning('must specify module if not module is currently being used') return False if module_path not in self.module: self.logger.error('invalid module requested for reload') raise termineter.errors.FrameworkRuntimeError('invalid module requested for reload') self.logger.info('reloading module: ' + module_path) module_instance = self.import_module(module_path, reload_module=True) if not isinstance(module_instance, termineter.module.TermineterModule): self.logger.error('module: ' + module_path + ' is not derived from the TermineterModule class') raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' is not derived from the TermineterModule class') if not hasattr(module_instance, 'run'): self.logger.error('module: ' + module_path + ' has no run() method') raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' has no run() method') if not isinstance(module_instance.options, termineter.options.Options) or not isinstance(module_instance.advanced_options, termineter.options.Options): self.logger.error('module: ' + module_path + ' options and advanced_options must be termineter.options.Options instances') raise termineter.errors.FrameworkRuntimeError('options and advanced_options must be termineter.options.Options instances') module_instance.name = module_path.split('/')[-1] module_instance.path = module_path self.modules[module_path] = module_instance if self.current_module is not None: if self.current_module.path == module_instance.path: self.current_module = module_instance return True
[ "def", "reload_module", "(", "self", ",", "module_path", "=", "None", ")", ":", "if", "module_path", "is", "None", ":", "if", "self", ".", "current_module", "is", "not", "None", ":", "module_path", "=", "self", ".", "current_module", ".", "name", "else", ":", "self", ".", "logger", ".", "warning", "(", "'must specify module if not module is currently being used'", ")", "return", "False", "if", "module_path", "not", "in", "self", ".", "module", ":", "self", ".", "logger", ".", "error", "(", "'invalid module requested for reload'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkRuntimeError", "(", "'invalid module requested for reload'", ")", "self", ".", "logger", ".", "info", "(", "'reloading module: '", "+", "module_path", ")", "module_instance", "=", "self", ".", "import_module", "(", "module_path", ",", "reload_module", "=", "True", ")", "if", "not", "isinstance", "(", "module_instance", ",", "termineter", ".", "module", ".", "TermineterModule", ")", ":", "self", ".", "logger", ".", "error", "(", "'module: '", "+", "module_path", "+", "' is not derived from the TermineterModule class'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkRuntimeError", "(", "'module: '", "+", "module_path", "+", "' is not derived from the TermineterModule class'", ")", "if", "not", "hasattr", "(", "module_instance", ",", "'run'", ")", ":", "self", ".", "logger", ".", "error", "(", "'module: '", "+", "module_path", "+", "' has no run() method'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkRuntimeError", "(", "'module: '", "+", "module_path", "+", "' has no run() method'", ")", "if", "not", "isinstance", "(", "module_instance", ".", "options", ",", "termineter", ".", "options", ".", "Options", ")", "or", "not", "isinstance", "(", "module_instance", ".", "advanced_options", ",", "termineter", ".", "options", ".", "Options", ")", ":", "self", ".", "logger", ".", "error", "(", "'module: '", "+", "module_path", "+", "' options and advanced_options must be termineter.options.Options instances'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkRuntimeError", "(", "'options and advanced_options must be termineter.options.Options instances'", ")", "module_instance", ".", "name", "=", "module_path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "module_instance", ".", "path", "=", "module_path", "self", ".", "modules", "[", "module_path", "]", "=", "module_instance", "if", "self", ".", "current_module", "is", "not", "None", ":", "if", "self", ".", "current_module", ".", "path", "==", "module_instance", ".", "path", ":", "self", ".", "current_module", "=", "module_instance", "return", "True" ]
Reloads a module into the framework. If module_path is not specified, then the current_module variable is used. Returns True on success, False on error. @type module_path: String @param module_path: The name of the module to reload
[ "Reloads", "a", "module", "into", "the", "framework", ".", "If", "module_path", "is", "not", "specified", "then", "the", "current_module", "variable", "is", "used", ".", "Returns", "True", "on", "success", "False", "on", "error", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L168-L204
227,336
securestate/termineter
lib/termineter/core.py
Framework.serial_disconnect
def serial_disconnect(self): """ Closes the serial connection to the meter and disconnects from the device. """ if self._serial_connected: try: self.serial_connection.close() except c1218.errors.C1218IOError as error: self.logger.error('caught C1218IOError: ' + str(error)) except serial.serialutil.SerialException as error: self.logger.error('caught SerialException: ' + str(error)) self._serial_connected = False self.logger.warning('the serial interface has been disconnected') return True
python
def serial_disconnect(self): """ Closes the serial connection to the meter and disconnects from the device. """ if self._serial_connected: try: self.serial_connection.close() except c1218.errors.C1218IOError as error: self.logger.error('caught C1218IOError: ' + str(error)) except serial.serialutil.SerialException as error: self.logger.error('caught SerialException: ' + str(error)) self._serial_connected = False self.logger.warning('the serial interface has been disconnected') return True
[ "def", "serial_disconnect", "(", "self", ")", ":", "if", "self", ".", "_serial_connected", ":", "try", ":", "self", ".", "serial_connection", ".", "close", "(", ")", "except", "c1218", ".", "errors", ".", "C1218IOError", "as", "error", ":", "self", ".", "logger", ".", "error", "(", "'caught C1218IOError: '", "+", "str", "(", "error", ")", ")", "except", "serial", ".", "serialutil", ".", "SerialException", "as", "error", ":", "self", ".", "logger", ".", "error", "(", "'caught SerialException: '", "+", "str", "(", "error", ")", ")", "self", ".", "_serial_connected", "=", "False", "self", ".", "logger", ".", "warning", "(", "'the serial interface has been disconnected'", ")", "return", "True" ]
Closes the serial connection to the meter and disconnects from the device.
[ "Closes", "the", "serial", "connection", "to", "the", "meter", "and", "disconnects", "from", "the", "device", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L324-L338
227,337
securestate/termineter
lib/termineter/core.py
Framework.serial_get
def serial_get(self): """ Create the serial connection from the framework settings and return it, setting the framework instance in the process. """ frmwk_c1218_settings = { 'nbrpkts': self.advanced_options['C1218_MAX_PACKETS'], 'pktsize': self.advanced_options['C1218_PACKET_SIZE'] } frmwk_serial_settings = termineter.utilities.get_default_serial_settings() frmwk_serial_settings['baudrate'] = self.advanced_options['SERIAL_BAUD_RATE'] frmwk_serial_settings['bytesize'] = self.advanced_options['SERIAL_BYTE_SIZE'] frmwk_serial_settings['stopbits'] = self.advanced_options['SERIAL_STOP_BITS'] self.logger.info('opening serial device: ' + self.options['SERIAL_CONNECTION']) try: self.serial_connection = c1218.connection.Connection(self.options['SERIAL_CONNECTION'], c1218_settings=frmwk_c1218_settings, serial_settings=frmwk_serial_settings, enable_cache=self.advanced_options['CACHE_TABLES']) except Exception as error: self.logger.error('could not open the serial device') raise error return self.serial_connection
python
def serial_get(self): """ Create the serial connection from the framework settings and return it, setting the framework instance in the process. """ frmwk_c1218_settings = { 'nbrpkts': self.advanced_options['C1218_MAX_PACKETS'], 'pktsize': self.advanced_options['C1218_PACKET_SIZE'] } frmwk_serial_settings = termineter.utilities.get_default_serial_settings() frmwk_serial_settings['baudrate'] = self.advanced_options['SERIAL_BAUD_RATE'] frmwk_serial_settings['bytesize'] = self.advanced_options['SERIAL_BYTE_SIZE'] frmwk_serial_settings['stopbits'] = self.advanced_options['SERIAL_STOP_BITS'] self.logger.info('opening serial device: ' + self.options['SERIAL_CONNECTION']) try: self.serial_connection = c1218.connection.Connection(self.options['SERIAL_CONNECTION'], c1218_settings=frmwk_c1218_settings, serial_settings=frmwk_serial_settings, enable_cache=self.advanced_options['CACHE_TABLES']) except Exception as error: self.logger.error('could not open the serial device') raise error return self.serial_connection
[ "def", "serial_get", "(", "self", ")", ":", "frmwk_c1218_settings", "=", "{", "'nbrpkts'", ":", "self", ".", "advanced_options", "[", "'C1218_MAX_PACKETS'", "]", ",", "'pktsize'", ":", "self", ".", "advanced_options", "[", "'C1218_PACKET_SIZE'", "]", "}", "frmwk_serial_settings", "=", "termineter", ".", "utilities", ".", "get_default_serial_settings", "(", ")", "frmwk_serial_settings", "[", "'baudrate'", "]", "=", "self", ".", "advanced_options", "[", "'SERIAL_BAUD_RATE'", "]", "frmwk_serial_settings", "[", "'bytesize'", "]", "=", "self", ".", "advanced_options", "[", "'SERIAL_BYTE_SIZE'", "]", "frmwk_serial_settings", "[", "'stopbits'", "]", "=", "self", ".", "advanced_options", "[", "'SERIAL_STOP_BITS'", "]", "self", ".", "logger", ".", "info", "(", "'opening serial device: '", "+", "self", ".", "options", "[", "'SERIAL_CONNECTION'", "]", ")", "try", ":", "self", ".", "serial_connection", "=", "c1218", ".", "connection", ".", "Connection", "(", "self", ".", "options", "[", "'SERIAL_CONNECTION'", "]", ",", "c1218_settings", "=", "frmwk_c1218_settings", ",", "serial_settings", "=", "frmwk_serial_settings", ",", "enable_cache", "=", "self", ".", "advanced_options", "[", "'CACHE_TABLES'", "]", ")", "except", "Exception", "as", "error", ":", "self", ".", "logger", ".", "error", "(", "'could not open the serial device'", ")", "raise", "error", "return", "self", ".", "serial_connection" ]
Create the serial connection from the framework settings and return it, setting the framework instance in the process.
[ "Create", "the", "serial", "connection", "from", "the", "framework", "settings", "and", "return", "it", "setting", "the", "framework", "instance", "in", "the", "process", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L340-L361
227,338
securestate/termineter
lib/termineter/core.py
Framework.serial_connect
def serial_connect(self): """ Connect to the serial device. """ self.serial_get() try: self.serial_connection.start() except c1218.errors.C1218IOError as error: self.logger.error('serial connection has been opened but the meter is unresponsive') raise error self._serial_connected = True return True
python
def serial_connect(self): """ Connect to the serial device. """ self.serial_get() try: self.serial_connection.start() except c1218.errors.C1218IOError as error: self.logger.error('serial connection has been opened but the meter is unresponsive') raise error self._serial_connected = True return True
[ "def", "serial_connect", "(", "self", ")", ":", "self", ".", "serial_get", "(", ")", "try", ":", "self", ".", "serial_connection", ".", "start", "(", ")", "except", "c1218", ".", "errors", ".", "C1218IOError", "as", "error", ":", "self", ".", "logger", ".", "error", "(", "'serial connection has been opened but the meter is unresponsive'", ")", "raise", "error", "self", ".", "_serial_connected", "=", "True", "return", "True" ]
Connect to the serial device.
[ "Connect", "to", "the", "serial", "device", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L363-L374
227,339
securestate/termineter
lib/termineter/core.py
Framework.serial_login
def serial_login(self): """ Attempt to log into the meter over the C12.18 protocol. Returns True on success, False on a failure. This can be called by modules in order to login with a username and password configured within the framework instance. """ if not self._serial_connected: raise termineter.errors.FrameworkRuntimeError('the serial interface is disconnected') username = self.options['USERNAME'] user_id = self.options['USER_ID'] password = self.options['PASSWORD'] if self.options['PASSWORD_HEX']: hex_regex = re.compile('^([0-9a-fA-F]{2})+$') if hex_regex.match(password) is None: self.print_error('Invalid characters in password') raise termineter.errors.FrameworkConfigurationError('invalid characters in password') password = binascii.a2b_hex(password) if len(username) > 10: self.print_error('Username cannot be longer than 10 characters') raise termineter.errors.FrameworkConfigurationError('username cannot be longer than 10 characters') if not (0 <= user_id <= 0xffff): self.print_error('User id must be between 0 and 0xffff') raise termineter.errors.FrameworkConfigurationError('user id must be between 0 and 0xffff') if len(password) > 20: self.print_error('Password cannot be longer than 20 characters') raise termineter.errors.FrameworkConfigurationError('password cannot be longer than 20 characters') if not self.serial_connection.login(username, user_id, password): return False return True
python
def serial_login(self): """ Attempt to log into the meter over the C12.18 protocol. Returns True on success, False on a failure. This can be called by modules in order to login with a username and password configured within the framework instance. """ if not self._serial_connected: raise termineter.errors.FrameworkRuntimeError('the serial interface is disconnected') username = self.options['USERNAME'] user_id = self.options['USER_ID'] password = self.options['PASSWORD'] if self.options['PASSWORD_HEX']: hex_regex = re.compile('^([0-9a-fA-F]{2})+$') if hex_regex.match(password) is None: self.print_error('Invalid characters in password') raise termineter.errors.FrameworkConfigurationError('invalid characters in password') password = binascii.a2b_hex(password) if len(username) > 10: self.print_error('Username cannot be longer than 10 characters') raise termineter.errors.FrameworkConfigurationError('username cannot be longer than 10 characters') if not (0 <= user_id <= 0xffff): self.print_error('User id must be between 0 and 0xffff') raise termineter.errors.FrameworkConfigurationError('user id must be between 0 and 0xffff') if len(password) > 20: self.print_error('Password cannot be longer than 20 characters') raise termineter.errors.FrameworkConfigurationError('password cannot be longer than 20 characters') if not self.serial_connection.login(username, user_id, password): return False return True
[ "def", "serial_login", "(", "self", ")", ":", "if", "not", "self", ".", "_serial_connected", ":", "raise", "termineter", ".", "errors", ".", "FrameworkRuntimeError", "(", "'the serial interface is disconnected'", ")", "username", "=", "self", ".", "options", "[", "'USERNAME'", "]", "user_id", "=", "self", ".", "options", "[", "'USER_ID'", "]", "password", "=", "self", ".", "options", "[", "'PASSWORD'", "]", "if", "self", ".", "options", "[", "'PASSWORD_HEX'", "]", ":", "hex_regex", "=", "re", ".", "compile", "(", "'^([0-9a-fA-F]{2})+$'", ")", "if", "hex_regex", ".", "match", "(", "password", ")", "is", "None", ":", "self", ".", "print_error", "(", "'Invalid characters in password'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkConfigurationError", "(", "'invalid characters in password'", ")", "password", "=", "binascii", ".", "a2b_hex", "(", "password", ")", "if", "len", "(", "username", ")", ">", "10", ":", "self", ".", "print_error", "(", "'Username cannot be longer than 10 characters'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkConfigurationError", "(", "'username cannot be longer than 10 characters'", ")", "if", "not", "(", "0", "<=", "user_id", "<=", "0xffff", ")", ":", "self", ".", "print_error", "(", "'User id must be between 0 and 0xffff'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkConfigurationError", "(", "'user id must be between 0 and 0xffff'", ")", "if", "len", "(", "password", ")", ">", "20", ":", "self", ".", "print_error", "(", "'Password cannot be longer than 20 characters'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkConfigurationError", "(", "'password cannot be longer than 20 characters'", ")", "if", "not", "self", ".", "serial_connection", ".", "login", "(", "username", ",", "user_id", ",", "password", ")", ":", "return", "False", "return", "True" ]
Attempt to log into the meter over the C12.18 protocol. Returns True on success, False on a failure. This can be called by modules in order to login with a username and password configured within the framework instance.
[ "Attempt", "to", "log", "into", "the", "meter", "over", "the", "C12", ".", "18", "protocol", ".", "Returns", "True", "on", "success", "False", "on", "a", "failure", ".", "This", "can", "be", "called", "by", "modules", "in", "order", "to", "login", "with", "a", "username", "and", "password", "configured", "within", "the", "framework", "instance", "." ]
d657d25d97c7739e650b951c396404e857e56625
https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L376-L405
227,340
MasoniteFramework/masonite
databases/seeds/user_table_seeder.py
UserTableSeeder.run
def run(self): """ Run the database seeds. """ self.factory.register(User, self.users_factory) self.factory(User, 50).create()
python
def run(self): """ Run the database seeds. """ self.factory.register(User, self.users_factory) self.factory(User, 50).create()
[ "def", "run", "(", "self", ")", ":", "self", ".", "factory", ".", "register", "(", "User", ",", "self", ".", "users_factory", ")", "self", ".", "factory", "(", "User", ",", "50", ")", ".", "create", "(", ")" ]
Run the database seeds.
[ "Run", "the", "database", "seeds", "." ]
c9bcca8f59169934c2accd8cecb2b996bb5e1a0d
https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/databases/seeds/user_table_seeder.py#L18-L24
227,341
MasoniteFramework/masonite
bootstrap/start.py
app
def app(environ, start_response): """The WSGI Application Server. Arguments: environ {dict} -- The WSGI environ dictionary start_response {WSGI callable} Returns: WSGI Response """ from wsgi import container """Add Environ To Service Container Add the environ to the service container. The environ is generated by the the WSGI server above and used by a service provider to manipulate the incoming requests """ container.bind('Environ', environ) """Execute All Service Providers That Require The WSGI Server Run all service provider boot methods if the wsgi attribute is true. """ try: for provider in container.make('WSGIProviders'): container.resolve(provider.boot) except Exception as e: container.make('ExceptionHandler').load_exception(e) """We Are Ready For Launch If we have a solid response and not redirecting then we need to return a 200 status code along with the data. If we don't, then we'll have to return a 302 redirection to where ever the user would like go to next. """ start_response(container.make('Request').get_status_code(), container.make('Request').get_and_reset_headers()) """Final Step This will take the data variable from the Service Container and return it to the WSGI server. """ return iter([bytes(container.make('Response'), 'utf-8')])
python
def app(environ, start_response): """The WSGI Application Server. Arguments: environ {dict} -- The WSGI environ dictionary start_response {WSGI callable} Returns: WSGI Response """ from wsgi import container """Add Environ To Service Container Add the environ to the service container. The environ is generated by the the WSGI server above and used by a service provider to manipulate the incoming requests """ container.bind('Environ', environ) """Execute All Service Providers That Require The WSGI Server Run all service provider boot methods if the wsgi attribute is true. """ try: for provider in container.make('WSGIProviders'): container.resolve(provider.boot) except Exception as e: container.make('ExceptionHandler').load_exception(e) """We Are Ready For Launch If we have a solid response and not redirecting then we need to return a 200 status code along with the data. If we don't, then we'll have to return a 302 redirection to where ever the user would like go to next. """ start_response(container.make('Request').get_status_code(), container.make('Request').get_and_reset_headers()) """Final Step This will take the data variable from the Service Container and return it to the WSGI server. """ return iter([bytes(container.make('Response'), 'utf-8')])
[ "def", "app", "(", "environ", ",", "start_response", ")", ":", "from", "wsgi", "import", "container", "\"\"\"Add Environ To Service Container\n Add the environ to the service container. The environ is generated by the\n the WSGI server above and used by a service provider to manipulate the\n incoming requests\n \"\"\"", "container", ".", "bind", "(", "'Environ'", ",", "environ", ")", "\"\"\"Execute All Service Providers That Require The WSGI Server\n Run all service provider boot methods if the wsgi attribute is true.\n \"\"\"", "try", ":", "for", "provider", "in", "container", ".", "make", "(", "'WSGIProviders'", ")", ":", "container", ".", "resolve", "(", "provider", ".", "boot", ")", "except", "Exception", "as", "e", ":", "container", ".", "make", "(", "'ExceptionHandler'", ")", ".", "load_exception", "(", "e", ")", "\"\"\"We Are Ready For Launch\n If we have a solid response and not redirecting then we need to return\n a 200 status code along with the data. If we don't, then we'll have\n to return a 302 redirection to where ever the user would like go\n to next.\n \"\"\"", "start_response", "(", "container", ".", "make", "(", "'Request'", ")", ".", "get_status_code", "(", ")", ",", "container", ".", "make", "(", "'Request'", ")", ".", "get_and_reset_headers", "(", ")", ")", "\"\"\"Final Step\n This will take the data variable from the Service Container and return\n it to the WSGI server.\n \"\"\"", "return", "iter", "(", "[", "bytes", "(", "container", ".", "make", "(", "'Response'", ")", ",", "'utf-8'", ")", "]", ")" ]
The WSGI Application Server. Arguments: environ {dict} -- The WSGI environ dictionary start_response {WSGI callable} Returns: WSGI Response
[ "The", "WSGI", "Application", "Server", "." ]
c9bcca8f59169934c2accd8cecb2b996bb5e1a0d
https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/bootstrap/start.py#L12-L57
227,342
MasoniteFramework/masonite
databases/migrations/2018_01_09_043202_create_users_table.py
CreateUsersTable.up
def up(self): """Run the migrations.""" with self.schema.create('users') as table: table.increments('id') table.string('name') table.string('email').unique() table.string('password') table.string('remember_token').nullable() table.timestamp('verified_at').nullable() table.timestamps()
python
def up(self): """Run the migrations.""" with self.schema.create('users') as table: table.increments('id') table.string('name') table.string('email').unique() table.string('password') table.string('remember_token').nullable() table.timestamp('verified_at').nullable() table.timestamps()
[ "def", "up", "(", "self", ")", ":", "with", "self", ".", "schema", ".", "create", "(", "'users'", ")", "as", "table", ":", "table", ".", "increments", "(", "'id'", ")", "table", ".", "string", "(", "'name'", ")", "table", ".", "string", "(", "'email'", ")", ".", "unique", "(", ")", "table", ".", "string", "(", "'password'", ")", "table", ".", "string", "(", "'remember_token'", ")", ".", "nullable", "(", ")", "table", ".", "timestamp", "(", "'verified_at'", ")", ".", "nullable", "(", ")", "table", ".", "timestamps", "(", ")" ]
Run the migrations.
[ "Run", "the", "migrations", "." ]
c9bcca8f59169934c2accd8cecb2b996bb5e1a0d
https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/databases/migrations/2018_01_09_043202_create_users_table.py#L6-L15
227,343
MasoniteFramework/masonite
app/http/middleware/VerifyEmailMiddleware.py
VerifyEmailMiddleware.before
def before(self): """Run This Middleware Before The Route Executes.""" user = self.request.user() if user and user.verified_at is None: self.request.redirect('/email/verify')
python
def before(self): """Run This Middleware Before The Route Executes.""" user = self.request.user() if user and user.verified_at is None: self.request.redirect('/email/verify')
[ "def", "before", "(", "self", ")", ":", "user", "=", "self", ".", "request", ".", "user", "(", ")", "if", "user", "and", "user", ".", "verified_at", "is", "None", ":", "self", ".", "request", ".", "redirect", "(", "'/email/verify'", ")" ]
Run This Middleware Before The Route Executes.
[ "Run", "This", "Middleware", "Before", "The", "Route", "Executes", "." ]
c9bcca8f59169934c2accd8cecb2b996bb5e1a0d
https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/app/http/middleware/VerifyEmailMiddleware.py#L17-L22
227,344
MasoniteFramework/masonite
app/http/controllers/WelcomeController.py
WelcomeController.show
def show(self, view: View, request: Request): """Show the welcome page. Arguments: view {masonite.view.View} -- The Masonite view class. Application {config.application} -- The application config module. Returns: masonite.view.View -- The Masonite view class. """ return view.render('welcome', { 'app': request.app().make('Application') })
python
def show(self, view: View, request: Request): """Show the welcome page. Arguments: view {masonite.view.View} -- The Masonite view class. Application {config.application} -- The application config module. Returns: masonite.view.View -- The Masonite view class. """ return view.render('welcome', { 'app': request.app().make('Application') })
[ "def", "show", "(", "self", ",", "view", ":", "View", ",", "request", ":", "Request", ")", ":", "return", "view", ".", "render", "(", "'welcome'", ",", "{", "'app'", ":", "request", ".", "app", "(", ")", ".", "make", "(", "'Application'", ")", "}", ")" ]
Show the welcome page. Arguments: view {masonite.view.View} -- The Masonite view class. Application {config.application} -- The application config module. Returns: masonite.view.View -- The Masonite view class.
[ "Show", "the", "welcome", "page", "." ]
c9bcca8f59169934c2accd8cecb2b996bb5e1a0d
https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/app/http/controllers/WelcomeController.py#L10-L22
227,345
pybluez/pybluez
bluetooth/btcommon.py
is_valid_address
def is_valid_address (s): """ returns True if address is a valid Bluetooth address valid address are always strings of the form XX:XX:XX:XX:XX:XX where X is a hexadecimal character. For example, 01:23:45:67:89:AB is a valid address, but IN:VA:LI:DA:DD:RE is not """ try: pairs = s.split (":") if len (pairs) != 6: return False if not all(0 <= int(b, 16) <= 255 for b in pairs): return False except: return False return True
python
def is_valid_address (s): """ returns True if address is a valid Bluetooth address valid address are always strings of the form XX:XX:XX:XX:XX:XX where X is a hexadecimal character. For example, 01:23:45:67:89:AB is a valid address, but IN:VA:LI:DA:DD:RE is not """ try: pairs = s.split (":") if len (pairs) != 6: return False if not all(0 <= int(b, 16) <= 255 for b in pairs): return False except: return False return True
[ "def", "is_valid_address", "(", "s", ")", ":", "try", ":", "pairs", "=", "s", ".", "split", "(", "\":\"", ")", "if", "len", "(", "pairs", ")", "!=", "6", ":", "return", "False", "if", "not", "all", "(", "0", "<=", "int", "(", "b", ",", "16", ")", "<=", "255", "for", "b", "in", "pairs", ")", ":", "return", "False", "except", ":", "return", "False", "return", "True" ]
returns True if address is a valid Bluetooth address valid address are always strings of the form XX:XX:XX:XX:XX:XX where X is a hexadecimal character. For example, 01:23:45:67:89:AB is a valid address, but IN:VA:LI:DA:DD:RE is not
[ "returns", "True", "if", "address", "is", "a", "valid", "Bluetooth", "address" ]
e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9
https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/bluetooth/btcommon.py#L182-L197
227,346
pybluez/pybluez
bluetooth/btcommon.py
to_full_uuid
def to_full_uuid (uuid): """ converts a short 16-bit or 32-bit reserved UUID to a full 128-bit Bluetooth UUID. """ if not is_valid_uuid (uuid): raise ValueError ("invalid UUID") if len (uuid) == 4: return "0000%s-0000-1000-8000-00805F9B34FB" % uuid elif len (uuid) == 8: return "%s-0000-1000-8000-00805F9B34FB" % uuid else: return uuid
python
def to_full_uuid (uuid): """ converts a short 16-bit or 32-bit reserved UUID to a full 128-bit Bluetooth UUID. """ if not is_valid_uuid (uuid): raise ValueError ("invalid UUID") if len (uuid) == 4: return "0000%s-0000-1000-8000-00805F9B34FB" % uuid elif len (uuid) == 8: return "%s-0000-1000-8000-00805F9B34FB" % uuid else: return uuid
[ "def", "to_full_uuid", "(", "uuid", ")", ":", "if", "not", "is_valid_uuid", "(", "uuid", ")", ":", "raise", "ValueError", "(", "\"invalid UUID\"", ")", "if", "len", "(", "uuid", ")", "==", "4", ":", "return", "\"0000%s-0000-1000-8000-00805F9B34FB\"", "%", "uuid", "elif", "len", "(", "uuid", ")", "==", "8", ":", "return", "\"%s-0000-1000-8000-00805F9B34FB\"", "%", "uuid", "else", ":", "return", "uuid" ]
converts a short 16-bit or 32-bit reserved UUID to a full 128-bit Bluetooth UUID.
[ "converts", "a", "short", "16", "-", "bit", "or", "32", "-", "bit", "reserved", "UUID", "to", "a", "full", "128", "-", "bit", "Bluetooth", "UUID", "." ]
e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9
https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/bluetooth/btcommon.py#L234-L245
227,347
pybluez/pybluez
bluetooth/bluez.py
DeviceDiscoverer.cancel_inquiry
def cancel_inquiry (self): """ Call this method to cancel an inquiry in process. inquiry_complete will still be called. """ self.names_to_find = {} if self.is_inquiring: try: _bt.hci_send_cmd (self.sock, _bt.OGF_LINK_CTL, \ _bt.OCF_INQUIRY_CANCEL) except _bt.error as e: self.sock.close () self.sock = None raise BluetoothError (e.args[0], "error canceling inquiry: " + e.args[1]) self.is_inquiring = False
python
def cancel_inquiry (self): """ Call this method to cancel an inquiry in process. inquiry_complete will still be called. """ self.names_to_find = {} if self.is_inquiring: try: _bt.hci_send_cmd (self.sock, _bt.OGF_LINK_CTL, \ _bt.OCF_INQUIRY_CANCEL) except _bt.error as e: self.sock.close () self.sock = None raise BluetoothError (e.args[0], "error canceling inquiry: " + e.args[1]) self.is_inquiring = False
[ "def", "cancel_inquiry", "(", "self", ")", ":", "self", ".", "names_to_find", "=", "{", "}", "if", "self", ".", "is_inquiring", ":", "try", ":", "_bt", ".", "hci_send_cmd", "(", "self", ".", "sock", ",", "_bt", ".", "OGF_LINK_CTL", ",", "_bt", ".", "OCF_INQUIRY_CANCEL", ")", "except", "_bt", ".", "error", "as", "e", ":", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "sock", "=", "None", "raise", "BluetoothError", "(", "e", ".", "args", "[", "0", "]", ",", "\"error canceling inquiry: \"", "+", "e", ".", "args", "[", "1", "]", ")", "self", ".", "is_inquiring", "=", "False" ]
Call this method to cancel an inquiry in process. inquiry_complete will still be called.
[ "Call", "this", "method", "to", "cancel", "an", "inquiry", "in", "process", ".", "inquiry_complete", "will", "still", "be", "called", "." ]
e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9
https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/bluetooth/bluez.py#L451-L468
227,348
pybluez/pybluez
bluetooth/bluez.py
DeviceDiscoverer.device_discovered
def device_discovered (self, address, device_class, rssi, name): """ Called when a bluetooth device is discovered. address is the bluetooth address of the device device_class is the Class of Device, as specified in [1] passed in as a 3-byte string name is the user-friendly name of the device if lookup_names was set when the inquiry was started. otherwise None This method exists to be overriden. [1] https://www.bluetooth.org/foundry/assignnumb/document/baseband """ if name: print(("found: %s - %s (class 0x%X, rssi %s)" % \ (address, name, device_class, rssi))) else: print(("found: %s (class 0x%X)" % (address, device_class))) print(("found: %s (class 0x%X, rssi %s)" % \ (address, device_class, rssi)))
python
def device_discovered (self, address, device_class, rssi, name): """ Called when a bluetooth device is discovered. address is the bluetooth address of the device device_class is the Class of Device, as specified in [1] passed in as a 3-byte string name is the user-friendly name of the device if lookup_names was set when the inquiry was started. otherwise None This method exists to be overriden. [1] https://www.bluetooth.org/foundry/assignnumb/document/baseband """ if name: print(("found: %s - %s (class 0x%X, rssi %s)" % \ (address, name, device_class, rssi))) else: print(("found: %s (class 0x%X)" % (address, device_class))) print(("found: %s (class 0x%X, rssi %s)" % \ (address, device_class, rssi)))
[ "def", "device_discovered", "(", "self", ",", "address", ",", "device_class", ",", "rssi", ",", "name", ")", ":", "if", "name", ":", "print", "(", "(", "\"found: %s - %s (class 0x%X, rssi %s)\"", "%", "(", "address", ",", "name", ",", "device_class", ",", "rssi", ")", ")", ")", "else", ":", "print", "(", "(", "\"found: %s (class 0x%X)\"", "%", "(", "address", ",", "device_class", ")", ")", ")", "print", "(", "(", "\"found: %s (class 0x%X, rssi %s)\"", "%", "(", "address", ",", "device_class", ",", "rssi", ")", ")", ")" ]
Called when a bluetooth device is discovered. address is the bluetooth address of the device device_class is the Class of Device, as specified in [1] passed in as a 3-byte string name is the user-friendly name of the device if lookup_names was set when the inquiry was started. otherwise None This method exists to be overriden. [1] https://www.bluetooth.org/foundry/assignnumb/document/baseband
[ "Called", "when", "a", "bluetooth", "device", "is", "discovered", "." ]
e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9
https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/bluetooth/bluez.py#L646-L668
227,349
pybluez/pybluez
examples/advanced/write-inquiry-scan.py
read_inquiry_scan_activity
def read_inquiry_scan_activity(sock): """returns the current inquiry scan interval and window, or -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # read_inquiry_mode command flt = bluez.hci_filter_new() opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, bluez.OCF_READ_INQ_ACTIVITY) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE); bluez.hci_filter_set_opcode(flt, opcode) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) # first read the current inquiry mode. bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_READ_INQ_ACTIVITY ) pkt = sock.recv(255) status,interval,window = struct.unpack("!xxxxxxBHH", pkt) interval = bluez.btohs(interval) interval = (interval >> 8) | ( (interval & 0xFF) << 8 ) window = (window >> 8) | ( (window & 0xFF) << 8 ) if status != 0: mode = -1 # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) return interval, window
python
def read_inquiry_scan_activity(sock): """returns the current inquiry scan interval and window, or -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # read_inquiry_mode command flt = bluez.hci_filter_new() opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, bluez.OCF_READ_INQ_ACTIVITY) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE); bluez.hci_filter_set_opcode(flt, opcode) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) # first read the current inquiry mode. bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_READ_INQ_ACTIVITY ) pkt = sock.recv(255) status,interval,window = struct.unpack("!xxxxxxBHH", pkt) interval = bluez.btohs(interval) interval = (interval >> 8) | ( (interval & 0xFF) << 8 ) window = (window >> 8) | ( (window & 0xFF) << 8 ) if status != 0: mode = -1 # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) return interval, window
[ "def", "read_inquiry_scan_activity", "(", "sock", ")", ":", "# save current filter", "old_filter", "=", "sock", ".", "getsockopt", "(", "bluez", ".", "SOL_HCI", ",", "bluez", ".", "HCI_FILTER", ",", "14", ")", "# Setup socket filter to receive only events related to the", "# read_inquiry_mode command", "flt", "=", "bluez", ".", "hci_filter_new", "(", ")", "opcode", "=", "bluez", ".", "cmd_opcode_pack", "(", "bluez", ".", "OGF_HOST_CTL", ",", "bluez", ".", "OCF_READ_INQ_ACTIVITY", ")", "bluez", ".", "hci_filter_set_ptype", "(", "flt", ",", "bluez", ".", "HCI_EVENT_PKT", ")", "bluez", ".", "hci_filter_set_event", "(", "flt", ",", "bluez", ".", "EVT_CMD_COMPLETE", ")", "bluez", ".", "hci_filter_set_opcode", "(", "flt", ",", "opcode", ")", "sock", ".", "setsockopt", "(", "bluez", ".", "SOL_HCI", ",", "bluez", ".", "HCI_FILTER", ",", "flt", ")", "# first read the current inquiry mode.", "bluez", ".", "hci_send_cmd", "(", "sock", ",", "bluez", ".", "OGF_HOST_CTL", ",", "bluez", ".", "OCF_READ_INQ_ACTIVITY", ")", "pkt", "=", "sock", ".", "recv", "(", "255", ")", "status", ",", "interval", ",", "window", "=", "struct", ".", "unpack", "(", "\"!xxxxxxBHH\"", ",", "pkt", ")", "interval", "=", "bluez", ".", "btohs", "(", "interval", ")", "interval", "=", "(", "interval", ">>", "8", ")", "|", "(", "(", "interval", "&", "0xFF", ")", "<<", "8", ")", "window", "=", "(", "window", ">>", "8", ")", "|", "(", "(", "window", "&", "0xFF", ")", "<<", "8", ")", "if", "status", "!=", "0", ":", "mode", "=", "-", "1", "# restore old filter", "sock", ".", "setsockopt", "(", "bluez", ".", "SOL_HCI", ",", "bluez", ".", "HCI_FILTER", ",", "old_filter", ")", "return", "interval", ",", "window" ]
returns the current inquiry scan interval and window, or -1 on failure
[ "returns", "the", "current", "inquiry", "scan", "interval", "and", "window", "or", "-", "1", "on", "failure" ]
e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9
https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/examples/advanced/write-inquiry-scan.py#L6-L36
227,350
pybluez/pybluez
examples/advanced/write-inquiry-scan.py
write_inquiry_scan_activity
def write_inquiry_scan_activity(sock, interval, window): """returns 0 on success, -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # write_inquiry_mode command flt = bluez.hci_filter_new() opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, bluez.OCF_WRITE_INQ_ACTIVITY) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE); bluez.hci_filter_set_opcode(flt, opcode) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) # send the command! bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_WRITE_INQ_ACTIVITY, struct.pack("HH", interval, window) ) pkt = sock.recv(255) status = struct.unpack("xxxxxxB", pkt)[0] # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) if status != 0: return -1 return 0
python
def write_inquiry_scan_activity(sock, interval, window): """returns 0 on success, -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # write_inquiry_mode command flt = bluez.hci_filter_new() opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, bluez.OCF_WRITE_INQ_ACTIVITY) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE); bluez.hci_filter_set_opcode(flt, opcode) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) # send the command! bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_WRITE_INQ_ACTIVITY, struct.pack("HH", interval, window) ) pkt = sock.recv(255) status = struct.unpack("xxxxxxB", pkt)[0] # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) if status != 0: return -1 return 0
[ "def", "write_inquiry_scan_activity", "(", "sock", ",", "interval", ",", "window", ")", ":", "# save current filter", "old_filter", "=", "sock", ".", "getsockopt", "(", "bluez", ".", "SOL_HCI", ",", "bluez", ".", "HCI_FILTER", ",", "14", ")", "# Setup socket filter to receive only events related to the", "# write_inquiry_mode command", "flt", "=", "bluez", ".", "hci_filter_new", "(", ")", "opcode", "=", "bluez", ".", "cmd_opcode_pack", "(", "bluez", ".", "OGF_HOST_CTL", ",", "bluez", ".", "OCF_WRITE_INQ_ACTIVITY", ")", "bluez", ".", "hci_filter_set_ptype", "(", "flt", ",", "bluez", ".", "HCI_EVENT_PKT", ")", "bluez", ".", "hci_filter_set_event", "(", "flt", ",", "bluez", ".", "EVT_CMD_COMPLETE", ")", "bluez", ".", "hci_filter_set_opcode", "(", "flt", ",", "opcode", ")", "sock", ".", "setsockopt", "(", "bluez", ".", "SOL_HCI", ",", "bluez", ".", "HCI_FILTER", ",", "flt", ")", "# send the command!", "bluez", ".", "hci_send_cmd", "(", "sock", ",", "bluez", ".", "OGF_HOST_CTL", ",", "bluez", ".", "OCF_WRITE_INQ_ACTIVITY", ",", "struct", ".", "pack", "(", "\"HH\"", ",", "interval", ",", "window", ")", ")", "pkt", "=", "sock", ".", "recv", "(", "255", ")", "status", "=", "struct", ".", "unpack", "(", "\"xxxxxxB\"", ",", "pkt", ")", "[", "0", "]", "# restore old filter", "sock", ".", "setsockopt", "(", "bluez", ".", "SOL_HCI", ",", "bluez", ".", "HCI_FILTER", ",", "old_filter", ")", "if", "status", "!=", "0", ":", "return", "-", "1", "return", "0" ]
returns 0 on success, -1 on failure
[ "returns", "0", "on", "success", "-", "1", "on", "failure" ]
e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9
https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/examples/advanced/write-inquiry-scan.py#L38-L65
227,351
pybluez/pybluez
examples/advanced/inquiry-with-rssi.py
read_inquiry_mode
def read_inquiry_mode(sock): """returns the current mode, or -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # read_inquiry_mode command flt = bluez.hci_filter_new() opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, bluez.OCF_READ_INQUIRY_MODE) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE); bluez.hci_filter_set_opcode(flt, opcode) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) # first read the current inquiry mode. bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_READ_INQUIRY_MODE ) pkt = sock.recv(255) status,mode = struct.unpack("xxxxxxBB", pkt) if status != 0: mode = -1 # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) return mode
python
def read_inquiry_mode(sock): """returns the current mode, or -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # read_inquiry_mode command flt = bluez.hci_filter_new() opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, bluez.OCF_READ_INQUIRY_MODE) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE); bluez.hci_filter_set_opcode(flt, opcode) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) # first read the current inquiry mode. bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_READ_INQUIRY_MODE ) pkt = sock.recv(255) status,mode = struct.unpack("xxxxxxBB", pkt) if status != 0: mode = -1 # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) return mode
[ "def", "read_inquiry_mode", "(", "sock", ")", ":", "# save current filter", "old_filter", "=", "sock", ".", "getsockopt", "(", "bluez", ".", "SOL_HCI", ",", "bluez", ".", "HCI_FILTER", ",", "14", ")", "# Setup socket filter to receive only events related to the", "# read_inquiry_mode command", "flt", "=", "bluez", ".", "hci_filter_new", "(", ")", "opcode", "=", "bluez", ".", "cmd_opcode_pack", "(", "bluez", ".", "OGF_HOST_CTL", ",", "bluez", ".", "OCF_READ_INQUIRY_MODE", ")", "bluez", ".", "hci_filter_set_ptype", "(", "flt", ",", "bluez", ".", "HCI_EVENT_PKT", ")", "bluez", ".", "hci_filter_set_event", "(", "flt", ",", "bluez", ".", "EVT_CMD_COMPLETE", ")", "bluez", ".", "hci_filter_set_opcode", "(", "flt", ",", "opcode", ")", "sock", ".", "setsockopt", "(", "bluez", ".", "SOL_HCI", ",", "bluez", ".", "HCI_FILTER", ",", "flt", ")", "# first read the current inquiry mode.", "bluez", ".", "hci_send_cmd", "(", "sock", ",", "bluez", ".", "OGF_HOST_CTL", ",", "bluez", ".", "OCF_READ_INQUIRY_MODE", ")", "pkt", "=", "sock", ".", "recv", "(", "255", ")", "status", ",", "mode", "=", "struct", ".", "unpack", "(", "\"xxxxxxBB\"", ",", "pkt", ")", "if", "status", "!=", "0", ":", "mode", "=", "-", "1", "# restore old filter", "sock", ".", "setsockopt", "(", "bluez", ".", "SOL_HCI", ",", "bluez", ".", "HCI_FILTER", ",", "old_filter", ")", "return", "mode" ]
returns the current mode, or -1 on failure
[ "returns", "the", "current", "mode", "or", "-", "1", "on", "failure" ]
e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9
https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/examples/advanced/inquiry-with-rssi.py#L16-L42
227,352
pybluez/pybluez
macos/_lightbluecommon.py
splitclass
def splitclass(classofdevice): """ Splits the given class of device to return a 3-item tuple with the major service class, major device class and minor device class values. These values indicate the device's major services and the type of the device (e.g. mobile phone, laptop, etc.). If you google for "assigned numbers bluetooth baseband" you might find some documents that discuss how to extract this information from the class of device. Example: >>> splitclass(1057036) (129, 1, 3) >>> """ if not isinstance(classofdevice, int): try: classofdevice = int(classofdevice) except (TypeError, ValueError): raise TypeError("Given device class '%s' cannot be split" % \ str(classofdevice)) data = classofdevice >> 2 # skip over the 2 "format" bits service = data >> 11 major = (data >> 6) & 0x1F minor = data & 0x3F return (service, major, minor)
python
def splitclass(classofdevice): """ Splits the given class of device to return a 3-item tuple with the major service class, major device class and minor device class values. These values indicate the device's major services and the type of the device (e.g. mobile phone, laptop, etc.). If you google for "assigned numbers bluetooth baseband" you might find some documents that discuss how to extract this information from the class of device. Example: >>> splitclass(1057036) (129, 1, 3) >>> """ if not isinstance(classofdevice, int): try: classofdevice = int(classofdevice) except (TypeError, ValueError): raise TypeError("Given device class '%s' cannot be split" % \ str(classofdevice)) data = classofdevice >> 2 # skip over the 2 "format" bits service = data >> 11 major = (data >> 6) & 0x1F minor = data & 0x3F return (service, major, minor)
[ "def", "splitclass", "(", "classofdevice", ")", ":", "if", "not", "isinstance", "(", "classofdevice", ",", "int", ")", ":", "try", ":", "classofdevice", "=", "int", "(", "classofdevice", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "TypeError", "(", "\"Given device class '%s' cannot be split\"", "%", "str", "(", "classofdevice", ")", ")", "data", "=", "classofdevice", ">>", "2", "# skip over the 2 \"format\" bits", "service", "=", "data", ">>", "11", "major", "=", "(", "data", ">>", "6", ")", "&", "0x1F", "minor", "=", "data", "&", "0x3F", "return", "(", "service", ",", "major", ",", "minor", ")" ]
Splits the given class of device to return a 3-item tuple with the major service class, major device class and minor device class values. These values indicate the device's major services and the type of the device (e.g. mobile phone, laptop, etc.). If you google for "assigned numbers bluetooth baseband" you might find some documents that discuss how to extract this information from the class of device. Example: >>> splitclass(1057036) (129, 1, 3) >>>
[ "Splits", "the", "given", "class", "of", "device", "to", "return", "a", "3", "-", "item", "tuple", "with", "the", "major", "service", "class", "major", "device", "class", "and", "minor", "device", "class", "values", "." ]
e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9
https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/macos/_lightbluecommon.py#L43-L69
227,353
pybluez/pybluez
macos/_lightblue.py
_searchservices
def _searchservices(device, name=None, uuid=None, uuidbad=None): """ Searches the given IOBluetoothDevice using the specified parameters. Returns an empty list if the device has no services. uuid should be IOBluetoothSDPUUID object. """ if not isinstance(device, _IOBluetooth.IOBluetoothDevice): raise ValueError("device must be IOBluetoothDevice, was %s" % \ type(device)) services = [] allservices = device.getServices() if uuid: gooduuids = (uuid, ) else: gooduuids = () if uuidbad: baduuids = (uuidbad, ) else: baduuids = () if allservices is not None: for s in allservices: if gooduuids and not s.hasServiceFromArray_(gooduuids): continue if baduuids and s.hasServiceFromArray_(baduuids): continue if name is None or s.getServiceName() == name: services.append(s) return services
python
def _searchservices(device, name=None, uuid=None, uuidbad=None): """ Searches the given IOBluetoothDevice using the specified parameters. Returns an empty list if the device has no services. uuid should be IOBluetoothSDPUUID object. """ if not isinstance(device, _IOBluetooth.IOBluetoothDevice): raise ValueError("device must be IOBluetoothDevice, was %s" % \ type(device)) services = [] allservices = device.getServices() if uuid: gooduuids = (uuid, ) else: gooduuids = () if uuidbad: baduuids = (uuidbad, ) else: baduuids = () if allservices is not None: for s in allservices: if gooduuids and not s.hasServiceFromArray_(gooduuids): continue if baduuids and s.hasServiceFromArray_(baduuids): continue if name is None or s.getServiceName() == name: services.append(s) return services
[ "def", "_searchservices", "(", "device", ",", "name", "=", "None", ",", "uuid", "=", "None", ",", "uuidbad", "=", "None", ")", ":", "if", "not", "isinstance", "(", "device", ",", "_IOBluetooth", ".", "IOBluetoothDevice", ")", ":", "raise", "ValueError", "(", "\"device must be IOBluetoothDevice, was %s\"", "%", "type", "(", "device", ")", ")", "services", "=", "[", "]", "allservices", "=", "device", ".", "getServices", "(", ")", "if", "uuid", ":", "gooduuids", "=", "(", "uuid", ",", ")", "else", ":", "gooduuids", "=", "(", ")", "if", "uuidbad", ":", "baduuids", "=", "(", "uuidbad", ",", ")", "else", ":", "baduuids", "=", "(", ")", "if", "allservices", "is", "not", "None", ":", "for", "s", "in", "allservices", ":", "if", "gooduuids", "and", "not", "s", ".", "hasServiceFromArray_", "(", "gooduuids", ")", ":", "continue", "if", "baduuids", "and", "s", ".", "hasServiceFromArray_", "(", "baduuids", ")", ":", "continue", "if", "name", "is", "None", "or", "s", ".", "getServiceName", "(", ")", "==", "name", ":", "services", ".", "append", "(", "s", ")", "return", "services" ]
Searches the given IOBluetoothDevice using the specified parameters. Returns an empty list if the device has no services. uuid should be IOBluetoothSDPUUID object.
[ "Searches", "the", "given", "IOBluetoothDevice", "using", "the", "specified", "parameters", ".", "Returns", "an", "empty", "list", "if", "the", "device", "has", "no", "services", "." ]
e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9
https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/macos/_lightblue.py#L485-L515
227,354
bambinos/bambi
bambi/backends/pymc.py
PyMC3BackEnd.reset
def reset(self): ''' Reset PyMC3 model and all tracked distributions and parameters. ''' self.model = pm.Model() self.mu = None self.par_groups = {}
python
def reset(self): ''' Reset PyMC3 model and all tracked distributions and parameters. ''' self.model = pm.Model() self.mu = None self.par_groups = {}
[ "def", "reset", "(", "self", ")", ":", "self", ".", "model", "=", "pm", ".", "Model", "(", ")", "self", ".", "mu", "=", "None", "self", ".", "par_groups", "=", "{", "}" ]
Reset PyMC3 model and all tracked distributions and parameters.
[ "Reset", "PyMC3", "model", "and", "all", "tracked", "distributions", "and", "parameters", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/backends/pymc.py#L37-L43
227,355
bambinos/bambi
bambi/backends/pymc.py
PyMC3BackEnd._build_dist
def _build_dist(self, spec, label, dist, **kwargs): ''' Build and return a PyMC3 Distribution. ''' if isinstance(dist, string_types): if hasattr(pm, dist): dist = getattr(pm, dist) elif dist in self.dists: dist = self.dists[dist] else: raise ValueError("The Distribution class '%s' was not " "found in PyMC3 or the PyMC3BackEnd." % dist) # Inspect all args in case we have hyperparameters def _expand_args(k, v, label): if isinstance(v, Prior): label = '%s_%s' % (label, k) return self._build_dist(spec, label, v.name, **v.args) return v kwargs = {k: _expand_args(k, v, label) for (k, v) in kwargs.items()} # Non-centered parameterization for hyperpriors if spec.noncentered and 'sd' in kwargs and 'observed' not in kwargs \ and isinstance(kwargs['sd'], pm.model.TransformedRV): old_sd = kwargs['sd'] _offset = pm.Normal(label + '_offset', mu=0, sd=1, shape=kwargs['shape']) return pm.Deterministic(label, _offset * old_sd) return dist(label, **kwargs)
python
def _build_dist(self, spec, label, dist, **kwargs): ''' Build and return a PyMC3 Distribution. ''' if isinstance(dist, string_types): if hasattr(pm, dist): dist = getattr(pm, dist) elif dist in self.dists: dist = self.dists[dist] else: raise ValueError("The Distribution class '%s' was not " "found in PyMC3 or the PyMC3BackEnd." % dist) # Inspect all args in case we have hyperparameters def _expand_args(k, v, label): if isinstance(v, Prior): label = '%s_%s' % (label, k) return self._build_dist(spec, label, v.name, **v.args) return v kwargs = {k: _expand_args(k, v, label) for (k, v) in kwargs.items()} # Non-centered parameterization for hyperpriors if spec.noncentered and 'sd' in kwargs and 'observed' not in kwargs \ and isinstance(kwargs['sd'], pm.model.TransformedRV): old_sd = kwargs['sd'] _offset = pm.Normal(label + '_offset', mu=0, sd=1, shape=kwargs['shape']) return pm.Deterministic(label, _offset * old_sd) return dist(label, **kwargs)
[ "def", "_build_dist", "(", "self", ",", "spec", ",", "label", ",", "dist", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "dist", ",", "string_types", ")", ":", "if", "hasattr", "(", "pm", ",", "dist", ")", ":", "dist", "=", "getattr", "(", "pm", ",", "dist", ")", "elif", "dist", "in", "self", ".", "dists", ":", "dist", "=", "self", ".", "dists", "[", "dist", "]", "else", ":", "raise", "ValueError", "(", "\"The Distribution class '%s' was not \"", "\"found in PyMC3 or the PyMC3BackEnd.\"", "%", "dist", ")", "# Inspect all args in case we have hyperparameters", "def", "_expand_args", "(", "k", ",", "v", ",", "label", ")", ":", "if", "isinstance", "(", "v", ",", "Prior", ")", ":", "label", "=", "'%s_%s'", "%", "(", "label", ",", "k", ")", "return", "self", ".", "_build_dist", "(", "spec", ",", "label", ",", "v", ".", "name", ",", "*", "*", "v", ".", "args", ")", "return", "v", "kwargs", "=", "{", "k", ":", "_expand_args", "(", "k", ",", "v", ",", "label", ")", "for", "(", "k", ",", "v", ")", "in", "kwargs", ".", "items", "(", ")", "}", "# Non-centered parameterization for hyperpriors", "if", "spec", ".", "noncentered", "and", "'sd'", "in", "kwargs", "and", "'observed'", "not", "in", "kwargs", "and", "isinstance", "(", "kwargs", "[", "'sd'", "]", ",", "pm", ".", "model", ".", "TransformedRV", ")", ":", "old_sd", "=", "kwargs", "[", "'sd'", "]", "_offset", "=", "pm", ".", "Normal", "(", "label", "+", "'_offset'", ",", "mu", "=", "0", ",", "sd", "=", "1", ",", "shape", "=", "kwargs", "[", "'shape'", "]", ")", "return", "pm", ".", "Deterministic", "(", "label", ",", "_offset", "*", "old_sd", ")", "return", "dist", "(", "label", ",", "*", "*", "kwargs", ")" ]
Build and return a PyMC3 Distribution.
[ "Build", "and", "return", "a", "PyMC3", "Distribution", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/backends/pymc.py#L45-L73
227,356
bambinos/bambi
bambi/results.py
MCMCResults.to_df
def to_df(self, varnames=None, ranefs=False, transformed=False, chains=None): ''' Returns the MCMC samples in a nice, neat pandas DataFrame with all MCMC chains concatenated. Args: varnames (list): List of variable names to include; if None (default), all eligible variables are included. ranefs (bool): Whether or not to include random effects in the returned DataFrame. Default is True. transformed (bool): Whether or not to include internally transformed variables in the result. Default is False. chains (int, list): Index, or list of indexes, of chains to concatenate. E.g., [1, 3] would concatenate the first and third chains, and ignore any others. If None (default), concatenates all available chains. ''' # filter out unwanted variables names = self._filter_names(varnames, ranefs, transformed) # concatenate the (pre-sliced) chains if chains is None: chains = list(range(self.n_chains)) chains = listify(chains) data = [self.data[:, i, :] for i in chains] data = np.concatenate(data, axis=0) # construct the trace DataFrame df = sum([self.level_dict[x] for x in names], []) df = pd.DataFrame({x: data[:, self.levels.index(x)] for x in df}) return df
python
def to_df(self, varnames=None, ranefs=False, transformed=False, chains=None): ''' Returns the MCMC samples in a nice, neat pandas DataFrame with all MCMC chains concatenated. Args: varnames (list): List of variable names to include; if None (default), all eligible variables are included. ranefs (bool): Whether or not to include random effects in the returned DataFrame. Default is True. transformed (bool): Whether or not to include internally transformed variables in the result. Default is False. chains (int, list): Index, or list of indexes, of chains to concatenate. E.g., [1, 3] would concatenate the first and third chains, and ignore any others. If None (default), concatenates all available chains. ''' # filter out unwanted variables names = self._filter_names(varnames, ranefs, transformed) # concatenate the (pre-sliced) chains if chains is None: chains = list(range(self.n_chains)) chains = listify(chains) data = [self.data[:, i, :] for i in chains] data = np.concatenate(data, axis=0) # construct the trace DataFrame df = sum([self.level_dict[x] for x in names], []) df = pd.DataFrame({x: data[:, self.levels.index(x)] for x in df}) return df
[ "def", "to_df", "(", "self", ",", "varnames", "=", "None", ",", "ranefs", "=", "False", ",", "transformed", "=", "False", ",", "chains", "=", "None", ")", ":", "# filter out unwanted variables", "names", "=", "self", ".", "_filter_names", "(", "varnames", ",", "ranefs", ",", "transformed", ")", "# concatenate the (pre-sliced) chains", "if", "chains", "is", "None", ":", "chains", "=", "list", "(", "range", "(", "self", ".", "n_chains", ")", ")", "chains", "=", "listify", "(", "chains", ")", "data", "=", "[", "self", ".", "data", "[", ":", ",", "i", ",", ":", "]", "for", "i", "in", "chains", "]", "data", "=", "np", ".", "concatenate", "(", "data", ",", "axis", "=", "0", ")", "# construct the trace DataFrame", "df", "=", "sum", "(", "[", "self", ".", "level_dict", "[", "x", "]", "for", "x", "in", "names", "]", ",", "[", "]", ")", "df", "=", "pd", ".", "DataFrame", "(", "{", "x", ":", "data", "[", ":", ",", "self", ".", "levels", ".", "index", "(", "x", ")", "]", "for", "x", "in", "df", "}", ")", "return", "df" ]
Returns the MCMC samples in a nice, neat pandas DataFrame with all MCMC chains concatenated. Args: varnames (list): List of variable names to include; if None (default), all eligible variables are included. ranefs (bool): Whether or not to include random effects in the returned DataFrame. Default is True. transformed (bool): Whether or not to include internally transformed variables in the result. Default is False. chains (int, list): Index, or list of indexes, of chains to concatenate. E.g., [1, 3] would concatenate the first and third chains, and ignore any others. If None (default), concatenates all available chains.
[ "Returns", "the", "MCMC", "samples", "in", "a", "nice", "neat", "pandas", "DataFrame", "with", "all", "MCMC", "chains", "concatenated", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/results.py#L369-L402
227,357
bambinos/bambi
bambi/diagnostics.py
autocov
def autocov(x): """Compute autocovariance estimates for every lag for the input array. Args: x (array-like): An array containing MCMC samples. Returns: np.ndarray: An array of the same size as the input array. """ acorr = autocorr(x) varx = np.var(x, ddof=1) * (len(x) - 1) / len(x) acov = acorr * varx return acov
python
def autocov(x): """Compute autocovariance estimates for every lag for the input array. Args: x (array-like): An array containing MCMC samples. Returns: np.ndarray: An array of the same size as the input array. """ acorr = autocorr(x) varx = np.var(x, ddof=1) * (len(x) - 1) / len(x) acov = acorr * varx return acov
[ "def", "autocov", "(", "x", ")", ":", "acorr", "=", "autocorr", "(", "x", ")", "varx", "=", "np", ".", "var", "(", "x", ",", "ddof", "=", "1", ")", "*", "(", "len", "(", "x", ")", "-", "1", ")", "/", "len", "(", "x", ")", "acov", "=", "acorr", "*", "varx", "return", "acov" ]
Compute autocovariance estimates for every lag for the input array. Args: x (array-like): An array containing MCMC samples. Returns: np.ndarray: An array of the same size as the input array.
[ "Compute", "autocovariance", "estimates", "for", "every", "lag", "for", "the", "input", "array", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/diagnostics.py#L30-L43
227,358
bambinos/bambi
bambi/models.py
Model.reset
def reset(self): ''' Reset list of terms and y-variable. ''' self.terms = OrderedDict() self.y = None self.backend = None self.added_terms = [] self._added_priors = {} self.completes = [] self.clean_data = None
python
def reset(self): ''' Reset list of terms and y-variable. ''' self.terms = OrderedDict() self.y = None self.backend = None self.added_terms = [] self._added_priors = {} self.completes = [] self.clean_data = None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "terms", "=", "OrderedDict", "(", ")", "self", ".", "y", "=", "None", "self", ".", "backend", "=", "None", "self", ".", "added_terms", "=", "[", "]", "self", ".", "_added_priors", "=", "{", "}", "self", ".", "completes", "=", "[", "]", "self", ".", "clean_data", "=", "None" ]
Reset list of terms and y-variable.
[ "Reset", "list", "of", "terms", "and", "y", "-", "variable", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L83-L93
227,359
bambinos/bambi
bambi/models.py
Model.fit
def fit(self, fixed=None, random=None, priors=None, family='gaussian', link=None, run=True, categorical=None, backend=None, **kwargs): '''Fit the model using the specified BackEnd. Args: fixed (str): Optional formula specification of fixed effects. random (list): Optional list-based specification of random effects. priors (dict): Optional specification of priors for one or more terms. A dict where the keys are the names of terms in the model, and the values are either instances of class Prior or ints, floats, or strings that specify the width of the priors on a standardized scale. family (str, Family): A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are 'gaussian', 'bernoulli', 'poisson', and 't'. link (str): The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least 'identity', 'logit', 'inverse', and 'log'), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape. run (bool): Whether or not to immediately begin fitting the model once any set up of passed arguments is complete. categorical (str, list): The names of any variables to treat as categorical. Can be either a single variable name, or a list of names. If categorical is None, the data type of the columns in the DataFrame will be used to infer handling. In cases where numeric columns are to be treated as categoricals (e.g., random factors coded as numerical IDs), explicitly passing variable names via this argument is recommended. backend (str): The name of the BackEnd to use. Currently only 'pymc' and 'stan' backends are supported. Defaults to PyMC3. ''' if fixed is not None or random is not None: self.add(fixed=fixed, random=random, priors=priors, family=family, link=link, categorical=categorical, append=False) ''' Run the BackEnd to fit the model. ''' if backend is None: backend = 'pymc' if self._backend_name is None else self._backend_name if run: if not self.built or backend != self._backend_name: self.build(backend) return self.backend.run(**kwargs) self._backend_name = backend
python
def fit(self, fixed=None, random=None, priors=None, family='gaussian', link=None, run=True, categorical=None, backend=None, **kwargs): '''Fit the model using the specified BackEnd. Args: fixed (str): Optional formula specification of fixed effects. random (list): Optional list-based specification of random effects. priors (dict): Optional specification of priors for one or more terms. A dict where the keys are the names of terms in the model, and the values are either instances of class Prior or ints, floats, or strings that specify the width of the priors on a standardized scale. family (str, Family): A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are 'gaussian', 'bernoulli', 'poisson', and 't'. link (str): The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least 'identity', 'logit', 'inverse', and 'log'), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape. run (bool): Whether or not to immediately begin fitting the model once any set up of passed arguments is complete. categorical (str, list): The names of any variables to treat as categorical. Can be either a single variable name, or a list of names. If categorical is None, the data type of the columns in the DataFrame will be used to infer handling. In cases where numeric columns are to be treated as categoricals (e.g., random factors coded as numerical IDs), explicitly passing variable names via this argument is recommended. backend (str): The name of the BackEnd to use. Currently only 'pymc' and 'stan' backends are supported. Defaults to PyMC3. ''' if fixed is not None or random is not None: self.add(fixed=fixed, random=random, priors=priors, family=family, link=link, categorical=categorical, append=False) ''' Run the BackEnd to fit the model. ''' if backend is None: backend = 'pymc' if self._backend_name is None else self._backend_name if run: if not self.built or backend != self._backend_name: self.build(backend) return self.backend.run(**kwargs) self._backend_name = backend
[ "def", "fit", "(", "self", ",", "fixed", "=", "None", ",", "random", "=", "None", ",", "priors", "=", "None", ",", "family", "=", "'gaussian'", ",", "link", "=", "None", ",", "run", "=", "True", ",", "categorical", "=", "None", ",", "backend", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "fixed", "is", "not", "None", "or", "random", "is", "not", "None", ":", "self", ".", "add", "(", "fixed", "=", "fixed", ",", "random", "=", "random", ",", "priors", "=", "priors", ",", "family", "=", "family", ",", "link", "=", "link", ",", "categorical", "=", "categorical", ",", "append", "=", "False", ")", "''' Run the BackEnd to fit the model. '''", "if", "backend", "is", "None", ":", "backend", "=", "'pymc'", "if", "self", ".", "_backend_name", "is", "None", "else", "self", ".", "_backend_name", "if", "run", ":", "if", "not", "self", ".", "built", "or", "backend", "!=", "self", ".", "_backend_name", ":", "self", ".", "build", "(", "backend", ")", "return", "self", ".", "backend", ".", "run", "(", "*", "*", "kwargs", ")", "self", ".", "_backend_name", "=", "backend" ]
Fit the model using the specified BackEnd. Args: fixed (str): Optional formula specification of fixed effects. random (list): Optional list-based specification of random effects. priors (dict): Optional specification of priors for one or more terms. A dict where the keys are the names of terms in the model, and the values are either instances of class Prior or ints, floats, or strings that specify the width of the priors on a standardized scale. family (str, Family): A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are 'gaussian', 'bernoulli', 'poisson', and 't'. link (str): The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least 'identity', 'logit', 'inverse', and 'log'), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape. run (bool): Whether or not to immediately begin fitting the model once any set up of passed arguments is complete. categorical (str, list): The names of any variables to treat as categorical. Can be either a single variable name, or a list of names. If categorical is None, the data type of the columns in the DataFrame will be used to infer handling. In cases where numeric columns are to be treated as categoricals (e.g., random factors coded as numerical IDs), explicitly passing variable names via this argument is recommended. backend (str): The name of the BackEnd to use. Currently only 'pymc' and 'stan' backends are supported. Defaults to PyMC3.
[ "Fit", "the", "model", "using", "the", "specified", "BackEnd", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L236-L286
227,360
bambinos/bambi
bambi/models.py
Model.add
def add(self, fixed=None, random=None, priors=None, family='gaussian', link=None, categorical=None, append=True): '''Adds one or more terms to the model via an R-like formula syntax. Args: fixed (str): Optional formula specification of fixed effects. random (list): Optional list-based specification of random effects. priors (dict): Optional specification of priors for one or more terms. A dict where the keys are the names of terms in the model, and the values are either instances of class Prior or ints, floats, or strings that specify the width of the priors on a standardized scale. family (str, Family): A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are 'gaussian', 'bernoulli', 'poisson', and 't'. link (str): The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least 'identity', 'logit', 'inverse', and 'log'), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape. categorical (str, list): The names of any variables to treat as categorical. Can be either a single variable name, or a list of names. If categorical is None, the data type of the columns in the DataFrame will be used to infer handling. In cases where numeric columns are to be treated as categoricals (e.g., random factors coded as numerical IDs), explicitly passing variable names via this argument is recommended. append (bool): If True, terms are appended to the existing model rather than replacing any existing terms. This allows formula-based specification of the model in stages. ''' data = self.data # Primitive values (floats, strs) can be overwritten with Prior objects # so we need to make sure to copy first to avoid bad things happening # if user is re-using same prior dict in multiple models. if priors is None: priors = {} else: priors = deepcopy(priors) if not append: self.reset() # Explicitly convert columns to category if desired--though this # can also be done within the formula using C(). if categorical is not None: data = data.copy() cats = listify(categorical) data[cats] = data[cats].apply(lambda x: x.astype('category')) # Custom patsy.missing.NAAction class. Similar to patsy drop/raise # defaults, but changes the raised message and logs any dropped rows NA_handler = Custom_NA(dropna=self.dropna) # screen fixed terms if fixed is not None: if '~' in fixed: clean_fix = re.sub(r'\[.+\]', '', fixed) dmatrices(clean_fix, data=data, NA_action=NA_handler) else: dmatrix(fixed, data=data, NA_action=NA_handler) # screen random terms if random is not None: for term in listify(random): for side in term.split('|'): dmatrix(side, data=data, NA_action=NA_handler) # update the running list of complete cases if len(NA_handler.completes): self.completes.append(NA_handler.completes) # save arguments to pass to _add() args = dict(zip( ['fixed', 'random', 'priors', 'family', 'link', 'categorical'], [fixed, random, priors, family, link, categorical])) self.added_terms.append(args) self.built = False
python
def add(self, fixed=None, random=None, priors=None, family='gaussian', link=None, categorical=None, append=True): '''Adds one or more terms to the model via an R-like formula syntax. Args: fixed (str): Optional formula specification of fixed effects. random (list): Optional list-based specification of random effects. priors (dict): Optional specification of priors for one or more terms. A dict where the keys are the names of terms in the model, and the values are either instances of class Prior or ints, floats, or strings that specify the width of the priors on a standardized scale. family (str, Family): A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are 'gaussian', 'bernoulli', 'poisson', and 't'. link (str): The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least 'identity', 'logit', 'inverse', and 'log'), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape. categorical (str, list): The names of any variables to treat as categorical. Can be either a single variable name, or a list of names. If categorical is None, the data type of the columns in the DataFrame will be used to infer handling. In cases where numeric columns are to be treated as categoricals (e.g., random factors coded as numerical IDs), explicitly passing variable names via this argument is recommended. append (bool): If True, terms are appended to the existing model rather than replacing any existing terms. This allows formula-based specification of the model in stages. ''' data = self.data # Primitive values (floats, strs) can be overwritten with Prior objects # so we need to make sure to copy first to avoid bad things happening # if user is re-using same prior dict in multiple models. if priors is None: priors = {} else: priors = deepcopy(priors) if not append: self.reset() # Explicitly convert columns to category if desired--though this # can also be done within the formula using C(). if categorical is not None: data = data.copy() cats = listify(categorical) data[cats] = data[cats].apply(lambda x: x.astype('category')) # Custom patsy.missing.NAAction class. Similar to patsy drop/raise # defaults, but changes the raised message and logs any dropped rows NA_handler = Custom_NA(dropna=self.dropna) # screen fixed terms if fixed is not None: if '~' in fixed: clean_fix = re.sub(r'\[.+\]', '', fixed) dmatrices(clean_fix, data=data, NA_action=NA_handler) else: dmatrix(fixed, data=data, NA_action=NA_handler) # screen random terms if random is not None: for term in listify(random): for side in term.split('|'): dmatrix(side, data=data, NA_action=NA_handler) # update the running list of complete cases if len(NA_handler.completes): self.completes.append(NA_handler.completes) # save arguments to pass to _add() args = dict(zip( ['fixed', 'random', 'priors', 'family', 'link', 'categorical'], [fixed, random, priors, family, link, categorical])) self.added_terms.append(args) self.built = False
[ "def", "add", "(", "self", ",", "fixed", "=", "None", ",", "random", "=", "None", ",", "priors", "=", "None", ",", "family", "=", "'gaussian'", ",", "link", "=", "None", ",", "categorical", "=", "None", ",", "append", "=", "True", ")", ":", "data", "=", "self", ".", "data", "# Primitive values (floats, strs) can be overwritten with Prior objects", "# so we need to make sure to copy first to avoid bad things happening", "# if user is re-using same prior dict in multiple models.", "if", "priors", "is", "None", ":", "priors", "=", "{", "}", "else", ":", "priors", "=", "deepcopy", "(", "priors", ")", "if", "not", "append", ":", "self", ".", "reset", "(", ")", "# Explicitly convert columns to category if desired--though this", "# can also be done within the formula using C().", "if", "categorical", "is", "not", "None", ":", "data", "=", "data", ".", "copy", "(", ")", "cats", "=", "listify", "(", "categorical", ")", "data", "[", "cats", "]", "=", "data", "[", "cats", "]", ".", "apply", "(", "lambda", "x", ":", "x", ".", "astype", "(", "'category'", ")", ")", "# Custom patsy.missing.NAAction class. Similar to patsy drop/raise", "# defaults, but changes the raised message and logs any dropped rows", "NA_handler", "=", "Custom_NA", "(", "dropna", "=", "self", ".", "dropna", ")", "# screen fixed terms", "if", "fixed", "is", "not", "None", ":", "if", "'~'", "in", "fixed", ":", "clean_fix", "=", "re", ".", "sub", "(", "r'\\[.+\\]'", ",", "''", ",", "fixed", ")", "dmatrices", "(", "clean_fix", ",", "data", "=", "data", ",", "NA_action", "=", "NA_handler", ")", "else", ":", "dmatrix", "(", "fixed", ",", "data", "=", "data", ",", "NA_action", "=", "NA_handler", ")", "# screen random terms", "if", "random", "is", "not", "None", ":", "for", "term", "in", "listify", "(", "random", ")", ":", "for", "side", "in", "term", ".", "split", "(", "'|'", ")", ":", "dmatrix", "(", "side", ",", "data", "=", "data", ",", "NA_action", "=", "NA_handler", ")", "# update the running list of complete cases", "if", "len", "(", "NA_handler", ".", "completes", ")", ":", "self", ".", "completes", ".", "append", "(", "NA_handler", ".", "completes", ")", "# save arguments to pass to _add()", "args", "=", "dict", "(", "zip", "(", "[", "'fixed'", ",", "'random'", ",", "'priors'", ",", "'family'", ",", "'link'", ",", "'categorical'", "]", ",", "[", "fixed", ",", "random", ",", "priors", ",", "family", ",", "link", ",", "categorical", "]", ")", ")", "self", ".", "added_terms", ".", "append", "(", "args", ")", "self", ".", "built", "=", "False" ]
Adds one or more terms to the model via an R-like formula syntax. Args: fixed (str): Optional formula specification of fixed effects. random (list): Optional list-based specification of random effects. priors (dict): Optional specification of priors for one or more terms. A dict where the keys are the names of terms in the model, and the values are either instances of class Prior or ints, floats, or strings that specify the width of the priors on a standardized scale. family (str, Family): A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are 'gaussian', 'bernoulli', 'poisson', and 't'. link (str): The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least 'identity', 'logit', 'inverse', and 'log'), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape. categorical (str, list): The names of any variables to treat as categorical. Can be either a single variable name, or a list of names. If categorical is None, the data type of the columns in the DataFrame will be used to infer handling. In cases where numeric columns are to be treated as categoricals (e.g., random factors coded as numerical IDs), explicitly passing variable names via this argument is recommended. append (bool): If True, terms are appended to the existing model rather than replacing any existing terms. This allows formula-based specification of the model in stages.
[ "Adds", "one", "or", "more", "terms", "to", "the", "model", "via", "an", "R", "-", "like", "formula", "syntax", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L288-L372
227,361
bambinos/bambi
bambi/models.py
Model.set_priors
def set_priors(self, priors=None, fixed=None, random=None, match_derived_names=True): '''Set priors for one or more existing terms. Args: priors (dict): Dict of priors to update. Keys are names of terms to update; values are the new priors (either a Prior instance, or an int or float that scales the default priors). Note that a tuple can be passed as the key, in which case the same prior will be applied to all terms named in the tuple. fixed (Prior, int, float, str): a prior specification to apply to all fixed terms currently included in the model. random (Prior, int, float, str): a prior specification to apply to all random terms currently included in the model. match_derived_names (bool): if True, the specified prior(s) will be applied not only to terms that match the keyword exactly, but to the levels of random effects that were derived from the original specification with the passed name. For example, `priors={'condition|subject':0.5}` would apply the prior to the terms with names '1|subject', 'condition[T.1]|subject', and so on. If False, an exact match is required for the prior to be applied. ''' # save arguments to pass to _set_priors() at build time kwargs = dict(zip( ['priors', 'fixed', 'random', 'match_derived_names'], [priors, fixed, random, match_derived_names])) self._added_priors.update(kwargs) self.built = False
python
def set_priors(self, priors=None, fixed=None, random=None, match_derived_names=True): '''Set priors for one or more existing terms. Args: priors (dict): Dict of priors to update. Keys are names of terms to update; values are the new priors (either a Prior instance, or an int or float that scales the default priors). Note that a tuple can be passed as the key, in which case the same prior will be applied to all terms named in the tuple. fixed (Prior, int, float, str): a prior specification to apply to all fixed terms currently included in the model. random (Prior, int, float, str): a prior specification to apply to all random terms currently included in the model. match_derived_names (bool): if True, the specified prior(s) will be applied not only to terms that match the keyword exactly, but to the levels of random effects that were derived from the original specification with the passed name. For example, `priors={'condition|subject':0.5}` would apply the prior to the terms with names '1|subject', 'condition[T.1]|subject', and so on. If False, an exact match is required for the prior to be applied. ''' # save arguments to pass to _set_priors() at build time kwargs = dict(zip( ['priors', 'fixed', 'random', 'match_derived_names'], [priors, fixed, random, match_derived_names])) self._added_priors.update(kwargs) self.built = False
[ "def", "set_priors", "(", "self", ",", "priors", "=", "None", ",", "fixed", "=", "None", ",", "random", "=", "None", ",", "match_derived_names", "=", "True", ")", ":", "# save arguments to pass to _set_priors() at build time", "kwargs", "=", "dict", "(", "zip", "(", "[", "'priors'", ",", "'fixed'", ",", "'random'", ",", "'match_derived_names'", "]", ",", "[", "priors", ",", "fixed", ",", "random", ",", "match_derived_names", "]", ")", ")", "self", ".", "_added_priors", ".", "update", "(", "kwargs", ")", "self", ".", "built", "=", "False" ]
Set priors for one or more existing terms. Args: priors (dict): Dict of priors to update. Keys are names of terms to update; values are the new priors (either a Prior instance, or an int or float that scales the default priors). Note that a tuple can be passed as the key, in which case the same prior will be applied to all terms named in the tuple. fixed (Prior, int, float, str): a prior specification to apply to all fixed terms currently included in the model. random (Prior, int, float, str): a prior specification to apply to all random terms currently included in the model. match_derived_names (bool): if True, the specified prior(s) will be applied not only to terms that match the keyword exactly, but to the levels of random effects that were derived from the original specification with the passed name. For example, `priors={'condition|subject':0.5}` would apply the prior to the terms with names '1|subject', 'condition[T.1]|subject', and so on. If False, an exact match is required for the prior to be applied.
[ "Set", "priors", "for", "one", "or", "more", "existing", "terms", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L576-L605
227,362
bambinos/bambi
bambi/models.py
Model.fixed_terms
def fixed_terms(self): '''Return dict of all and only fixed effects in model.''' return {k: v for (k, v) in self.terms.items() if not v.random}
python
def fixed_terms(self): '''Return dict of all and only fixed effects in model.''' return {k: v for (k, v) in self.terms.items() if not v.random}
[ "def", "fixed_terms", "(", "self", ")", ":", "return", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "self", ".", "terms", ".", "items", "(", ")", "if", "not", "v", ".", "random", "}" ]
Return dict of all and only fixed effects in model.
[ "Return", "dict", "of", "all", "and", "only", "fixed", "effects", "in", "model", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L722-L724
227,363
bambinos/bambi
bambi/models.py
Model.random_terms
def random_terms(self): '''Return dict of all and only random effects in model.''' return {k: v for (k, v) in self.terms.items() if v.random}
python
def random_terms(self): '''Return dict of all and only random effects in model.''' return {k: v for (k, v) in self.terms.items() if v.random}
[ "def", "random_terms", "(", "self", ")", ":", "return", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "self", ".", "terms", ".", "items", "(", ")", "if", "v", ".", "random", "}" ]
Return dict of all and only random effects in model.
[ "Return", "dict", "of", "all", "and", "only", "random", "effects", "in", "model", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L727-L729
227,364
bambinos/bambi
bambi/priors.py
Prior.update
def update(self, **kwargs): '''Update the model arguments with additional arguments. Args: kwargs (dict): Optional keyword arguments to add to prior args. ''' # Backends expect numpy arrays, so make sure all numeric values are # represented as such. kwargs = {k: (np.array(v) if isinstance(v, (int, float)) else v) for k, v in kwargs.items()} self.args.update(kwargs)
python
def update(self, **kwargs): '''Update the model arguments with additional arguments. Args: kwargs (dict): Optional keyword arguments to add to prior args. ''' # Backends expect numpy arrays, so make sure all numeric values are # represented as such. kwargs = {k: (np.array(v) if isinstance(v, (int, float)) else v) for k, v in kwargs.items()} self.args.update(kwargs)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Backends expect numpy arrays, so make sure all numeric values are", "# represented as such.", "kwargs", "=", "{", "k", ":", "(", "np", ".", "array", "(", "v", ")", "if", "isinstance", "(", "v", ",", "(", "int", ",", "float", ")", ")", "else", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "}", "self", ".", "args", ".", "update", "(", "kwargs", ")" ]
Update the model arguments with additional arguments. Args: kwargs (dict): Optional keyword arguments to add to prior args.
[ "Update", "the", "model", "arguments", "with", "additional", "arguments", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/priors.py#L59-L70
227,365
bambinos/bambi
bambi/priors.py
PriorFactory.get
def get(self, dist=None, term=None, family=None): '''Retrieve default prior for a named distribution, term type, or family. Args: dist (str): Name of desired distribution. Note that the name is the key in the defaults dictionary, not the name of the Distribution object used to construct the prior. term (str): The type of term family to retrieve defaults for. Must be one of 'intercept', 'fixed', or 'random'. family (str): The name of the Family to retrieve. Must be a value defined internally. In the default config, this is one of 'gaussian', 'bernoulli', 'poisson', or 't'. ''' if dist is not None: if dist not in self.dists: raise ValueError( "'%s' is not a valid distribution name." % dist) return self._get_prior(self.dists[dist]) elif term is not None: if term not in self.terms: raise ValueError("'%s' is not a valid term type." % term) return self._get_prior(self.terms[term]) elif family is not None: if family not in self.families: raise ValueError("'%s' is not a valid family name." % family) _f = self.families[family] prior = self._get_prior(_f['dist']) return Family(family, prior, _f['link'], _f['parent'])
python
def get(self, dist=None, term=None, family=None): '''Retrieve default prior for a named distribution, term type, or family. Args: dist (str): Name of desired distribution. Note that the name is the key in the defaults dictionary, not the name of the Distribution object used to construct the prior. term (str): The type of term family to retrieve defaults for. Must be one of 'intercept', 'fixed', or 'random'. family (str): The name of the Family to retrieve. Must be a value defined internally. In the default config, this is one of 'gaussian', 'bernoulli', 'poisson', or 't'. ''' if dist is not None: if dist not in self.dists: raise ValueError( "'%s' is not a valid distribution name." % dist) return self._get_prior(self.dists[dist]) elif term is not None: if term not in self.terms: raise ValueError("'%s' is not a valid term type." % term) return self._get_prior(self.terms[term]) elif family is not None: if family not in self.families: raise ValueError("'%s' is not a valid family name." % family) _f = self.families[family] prior = self._get_prior(_f['dist']) return Family(family, prior, _f['link'], _f['parent'])
[ "def", "get", "(", "self", ",", "dist", "=", "None", ",", "term", "=", "None", ",", "family", "=", "None", ")", ":", "if", "dist", "is", "not", "None", ":", "if", "dist", "not", "in", "self", ".", "dists", ":", "raise", "ValueError", "(", "\"'%s' is not a valid distribution name.\"", "%", "dist", ")", "return", "self", ".", "_get_prior", "(", "self", ".", "dists", "[", "dist", "]", ")", "elif", "term", "is", "not", "None", ":", "if", "term", "not", "in", "self", ".", "terms", ":", "raise", "ValueError", "(", "\"'%s' is not a valid term type.\"", "%", "term", ")", "return", "self", ".", "_get_prior", "(", "self", ".", "terms", "[", "term", "]", ")", "elif", "family", "is", "not", "None", ":", "if", "family", "not", "in", "self", ".", "families", ":", "raise", "ValueError", "(", "\"'%s' is not a valid family name.\"", "%", "family", ")", "_f", "=", "self", ".", "families", "[", "family", "]", "prior", "=", "self", ".", "_get_prior", "(", "_f", "[", "'dist'", "]", ")", "return", "Family", "(", "family", ",", "prior", ",", "_f", "[", "'link'", "]", ",", "_f", "[", "'parent'", "]", ")" ]
Retrieve default prior for a named distribution, term type, or family. Args: dist (str): Name of desired distribution. Note that the name is the key in the defaults dictionary, not the name of the Distribution object used to construct the prior. term (str): The type of term family to retrieve defaults for. Must be one of 'intercept', 'fixed', or 'random'. family (str): The name of the Family to retrieve. Must be a value defined internally. In the default config, this is one of 'gaussian', 'bernoulli', 'poisson', or 't'.
[ "Retrieve", "default", "prior", "for", "a", "named", "distribution", "term", "type", "or", "family", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/priors.py#L153-L181
227,366
bambinos/bambi
bambi/backends/stan.py
StanBackEnd.reset
def reset(self): ''' Reset Stan model and all tracked distributions and parameters. ''' self.parameters = [] self.transformed_parameters = [] self.expressions = [] self.data = [] self.transformed_data = [] self.X = {} self.model = [] self.mu_cont = [] self.mu_cat = [] self._original_names = {} # variables to suppress in output. Stan uses limited set for variable # names, so track variable names we may need to simplify for the model # code and then sub back later. self._suppress_vars = ['yhat', 'lp__']
python
def reset(self): ''' Reset Stan model and all tracked distributions and parameters. ''' self.parameters = [] self.transformed_parameters = [] self.expressions = [] self.data = [] self.transformed_data = [] self.X = {} self.model = [] self.mu_cont = [] self.mu_cat = [] self._original_names = {} # variables to suppress in output. Stan uses limited set for variable # names, so track variable names we may need to simplify for the model # code and then sub back later. self._suppress_vars = ['yhat', 'lp__']
[ "def", "reset", "(", "self", ")", ":", "self", ".", "parameters", "=", "[", "]", "self", ".", "transformed_parameters", "=", "[", "]", "self", ".", "expressions", "=", "[", "]", "self", ".", "data", "=", "[", "]", "self", ".", "transformed_data", "=", "[", "]", "self", ".", "X", "=", "{", "}", "self", ".", "model", "=", "[", "]", "self", ".", "mu_cont", "=", "[", "]", "self", ".", "mu_cat", "=", "[", "]", "self", ".", "_original_names", "=", "{", "}", "# variables to suppress in output. Stan uses limited set for variable", "# names, so track variable names we may need to simplify for the model", "# code and then sub back later.", "self", ".", "_suppress_vars", "=", "[", "'yhat'", ",", "'lp__'", "]" ]
Reset Stan model and all tracked distributions and parameters.
[ "Reset", "Stan", "model", "and", "all", "tracked", "distributions", "and", "parameters", "." ]
b4a0ced917968bb99ca20915317417d708387946
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/backends/stan.py#L63-L80
227,367
nfcpy/nfcpy
src/nfc/clf/rcs956.py
Chipset.reset_mode
def reset_mode(self): """Send a Reset command to set the operation mode to 0.""" self.command(0x18, b"\x01", timeout=0.1) self.transport.write(Chipset.ACK) time.sleep(0.010)
python
def reset_mode(self): """Send a Reset command to set the operation mode to 0.""" self.command(0x18, b"\x01", timeout=0.1) self.transport.write(Chipset.ACK) time.sleep(0.010)
[ "def", "reset_mode", "(", "self", ")", ":", "self", ".", "command", "(", "0x18", ",", "b\"\\x01\"", ",", "timeout", "=", "0.1", ")", "self", ".", "transport", ".", "write", "(", "Chipset", ".", "ACK", ")", "time", ".", "sleep", "(", "0.010", ")" ]
Send a Reset command to set the operation mode to 0.
[ "Send", "a", "Reset", "command", "to", "set", "the", "operation", "mode", "to", "0", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs956.py#L149-L153
227,368
nfcpy/nfcpy
src/nfc/clf/rcs956.py
Device.sense_ttb
def sense_ttb(self, target): """Activate the RF field and probe for a Type B Target. The RC-S956 can discover Type B Targets (Type 4B Tag) at 106 kbps. For a Type 4B Tag the firmware automatically sends an ATTRIB command that configures the use of DID and 64 byte maximum frame size. The driver reverts this configuration with a DESELECT and WUPB command to return the target prepared for activation (which nfcpy does in the tag activation code). """ return super(Device, self).sense_ttb(target, did=b'\x01')
python
def sense_ttb(self, target): """Activate the RF field and probe for a Type B Target. The RC-S956 can discover Type B Targets (Type 4B Tag) at 106 kbps. For a Type 4B Tag the firmware automatically sends an ATTRIB command that configures the use of DID and 64 byte maximum frame size. The driver reverts this configuration with a DESELECT and WUPB command to return the target prepared for activation (which nfcpy does in the tag activation code). """ return super(Device, self).sense_ttb(target, did=b'\x01')
[ "def", "sense_ttb", "(", "self", ",", "target", ")", ":", "return", "super", "(", "Device", ",", "self", ")", ".", "sense_ttb", "(", "target", ",", "did", "=", "b'\\x01'", ")" ]
Activate the RF field and probe for a Type B Target. The RC-S956 can discover Type B Targets (Type 4B Tag) at 106 kbps. For a Type 4B Tag the firmware automatically sends an ATTRIB command that configures the use of DID and 64 byte maximum frame size. The driver reverts this configuration with a DESELECT and WUPB command to return the target prepared for activation (which nfcpy does in the tag activation code).
[ "Activate", "the", "RF", "field", "and", "probe", "for", "a", "Type", "B", "Target", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs956.py#L231-L242
227,369
nfcpy/nfcpy
src/nfc/clf/rcs956.py
Device.sense_dep
def sense_dep(self, target): """Search for a DEP Target in active or passive communication mode. """ # Set timeout for PSL_RES and ATR_RES self.chipset.rf_configuration(0x02, b"\x0B\x0B\x0A") return super(Device, self).sense_dep(target)
python
def sense_dep(self, target): """Search for a DEP Target in active or passive communication mode. """ # Set timeout for PSL_RES and ATR_RES self.chipset.rf_configuration(0x02, b"\x0B\x0B\x0A") return super(Device, self).sense_dep(target)
[ "def", "sense_dep", "(", "self", ",", "target", ")", ":", "# Set timeout for PSL_RES and ATR_RES", "self", ".", "chipset", ".", "rf_configuration", "(", "0x02", ",", "b\"\\x0B\\x0B\\x0A\"", ")", "return", "super", "(", "Device", ",", "self", ")", ".", "sense_dep", "(", "target", ")" ]
Search for a DEP Target in active or passive communication mode.
[ "Search", "for", "a", "DEP", "Target", "in", "active", "or", "passive", "communication", "mode", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs956.py#L250-L256
227,370
nfcpy/nfcpy
src/nfc/handover/client.py
HandoverClient.send
def send(self, message): """Send a handover request message to the remote server.""" log.debug("sending '{0}' message".format(message.type)) send_miu = self.socket.getsockopt(nfc.llcp.SO_SNDMIU) try: data = str(message) except nfc.llcp.EncodeError as e: log.error("message encoding failed: {0}".format(e)) else: return self._send(data, send_miu)
python
def send(self, message): """Send a handover request message to the remote server.""" log.debug("sending '{0}' message".format(message.type)) send_miu = self.socket.getsockopt(nfc.llcp.SO_SNDMIU) try: data = str(message) except nfc.llcp.EncodeError as e: log.error("message encoding failed: {0}".format(e)) else: return self._send(data, send_miu)
[ "def", "send", "(", "self", ",", "message", ")", ":", "log", ".", "debug", "(", "\"sending '{0}' message\"", ".", "format", "(", "message", ".", "type", ")", ")", "send_miu", "=", "self", ".", "socket", ".", "getsockopt", "(", "nfc", ".", "llcp", ".", "SO_SNDMIU", ")", "try", ":", "data", "=", "str", "(", "message", ")", "except", "nfc", ".", "llcp", ".", "EncodeError", "as", "e", ":", "log", ".", "error", "(", "\"message encoding failed: {0}\"", ".", "format", "(", "e", ")", ")", "else", ":", "return", "self", ".", "_send", "(", "data", ",", "send_miu", ")" ]
Send a handover request message to the remote server.
[ "Send", "a", "handover", "request", "message", "to", "the", "remote", "server", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/handover/client.py#L59-L68
227,371
nfcpy/nfcpy
src/nfc/handover/client.py
HandoverClient.recv
def recv(self, timeout=None): """Receive a handover select message from the remote server.""" message = self._recv(timeout) if message and message.type == "urn:nfc:wkt:Hs": log.debug("received '{0}' message".format(message.type)) return nfc.ndef.HandoverSelectMessage(message) else: log.error("received invalid message type {0}".format(message.type)) return None
python
def recv(self, timeout=None): """Receive a handover select message from the remote server.""" message = self._recv(timeout) if message and message.type == "urn:nfc:wkt:Hs": log.debug("received '{0}' message".format(message.type)) return nfc.ndef.HandoverSelectMessage(message) else: log.error("received invalid message type {0}".format(message.type)) return None
[ "def", "recv", "(", "self", ",", "timeout", "=", "None", ")", ":", "message", "=", "self", ".", "_recv", "(", "timeout", ")", "if", "message", "and", "message", ".", "type", "==", "\"urn:nfc:wkt:Hs\"", ":", "log", ".", "debug", "(", "\"received '{0}' message\"", ".", "format", "(", "message", ".", "type", ")", ")", "return", "nfc", ".", "ndef", ".", "HandoverSelectMessage", "(", "message", ")", "else", ":", "log", ".", "error", "(", "\"received invalid message type {0}\"", ".", "format", "(", "message", ".", "type", ")", ")", "return", "None" ]
Receive a handover select message from the remote server.
[ "Receive", "a", "handover", "select", "message", "from", "the", "remote", "server", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/handover/client.py#L78-L86
227,372
nfcpy/nfcpy
src/nfc/clf/pn531.py
Device.sense_ttb
def sense_ttb(self, target): """Sense for a Type B Target is not supported.""" info = "{device} does not support sense for Type B Target" raise nfc.clf.UnsupportedTargetError(info.format(device=self))
python
def sense_ttb(self, target): """Sense for a Type B Target is not supported.""" info = "{device} does not support sense for Type B Target" raise nfc.clf.UnsupportedTargetError(info.format(device=self))
[ "def", "sense_ttb", "(", "self", ",", "target", ")", ":", "info", "=", "\"{device} does not support sense for Type B Target\"", "raise", "nfc", ".", "clf", ".", "UnsupportedTargetError", "(", "info", ".", "format", "(", "device", "=", "self", ")", ")" ]
Sense for a Type B Target is not supported.
[ "Sense", "for", "a", "Type", "B", "Target", "is", "not", "supported", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/pn531.py#L231-L234
227,373
nfcpy/nfcpy
src/nfc/clf/pn531.py
Device.sense_dep
def sense_dep(self, target): """Search for a DEP Target in active communication mode. Because the PN531 does not implement the extended frame syntax for host controller communication, it can not support the maximum payload size of 254 byte. The driver handles this by modifying the length-reduction values in atr_req and atr_res. """ if target.atr_req[15] & 0x30 == 0x30: self.log.warning("must reduce the max payload size in atr_req") target.atr_req[15] = (target.atr_req[15] & 0xCF) | 0x20 target = super(Device, self).sense_dep(target) if target is None: return if target.atr_res[16] & 0x30 == 0x30: self.log.warning("must reduce the max payload size in atr_res") target.atr_res[16] = (target.atr_res[16] & 0xCF) | 0x20 return target
python
def sense_dep(self, target): """Search for a DEP Target in active communication mode. Because the PN531 does not implement the extended frame syntax for host controller communication, it can not support the maximum payload size of 254 byte. The driver handles this by modifying the length-reduction values in atr_req and atr_res. """ if target.atr_req[15] & 0x30 == 0x30: self.log.warning("must reduce the max payload size in atr_req") target.atr_req[15] = (target.atr_req[15] & 0xCF) | 0x20 target = super(Device, self).sense_dep(target) if target is None: return if target.atr_res[16] & 0x30 == 0x30: self.log.warning("must reduce the max payload size in atr_res") target.atr_res[16] = (target.atr_res[16] & 0xCF) | 0x20 return target
[ "def", "sense_dep", "(", "self", ",", "target", ")", ":", "if", "target", ".", "atr_req", "[", "15", "]", "&", "0x30", "==", "0x30", ":", "self", ".", "log", ".", "warning", "(", "\"must reduce the max payload size in atr_req\"", ")", "target", ".", "atr_req", "[", "15", "]", "=", "(", "target", ".", "atr_req", "[", "15", "]", "&", "0xCF", ")", "|", "0x20", "target", "=", "super", "(", "Device", ",", "self", ")", ".", "sense_dep", "(", "target", ")", "if", "target", "is", "None", ":", "return", "if", "target", ".", "atr_res", "[", "16", "]", "&", "0x30", "==", "0x30", ":", "self", ".", "log", ".", "warning", "(", "\"must reduce the max payload size in atr_res\"", ")", "target", ".", "atr_res", "[", "16", "]", "=", "(", "target", ".", "atr_res", "[", "16", "]", "&", "0xCF", ")", "|", "0x20", "return", "target" ]
Search for a DEP Target in active communication mode. Because the PN531 does not implement the extended frame syntax for host controller communication, it can not support the maximum payload size of 254 byte. The driver handles this by modifying the length-reduction values in atr_req and atr_res.
[ "Search", "for", "a", "DEP", "Target", "in", "active", "communication", "mode", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/pn531.py#L242-L263
227,374
nfcpy/nfcpy
src/nfc/tag/tt2_nxp.py
NTAG203.protect
def protect(self, password=None, read_protect=False, protect_from=0): """Set lock bits to disable future memory modifications. If *password* is None, all memory pages except the 16-bit counter in page 41 are protected by setting the relevant lock bits (note that lock bits can not be reset). If valid NDEF management data is found in page 4, protect() also sets the NDEF write flag to read-only. The NTAG203 can not be password protected. If a *password* argument is provided, the protect() method always returns False. """ return super(NTAG203, self).protect( password, read_protect, protect_from)
python
def protect(self, password=None, read_protect=False, protect_from=0): """Set lock bits to disable future memory modifications. If *password* is None, all memory pages except the 16-bit counter in page 41 are protected by setting the relevant lock bits (note that lock bits can not be reset). If valid NDEF management data is found in page 4, protect() also sets the NDEF write flag to read-only. The NTAG203 can not be password protected. If a *password* argument is provided, the protect() method always returns False. """ return super(NTAG203, self).protect( password, read_protect, protect_from)
[ "def", "protect", "(", "self", ",", "password", "=", "None", ",", "read_protect", "=", "False", ",", "protect_from", "=", "0", ")", ":", "return", "super", "(", "NTAG203", ",", "self", ")", ".", "protect", "(", "password", ",", "read_protect", ",", "protect_from", ")" ]
Set lock bits to disable future memory modifications. If *password* is None, all memory pages except the 16-bit counter in page 41 are protected by setting the relevant lock bits (note that lock bits can not be reset). If valid NDEF management data is found in page 4, protect() also sets the NDEF write flag to read-only. The NTAG203 can not be password protected. If a *password* argument is provided, the protect() method always returns False.
[ "Set", "lock", "bits", "to", "disable", "future", "memory", "modifications", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2_nxp.py#L268-L283
227,375
nfcpy/nfcpy
src/nfc/tag/tt2_nxp.py
NTAG21x.signature
def signature(self): """The 32-byte ECC tag signature programmed at chip production. The signature is provided as a string and can only be read. The signature attribute is always loaded from the tag when it is accessed, i.e. it is not cached. If communication with the tag fails for some reason the signature attribute is set to a 32-byte string of all zeros. """ log.debug("read tag signature") try: return bytes(self.transceive(b"\x3C\x00")) except tt2.Type2TagCommandError: return 32 * b"\0"
python
def signature(self): """The 32-byte ECC tag signature programmed at chip production. The signature is provided as a string and can only be read. The signature attribute is always loaded from the tag when it is accessed, i.e. it is not cached. If communication with the tag fails for some reason the signature attribute is set to a 32-byte string of all zeros. """ log.debug("read tag signature") try: return bytes(self.transceive(b"\x3C\x00")) except tt2.Type2TagCommandError: return 32 * b"\0"
[ "def", "signature", "(", "self", ")", ":", "log", ".", "debug", "(", "\"read tag signature\"", ")", "try", ":", "return", "bytes", "(", "self", ".", "transceive", "(", "b\"\\x3C\\x00\"", ")", ")", "except", "tt2", ".", "Type2TagCommandError", ":", "return", "32", "*", "b\"\\0\"" ]
The 32-byte ECC tag signature programmed at chip production. The signature is provided as a string and can only be read. The signature attribute is always loaded from the tag when it is accessed, i.e. it is not cached. If communication with the tag fails for some reason the signature attribute is set to a 32-byte string of all zeros.
[ "The", "32", "-", "byte", "ECC", "tag", "signature", "programmed", "at", "chip", "production", ".", "The", "signature", "is", "provided", "as", "a", "string", "and", "can", "only", "be", "read", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2_nxp.py#L330-L344
227,376
nfcpy/nfcpy
src/nfc/tag/tt2_nxp.py
NTAG21x.protect
def protect(self, password=None, read_protect=False, protect_from=0): """Set password protection or permanent lock bits. If the *password* argument is None, all memory pages will be protected by setting the relevant lock bits (note that lock bits can not be reset). If valid NDEF management data is found, protect() also sets the NDEF write flag to read-only. All Tags of the NTAG21x family can alternatively be protected by password. If a *password* argument is provided, the protect() method writes the first 4 byte of the *password* string into the Tag's password (PWD) memory bytes and the following 2 byte of the *password* string into the password acknowledge (PACK) memory bytes. Factory default values are used if the *password* argument is an empty string. Lock bits are not set for password protection. The *read_protect* and *protect_from* arguments are only evaluated if *password* is not None. If *read_protect* is True, the memory protection bit (PROT) is set to require password verification also for reading of protected memory pages. The value of *protect_from* determines the first password protected memory page (one page is 4 byte) with the exception that the smallest set value is page 3 even if *protect_from* is smaller. """ args = (password, read_protect, protect_from) return super(NTAG21x, self).protect(*args)
python
def protect(self, password=None, read_protect=False, protect_from=0): """Set password protection or permanent lock bits. If the *password* argument is None, all memory pages will be protected by setting the relevant lock bits (note that lock bits can not be reset). If valid NDEF management data is found, protect() also sets the NDEF write flag to read-only. All Tags of the NTAG21x family can alternatively be protected by password. If a *password* argument is provided, the protect() method writes the first 4 byte of the *password* string into the Tag's password (PWD) memory bytes and the following 2 byte of the *password* string into the password acknowledge (PACK) memory bytes. Factory default values are used if the *password* argument is an empty string. Lock bits are not set for password protection. The *read_protect* and *protect_from* arguments are only evaluated if *password* is not None. If *read_protect* is True, the memory protection bit (PROT) is set to require password verification also for reading of protected memory pages. The value of *protect_from* determines the first password protected memory page (one page is 4 byte) with the exception that the smallest set value is page 3 even if *protect_from* is smaller. """ args = (password, read_protect, protect_from) return super(NTAG21x, self).protect(*args)
[ "def", "protect", "(", "self", ",", "password", "=", "None", ",", "read_protect", "=", "False", ",", "protect_from", "=", "0", ")", ":", "args", "=", "(", "password", ",", "read_protect", ",", "protect_from", ")", "return", "super", "(", "NTAG21x", ",", "self", ")", ".", "protect", "(", "*", "args", ")" ]
Set password protection or permanent lock bits. If the *password* argument is None, all memory pages will be protected by setting the relevant lock bits (note that lock bits can not be reset). If valid NDEF management data is found, protect() also sets the NDEF write flag to read-only. All Tags of the NTAG21x family can alternatively be protected by password. If a *password* argument is provided, the protect() method writes the first 4 byte of the *password* string into the Tag's password (PWD) memory bytes and the following 2 byte of the *password* string into the password acknowledge (PACK) memory bytes. Factory default values are used if the *password* argument is an empty string. Lock bits are not set for password protection. The *read_protect* and *protect_from* arguments are only evaluated if *password* is not None. If *read_protect* is True, the memory protection bit (PROT) is set to require password verification also for reading of protected memory pages. The value of *protect_from* determines the first password protected memory page (one page is 4 byte) with the exception that the smallest set value is page 3 even if *protect_from* is smaller.
[ "Set", "password", "protection", "or", "permanent", "lock", "bits", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2_nxp.py#L346-L374
227,377
nfcpy/nfcpy
src/nfc/clf/device.py
Device.mute
def mute(self): """Mutes all existing communication, most notably the device will no longer generate a 13.56 MHz carrier signal when operating as Initiator. """ fname = "mute" cname = self.__class__.__module__ + '.' + self.__class__.__name__ raise NotImplementedError("%s.%s() is required" % (cname, fname))
python
def mute(self): """Mutes all existing communication, most notably the device will no longer generate a 13.56 MHz carrier signal when operating as Initiator. """ fname = "mute" cname = self.__class__.__module__ + '.' + self.__class__.__name__ raise NotImplementedError("%s.%s() is required" % (cname, fname))
[ "def", "mute", "(", "self", ")", ":", "fname", "=", "\"mute\"", "cname", "=", "self", ".", "__class__", ".", "__module__", "+", "'.'", "+", "self", ".", "__class__", ".", "__name__", "raise", "NotImplementedError", "(", "\"%s.%s() is required\"", "%", "(", "cname", ",", "fname", ")", ")" ]
Mutes all existing communication, most notably the device will no longer generate a 13.56 MHz carrier signal when operating as Initiator.
[ "Mutes", "all", "existing", "communication", "most", "notably", "the", "device", "will", "no", "longer", "generate", "a", "13", ".", "56", "MHz", "carrier", "signal", "when", "operating", "as", "Initiator", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/device.py#L174-L182
227,378
nfcpy/nfcpy
src/nfc/clf/device.py
Device.listen_tta
def listen_tta(self, target, timeout): """Listen as Type A Target. Waits to receive a SENS_REQ command at the bitrate set by **target.brty** and sends the **target.sens_res** response. Depending on the SENS_RES bytes, the Initiator then sends an RID_CMD (SENS_RES coded for a Type 1 Tag) or SDD_REQ and SEL_REQ (SENS_RES coded for a Type 2/4 Tag). Responses are then generated from the **rid_res** or **sdd_res** and **sel_res** attributes in *target*. Note that none of the currently supported hardware can actually receive an RID_CMD, thus Type 1 Tag emulation is impossible. Arguments: target (nfc.clf.LocalTarget): Supplies bitrate and mandatory response data to reply when being discovered. timeout (float): The maximum number of seconds to wait for a discovery command. Returns: nfc.clf.LocalTarget: Command data received from the remote Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as one of the **tt1_cmd**, **tt2_cmd** or **tt4_cmd** attribute (note that unset attributes are always None). Raises: nfc.clf.UnsupportedTargetError: The method is not supported or the *target* argument requested an unsupported bitrate (or has a wrong technology type identifier). ~exceptions.ValueError: A required target response attribute is not present or does not supply the number of bytes expected. """ fname = "listen_tta" cname = self.__class__.__module__ + '.' + self.__class__.__name__ raise NotImplementedError("%s.%s() is required" % (cname, fname))
python
def listen_tta(self, target, timeout): """Listen as Type A Target. Waits to receive a SENS_REQ command at the bitrate set by **target.brty** and sends the **target.sens_res** response. Depending on the SENS_RES bytes, the Initiator then sends an RID_CMD (SENS_RES coded for a Type 1 Tag) or SDD_REQ and SEL_REQ (SENS_RES coded for a Type 2/4 Tag). Responses are then generated from the **rid_res** or **sdd_res** and **sel_res** attributes in *target*. Note that none of the currently supported hardware can actually receive an RID_CMD, thus Type 1 Tag emulation is impossible. Arguments: target (nfc.clf.LocalTarget): Supplies bitrate and mandatory response data to reply when being discovered. timeout (float): The maximum number of seconds to wait for a discovery command. Returns: nfc.clf.LocalTarget: Command data received from the remote Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as one of the **tt1_cmd**, **tt2_cmd** or **tt4_cmd** attribute (note that unset attributes are always None). Raises: nfc.clf.UnsupportedTargetError: The method is not supported or the *target* argument requested an unsupported bitrate (or has a wrong technology type identifier). ~exceptions.ValueError: A required target response attribute is not present or does not supply the number of bytes expected. """ fname = "listen_tta" cname = self.__class__.__module__ + '.' + self.__class__.__name__ raise NotImplementedError("%s.%s() is required" % (cname, fname))
[ "def", "listen_tta", "(", "self", ",", "target", ",", "timeout", ")", ":", "fname", "=", "\"listen_tta\"", "cname", "=", "self", ".", "__class__", ".", "__module__", "+", "'.'", "+", "self", ".", "__class__", ".", "__name__", "raise", "NotImplementedError", "(", "\"%s.%s() is required\"", "%", "(", "cname", ",", "fname", ")", ")" ]
Listen as Type A Target. Waits to receive a SENS_REQ command at the bitrate set by **target.brty** and sends the **target.sens_res** response. Depending on the SENS_RES bytes, the Initiator then sends an RID_CMD (SENS_RES coded for a Type 1 Tag) or SDD_REQ and SEL_REQ (SENS_RES coded for a Type 2/4 Tag). Responses are then generated from the **rid_res** or **sdd_res** and **sel_res** attributes in *target*. Note that none of the currently supported hardware can actually receive an RID_CMD, thus Type 1 Tag emulation is impossible. Arguments: target (nfc.clf.LocalTarget): Supplies bitrate and mandatory response data to reply when being discovered. timeout (float): The maximum number of seconds to wait for a discovery command. Returns: nfc.clf.LocalTarget: Command data received from the remote Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as one of the **tt1_cmd**, **tt2_cmd** or **tt4_cmd** attribute (note that unset attributes are always None). Raises: nfc.clf.UnsupportedTargetError: The method is not supported or the *target* argument requested an unsupported bitrate (or has a wrong technology type identifier). ~exceptions.ValueError: A required target response attribute is not present or does not supply the number of bytes expected.
[ "Listen", "as", "Type", "A", "Target", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/device.py#L324-L369
227,379
nfcpy/nfcpy
src/nfc/clf/device.py
Device.send_cmd_recv_rsp
def send_cmd_recv_rsp(self, target, data, timeout): """Exchange data with a remote Target Sends command *data* to the remote *target* discovered in the most recent call to one of the sense_xxx() methods. Note that *target* becomes invalid with any call to mute(), sense_xxx() or listen_xxx() Arguments: target (nfc.clf.RemoteTarget): The target returned by the last successful call of a sense_xxx() method. data (bytearray): The binary data to send to the remote device. timeout (float): The maximum number of seconds to wait for response data from the remote device. Returns: bytearray: Response data received from the remote device. Raises: nfc.clf.CommunicationError: When no data was received. """ fname = "send_cmd_recv_rsp" cname = self.__class__.__module__ + '.' + self.__class__.__name__ raise NotImplementedError("%s.%s() is required" % (cname, fname))
python
def send_cmd_recv_rsp(self, target, data, timeout): """Exchange data with a remote Target Sends command *data* to the remote *target* discovered in the most recent call to one of the sense_xxx() methods. Note that *target* becomes invalid with any call to mute(), sense_xxx() or listen_xxx() Arguments: target (nfc.clf.RemoteTarget): The target returned by the last successful call of a sense_xxx() method. data (bytearray): The binary data to send to the remote device. timeout (float): The maximum number of seconds to wait for response data from the remote device. Returns: bytearray: Response data received from the remote device. Raises: nfc.clf.CommunicationError: When no data was received. """ fname = "send_cmd_recv_rsp" cname = self.__class__.__module__ + '.' + self.__class__.__name__ raise NotImplementedError("%s.%s() is required" % (cname, fname))
[ "def", "send_cmd_recv_rsp", "(", "self", ",", "target", ",", "data", ",", "timeout", ")", ":", "fname", "=", "\"send_cmd_recv_rsp\"", "cname", "=", "self", ".", "__class__", ".", "__module__", "+", "'.'", "+", "self", ".", "__class__", ".", "__name__", "raise", "NotImplementedError", "(", "\"%s.%s() is required\"", "%", "(", "cname", ",", "fname", ")", ")" ]
Exchange data with a remote Target Sends command *data* to the remote *target* discovered in the most recent call to one of the sense_xxx() methods. Note that *target* becomes invalid with any call to mute(), sense_xxx() or listen_xxx() Arguments: target (nfc.clf.RemoteTarget): The target returned by the last successful call of a sense_xxx() method. data (bytearray): The binary data to send to the remote device. timeout (float): The maximum number of seconds to wait for response data from the remote device. Returns: bytearray: Response data received from the remote device. Raises: nfc.clf.CommunicationError: When no data was received.
[ "Exchange", "data", "with", "a", "remote", "Target" ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/device.py#L496-L526
227,380
nfcpy/nfcpy
src/nfc/clf/device.py
Device.get_max_recv_data_size
def get_max_recv_data_size(self, target): """Returns the maximum number of data bytes for receiving. The maximum number of data bytes acceptable for receiving with either :meth:`send_cmd_recv_rsp` or :meth:`send_rsp_recv_cmd`. The value reflects the local device capabilities for receiving in the mode determined by *target*. It does not relate to any protocol capabilities and negotiations. Arguments: target (nfc.clf.Target): The current local or remote communication target. Returns: int: Maximum number of data bytes supported for receiving. """ fname = "get_max_recv_data_size" cname = self.__class__.__module__ + '.' + self.__class__.__name__ raise NotImplementedError("%s.%s() is required" % (cname, fname))
python
def get_max_recv_data_size(self, target): """Returns the maximum number of data bytes for receiving. The maximum number of data bytes acceptable for receiving with either :meth:`send_cmd_recv_rsp` or :meth:`send_rsp_recv_cmd`. The value reflects the local device capabilities for receiving in the mode determined by *target*. It does not relate to any protocol capabilities and negotiations. Arguments: target (nfc.clf.Target): The current local or remote communication target. Returns: int: Maximum number of data bytes supported for receiving. """ fname = "get_max_recv_data_size" cname = self.__class__.__module__ + '.' + self.__class__.__name__ raise NotImplementedError("%s.%s() is required" % (cname, fname))
[ "def", "get_max_recv_data_size", "(", "self", ",", "target", ")", ":", "fname", "=", "\"get_max_recv_data_size\"", "cname", "=", "self", ".", "__class__", ".", "__module__", "+", "'.'", "+", "self", ".", "__class__", ".", "__name__", "raise", "NotImplementedError", "(", "\"%s.%s() is required\"", "%", "(", "cname", ",", "fname", ")", ")" ]
Returns the maximum number of data bytes for receiving. The maximum number of data bytes acceptable for receiving with either :meth:`send_cmd_recv_rsp` or :meth:`send_rsp_recv_cmd`. The value reflects the local device capabilities for receiving in the mode determined by *target*. It does not relate to any protocol capabilities and negotiations. Arguments: target (nfc.clf.Target): The current local or remote communication target. Returns: int: Maximum number of data bytes supported for receiving.
[ "Returns", "the", "maximum", "number", "of", "data", "bytes", "for", "receiving", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/device.py#L583-L604
227,381
nfcpy/nfcpy
src/nfc/tag/tt2.py
Type2Tag.format
def format(self, version=None, wipe=None): """Erase the NDEF message on a Type 2 Tag. The :meth:`format` method will reset the length of the NDEF message on a type 2 tag to zero, thus the tag will appear to be empty. Additionally, if the *wipe* argument is set to some integer then :meth:`format` will overwrite all user date that follows the NDEF message TLV with that integer (mod 256). If an NDEF message TLV is not present it will be created with a length of zero. Despite it's name, the :meth:`format` method can not format a blank tag to make it NDEF compatible. This is because the user data are of a type 2 tag can not be safely determined, also reading all memory pages until an error response yields only the total memory size which includes an undetermined number of special pages at the end of memory. It is also not possible to change the NDEF mapping version, located in a one-time-programmable area of the tag memory. """ return super(Type2Tag, self).format(version, wipe)
python
def format(self, version=None, wipe=None): """Erase the NDEF message on a Type 2 Tag. The :meth:`format` method will reset the length of the NDEF message on a type 2 tag to zero, thus the tag will appear to be empty. Additionally, if the *wipe* argument is set to some integer then :meth:`format` will overwrite all user date that follows the NDEF message TLV with that integer (mod 256). If an NDEF message TLV is not present it will be created with a length of zero. Despite it's name, the :meth:`format` method can not format a blank tag to make it NDEF compatible. This is because the user data are of a type 2 tag can not be safely determined, also reading all memory pages until an error response yields only the total memory size which includes an undetermined number of special pages at the end of memory. It is also not possible to change the NDEF mapping version, located in a one-time-programmable area of the tag memory. """ return super(Type2Tag, self).format(version, wipe)
[ "def", "format", "(", "self", ",", "version", "=", "None", ",", "wipe", "=", "None", ")", ":", "return", "super", "(", "Type2Tag", ",", "self", ")", ".", "format", "(", "version", ",", "wipe", ")" ]
Erase the NDEF message on a Type 2 Tag. The :meth:`format` method will reset the length of the NDEF message on a type 2 tag to zero, thus the tag will appear to be empty. Additionally, if the *wipe* argument is set to some integer then :meth:`format` will overwrite all user date that follows the NDEF message TLV with that integer (mod 256). If an NDEF message TLV is not present it will be created with a length of zero. Despite it's name, the :meth:`format` method can not format a blank tag to make it NDEF compatible. This is because the user data are of a type 2 tag can not be safely determined, also reading all memory pages until an error response yields only the total memory size which includes an undetermined number of special pages at the end of memory. It is also not possible to change the NDEF mapping version, located in a one-time-programmable area of the tag memory.
[ "Erase", "the", "NDEF", "message", "on", "a", "Type", "2", "Tag", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L346-L368
227,382
nfcpy/nfcpy
src/nfc/tag/tt2.py
Type2Tag.protect
def protect(self, password=None, read_protect=False, protect_from=0): """Protect the tag against write access, i.e. make it read-only. :meth:`Type2Tag.protect` switches an NFC Forum Type 2 Tag to read-only state by setting all lock bits to 1. This operation can not be reversed. If the tag is not an NFC Forum Tag, i.e. it is not formatted with an NDEF Capability Container, the :meth:`protect` method simply returns :const:`False`. A generic Type 2 Tag can not be protected with a password. If the *password* argument is provided, the :meth:`protect` method does nothing else than return :const:`False`. The *read_protect* and *protect_from* arguments are safely ignored. """ return super(Type2Tag, self).protect( password, read_protect, protect_from)
python
def protect(self, password=None, read_protect=False, protect_from=0): """Protect the tag against write access, i.e. make it read-only. :meth:`Type2Tag.protect` switches an NFC Forum Type 2 Tag to read-only state by setting all lock bits to 1. This operation can not be reversed. If the tag is not an NFC Forum Tag, i.e. it is not formatted with an NDEF Capability Container, the :meth:`protect` method simply returns :const:`False`. A generic Type 2 Tag can not be protected with a password. If the *password* argument is provided, the :meth:`protect` method does nothing else than return :const:`False`. The *read_protect* and *protect_from* arguments are safely ignored. """ return super(Type2Tag, self).protect( password, read_protect, protect_from)
[ "def", "protect", "(", "self", ",", "password", "=", "None", ",", "read_protect", "=", "False", ",", "protect_from", "=", "0", ")", ":", "return", "super", "(", "Type2Tag", ",", "self", ")", ".", "protect", "(", "password", ",", "read_protect", ",", "protect_from", ")" ]
Protect the tag against write access, i.e. make it read-only. :meth:`Type2Tag.protect` switches an NFC Forum Type 2 Tag to read-only state by setting all lock bits to 1. This operation can not be reversed. If the tag is not an NFC Forum Tag, i.e. it is not formatted with an NDEF Capability Container, the :meth:`protect` method simply returns :const:`False`. A generic Type 2 Tag can not be protected with a password. If the *password* argument is provided, the :meth:`protect` method does nothing else than return :const:`False`. The *read_protect* and *protect_from* arguments are safely ignored.
[ "Protect", "the", "tag", "against", "write", "access", "i", ".", "e", ".", "make", "it", "read", "-", "only", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L385-L402
227,383
nfcpy/nfcpy
src/nfc/tag/tt2.py
Type2Tag.read
def read(self, page): """Send a READ command to retrieve data from the tag. The *page* argument specifies the offset in multiples of 4 bytes (i.e. page number 1 will return bytes 4 to 19). The data returned is a byte array of length 16 or None if the block is outside the readable memory range. Command execution errors raise :exc:`Type2TagCommandError`. """ log.debug("read pages {0} to {1}".format(page, page+3)) data = self.transceive("\x30"+chr(page % 256), timeout=0.005) if len(data) == 1 and data[0] & 0xFA == 0x00: log.debug("received nak response") self.target.sel_req = self.target.sdd_res[:] self._target = self.clf.sense(self.target) raise Type2TagCommandError( INVALID_PAGE_ERROR if self.target else nfc.tag.RECEIVE_ERROR) if len(data) != 16: log.debug("invalid response " + hexlify(data)) raise Type2TagCommandError(INVALID_RESPONSE_ERROR) return data
python
def read(self, page): """Send a READ command to retrieve data from the tag. The *page* argument specifies the offset in multiples of 4 bytes (i.e. page number 1 will return bytes 4 to 19). The data returned is a byte array of length 16 or None if the block is outside the readable memory range. Command execution errors raise :exc:`Type2TagCommandError`. """ log.debug("read pages {0} to {1}".format(page, page+3)) data = self.transceive("\x30"+chr(page % 256), timeout=0.005) if len(data) == 1 and data[0] & 0xFA == 0x00: log.debug("received nak response") self.target.sel_req = self.target.sdd_res[:] self._target = self.clf.sense(self.target) raise Type2TagCommandError( INVALID_PAGE_ERROR if self.target else nfc.tag.RECEIVE_ERROR) if len(data) != 16: log.debug("invalid response " + hexlify(data)) raise Type2TagCommandError(INVALID_RESPONSE_ERROR) return data
[ "def", "read", "(", "self", ",", "page", ")", ":", "log", ".", "debug", "(", "\"read pages {0} to {1}\"", ".", "format", "(", "page", ",", "page", "+", "3", ")", ")", "data", "=", "self", ".", "transceive", "(", "\"\\x30\"", "+", "chr", "(", "page", "%", "256", ")", ",", "timeout", "=", "0.005", ")", "if", "len", "(", "data", ")", "==", "1", "and", "data", "[", "0", "]", "&", "0xFA", "==", "0x00", ":", "log", ".", "debug", "(", "\"received nak response\"", ")", "self", ".", "target", ".", "sel_req", "=", "self", ".", "target", ".", "sdd_res", "[", ":", "]", "self", ".", "_target", "=", "self", ".", "clf", ".", "sense", "(", "self", ".", "target", ")", "raise", "Type2TagCommandError", "(", "INVALID_PAGE_ERROR", "if", "self", ".", "target", "else", "nfc", ".", "tag", ".", "RECEIVE_ERROR", ")", "if", "len", "(", "data", ")", "!=", "16", ":", "log", ".", "debug", "(", "\"invalid response \"", "+", "hexlify", "(", "data", ")", ")", "raise", "Type2TagCommandError", "(", "INVALID_RESPONSE_ERROR", ")", "return", "data" ]
Send a READ command to retrieve data from the tag. The *page* argument specifies the offset in multiples of 4 bytes (i.e. page number 1 will return bytes 4 to 19). The data returned is a byte array of length 16 or None if the block is outside the readable memory range. Command execution errors raise :exc:`Type2TagCommandError`.
[ "Send", "a", "READ", "command", "to", "retrieve", "data", "from", "the", "tag", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L468-L494
227,384
nfcpy/nfcpy
src/nfc/tag/tt2.py
Type2Tag.write
def write(self, page, data): """Send a WRITE command to store data on the tag. The *page* argument specifies the offset in multiples of 4 bytes. The *data* argument must be a string or bytearray of length 4. Command execution errors raise :exc:`Type2TagCommandError`. """ if len(data) != 4: raise ValueError("data must be a four byte string or array") log.debug("write {0} to page {1}".format(hexlify(data), page)) rsp = self.transceive("\xA2" + chr(page % 256) + data) if len(rsp) != 1: log.debug("invalid response " + hexlify(data)) raise Type2TagCommandError(INVALID_RESPONSE_ERROR) if rsp[0] != 0x0A: # NAK log.debug("invalid page, received nak") raise Type2TagCommandError(INVALID_PAGE_ERROR) return True
python
def write(self, page, data): """Send a WRITE command to store data on the tag. The *page* argument specifies the offset in multiples of 4 bytes. The *data* argument must be a string or bytearray of length 4. Command execution errors raise :exc:`Type2TagCommandError`. """ if len(data) != 4: raise ValueError("data must be a four byte string or array") log.debug("write {0} to page {1}".format(hexlify(data), page)) rsp = self.transceive("\xA2" + chr(page % 256) + data) if len(rsp) != 1: log.debug("invalid response " + hexlify(data)) raise Type2TagCommandError(INVALID_RESPONSE_ERROR) if rsp[0] != 0x0A: # NAK log.debug("invalid page, received nak") raise Type2TagCommandError(INVALID_PAGE_ERROR) return True
[ "def", "write", "(", "self", ",", "page", ",", "data", ")", ":", "if", "len", "(", "data", ")", "!=", "4", ":", "raise", "ValueError", "(", "\"data must be a four byte string or array\"", ")", "log", ".", "debug", "(", "\"write {0} to page {1}\"", ".", "format", "(", "hexlify", "(", "data", ")", ",", "page", ")", ")", "rsp", "=", "self", ".", "transceive", "(", "\"\\xA2\"", "+", "chr", "(", "page", "%", "256", ")", "+", "data", ")", "if", "len", "(", "rsp", ")", "!=", "1", ":", "log", ".", "debug", "(", "\"invalid response \"", "+", "hexlify", "(", "data", ")", ")", "raise", "Type2TagCommandError", "(", "INVALID_RESPONSE_ERROR", ")", "if", "rsp", "[", "0", "]", "!=", "0x0A", ":", "# NAK", "log", ".", "debug", "(", "\"invalid page, received nak\"", ")", "raise", "Type2TagCommandError", "(", "INVALID_PAGE_ERROR", ")", "return", "True" ]
Send a WRITE command to store data on the tag. The *page* argument specifies the offset in multiples of 4 bytes. The *data* argument must be a string or bytearray of length 4. Command execution errors raise :exc:`Type2TagCommandError`.
[ "Send", "a", "WRITE", "command", "to", "store", "data", "on", "the", "tag", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L496-L520
227,385
nfcpy/nfcpy
src/nfc/tag/tt2.py
Type2Tag.sector_select
def sector_select(self, sector): """Send a SECTOR_SELECT command to switch the 1K address sector. The command is only send to the tag if the *sector* number is different from the currently selected sector number (set to 0 when the tag instance is created). If the command was successful, the currently selected sector number is updated and further :meth:`read` and :meth:`write` commands will be relative to that sector. Command execution errors raise :exc:`Type2TagCommandError`. """ if sector != self._current_sector: log.debug("select sector {0} (pages {1} to {2})".format( sector, sector << 10, ((sector+1) << 8) - 1)) sector_select_1 = b'\xC2\xFF' sector_select_2 = pack('Bxxx', sector) rsp = self.transceive(sector_select_1) if len(rsp) == 1 and rsp[0] == 0x0A: try: # command is passively ack'd, i.e. there's no response # and we must make sure there's no retries attempted self.transceive(sector_select_2, timeout=0.001, retries=0) except Type2TagCommandError as error: assert int(error) == TIMEOUT_ERROR # passive ack else: log.debug("sector {0} does not exist".format(sector)) raise Type2TagCommandError(INVALID_SECTOR_ERROR) else: log.debug("sector select is not supported for this tag") raise Type2TagCommandError(INVALID_SECTOR_ERROR) log.debug("sector {0} is now selected".format(sector)) self._current_sector = sector return self._current_sector
python
def sector_select(self, sector): """Send a SECTOR_SELECT command to switch the 1K address sector. The command is only send to the tag if the *sector* number is different from the currently selected sector number (set to 0 when the tag instance is created). If the command was successful, the currently selected sector number is updated and further :meth:`read` and :meth:`write` commands will be relative to that sector. Command execution errors raise :exc:`Type2TagCommandError`. """ if sector != self._current_sector: log.debug("select sector {0} (pages {1} to {2})".format( sector, sector << 10, ((sector+1) << 8) - 1)) sector_select_1 = b'\xC2\xFF' sector_select_2 = pack('Bxxx', sector) rsp = self.transceive(sector_select_1) if len(rsp) == 1 and rsp[0] == 0x0A: try: # command is passively ack'd, i.e. there's no response # and we must make sure there's no retries attempted self.transceive(sector_select_2, timeout=0.001, retries=0) except Type2TagCommandError as error: assert int(error) == TIMEOUT_ERROR # passive ack else: log.debug("sector {0} does not exist".format(sector)) raise Type2TagCommandError(INVALID_SECTOR_ERROR) else: log.debug("sector select is not supported for this tag") raise Type2TagCommandError(INVALID_SECTOR_ERROR) log.debug("sector {0} is now selected".format(sector)) self._current_sector = sector return self._current_sector
[ "def", "sector_select", "(", "self", ",", "sector", ")", ":", "if", "sector", "!=", "self", ".", "_current_sector", ":", "log", ".", "debug", "(", "\"select sector {0} (pages {1} to {2})\"", ".", "format", "(", "sector", ",", "sector", "<<", "10", ",", "(", "(", "sector", "+", "1", ")", "<<", "8", ")", "-", "1", ")", ")", "sector_select_1", "=", "b'\\xC2\\xFF'", "sector_select_2", "=", "pack", "(", "'Bxxx'", ",", "sector", ")", "rsp", "=", "self", ".", "transceive", "(", "sector_select_1", ")", "if", "len", "(", "rsp", ")", "==", "1", "and", "rsp", "[", "0", "]", "==", "0x0A", ":", "try", ":", "# command is passively ack'd, i.e. there's no response", "# and we must make sure there's no retries attempted", "self", ".", "transceive", "(", "sector_select_2", ",", "timeout", "=", "0.001", ",", "retries", "=", "0", ")", "except", "Type2TagCommandError", "as", "error", ":", "assert", "int", "(", "error", ")", "==", "TIMEOUT_ERROR", "# passive ack", "else", ":", "log", ".", "debug", "(", "\"sector {0} does not exist\"", ".", "format", "(", "sector", ")", ")", "raise", "Type2TagCommandError", "(", "INVALID_SECTOR_ERROR", ")", "else", ":", "log", ".", "debug", "(", "\"sector select is not supported for this tag\"", ")", "raise", "Type2TagCommandError", "(", "INVALID_SECTOR_ERROR", ")", "log", ".", "debug", "(", "\"sector {0} is now selected\"", ".", "format", "(", "sector", ")", ")", "self", ".", "_current_sector", "=", "sector", "return", "self", ".", "_current_sector" ]
Send a SECTOR_SELECT command to switch the 1K address sector. The command is only send to the tag if the *sector* number is different from the currently selected sector number (set to 0 when the tag instance is created). If the command was successful, the currently selected sector number is updated and further :meth:`read` and :meth:`write` commands will be relative to that sector. Command execution errors raise :exc:`Type2TagCommandError`.
[ "Send", "a", "SECTOR_SELECT", "command", "to", "switch", "the", "1K", "address", "sector", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L522-L559
227,386
nfcpy/nfcpy
src/nfc/tag/tt2.py
Type2Tag.transceive
def transceive(self, data, timeout=0.1, retries=2): """Send a Type 2 Tag command and receive the response. :meth:`transceive` is a type 2 tag specific wrapper around the :meth:`nfc.ContactlessFrontend.exchange` method. It can be used to send custom commands as a sequence of *data* bytes to the tag and receive the response data bytes. If *timeout* seconds pass without a response, the operation is aborted and :exc:`~nfc.tag.TagCommandError` raised with the TIMEOUT_ERROR error code. Command execution errors raise :exc:`Type2TagCommandError`. """ log.debug(">> {0} ({1:f}s)".format(hexlify(data), timeout)) if not self.target: # Sometimes we have to (re)sense the target during # communication. If that failed (tag gone) then any # further attempt to transceive() is the same as # "unrecoverable timeout error". raise Type2TagCommandError(nfc.tag.TIMEOUT_ERROR) started = time.time() for retry in range(1 + retries): try: data = self.clf.exchange(data, timeout) break except nfc.clf.CommunicationError as error: reason = error.__class__.__name__ log.debug("%s after %d retries" % (reason, retry)) else: if type(error) is nfc.clf.TimeoutError: raise Type2TagCommandError(nfc.tag.TIMEOUT_ERROR) if type(error) is nfc.clf.TransmissionError: raise Type2TagCommandError(nfc.tag.RECEIVE_ERROR) if type(error) is nfc.clf.ProtocolError: raise Type2TagCommandError(nfc.tag.PROTOCOL_ERROR) raise RuntimeError("unexpected " + repr(error)) elapsed = time.time() - started log.debug("<< {0} ({1:f}s)".format(hexlify(data), elapsed)) return data
python
def transceive(self, data, timeout=0.1, retries=2): """Send a Type 2 Tag command and receive the response. :meth:`transceive` is a type 2 tag specific wrapper around the :meth:`nfc.ContactlessFrontend.exchange` method. It can be used to send custom commands as a sequence of *data* bytes to the tag and receive the response data bytes. If *timeout* seconds pass without a response, the operation is aborted and :exc:`~nfc.tag.TagCommandError` raised with the TIMEOUT_ERROR error code. Command execution errors raise :exc:`Type2TagCommandError`. """ log.debug(">> {0} ({1:f}s)".format(hexlify(data), timeout)) if not self.target: # Sometimes we have to (re)sense the target during # communication. If that failed (tag gone) then any # further attempt to transceive() is the same as # "unrecoverable timeout error". raise Type2TagCommandError(nfc.tag.TIMEOUT_ERROR) started = time.time() for retry in range(1 + retries): try: data = self.clf.exchange(data, timeout) break except nfc.clf.CommunicationError as error: reason = error.__class__.__name__ log.debug("%s after %d retries" % (reason, retry)) else: if type(error) is nfc.clf.TimeoutError: raise Type2TagCommandError(nfc.tag.TIMEOUT_ERROR) if type(error) is nfc.clf.TransmissionError: raise Type2TagCommandError(nfc.tag.RECEIVE_ERROR) if type(error) is nfc.clf.ProtocolError: raise Type2TagCommandError(nfc.tag.PROTOCOL_ERROR) raise RuntimeError("unexpected " + repr(error)) elapsed = time.time() - started log.debug("<< {0} ({1:f}s)".format(hexlify(data), elapsed)) return data
[ "def", "transceive", "(", "self", ",", "data", ",", "timeout", "=", "0.1", ",", "retries", "=", "2", ")", ":", "log", ".", "debug", "(", "\">> {0} ({1:f}s)\"", ".", "format", "(", "hexlify", "(", "data", ")", ",", "timeout", ")", ")", "if", "not", "self", ".", "target", ":", "# Sometimes we have to (re)sense the target during", "# communication. If that failed (tag gone) then any", "# further attempt to transceive() is the same as", "# \"unrecoverable timeout error\".", "raise", "Type2TagCommandError", "(", "nfc", ".", "tag", ".", "TIMEOUT_ERROR", ")", "started", "=", "time", ".", "time", "(", ")", "for", "retry", "in", "range", "(", "1", "+", "retries", ")", ":", "try", ":", "data", "=", "self", ".", "clf", ".", "exchange", "(", "data", ",", "timeout", ")", "break", "except", "nfc", ".", "clf", ".", "CommunicationError", "as", "error", ":", "reason", "=", "error", ".", "__class__", ".", "__name__", "log", ".", "debug", "(", "\"%s after %d retries\"", "%", "(", "reason", ",", "retry", ")", ")", "else", ":", "if", "type", "(", "error", ")", "is", "nfc", ".", "clf", ".", "TimeoutError", ":", "raise", "Type2TagCommandError", "(", "nfc", ".", "tag", ".", "TIMEOUT_ERROR", ")", "if", "type", "(", "error", ")", "is", "nfc", ".", "clf", ".", "TransmissionError", ":", "raise", "Type2TagCommandError", "(", "nfc", ".", "tag", ".", "RECEIVE_ERROR", ")", "if", "type", "(", "error", ")", "is", "nfc", ".", "clf", ".", "ProtocolError", ":", "raise", "Type2TagCommandError", "(", "nfc", ".", "tag", ".", "PROTOCOL_ERROR", ")", "raise", "RuntimeError", "(", "\"unexpected \"", "+", "repr", "(", "error", ")", ")", "elapsed", "=", "time", ".", "time", "(", ")", "-", "started", "log", ".", "debug", "(", "\"<< {0} ({1:f}s)\"", ".", "format", "(", "hexlify", "(", "data", ")", ",", "elapsed", ")", ")", "return", "data" ]
Send a Type 2 Tag command and receive the response. :meth:`transceive` is a type 2 tag specific wrapper around the :meth:`nfc.ContactlessFrontend.exchange` method. It can be used to send custom commands as a sequence of *data* bytes to the tag and receive the response data bytes. If *timeout* seconds pass without a response, the operation is aborted and :exc:`~nfc.tag.TagCommandError` raised with the TIMEOUT_ERROR error code. Command execution errors raise :exc:`Type2TagCommandError`.
[ "Send", "a", "Type", "2", "Tag", "command", "and", "receive", "the", "response", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L561-L603
227,387
nfcpy/nfcpy
src/nfc/llcp/socket.py
Socket.setsockopt
def setsockopt(self, option, value): """Set the value of the given socket option and return the current value which may have been corrected if it was out of bounds.""" return self.llc.setsockopt(self._tco, option, value)
python
def setsockopt(self, option, value): """Set the value of the given socket option and return the current value which may have been corrected if it was out of bounds.""" return self.llc.setsockopt(self._tco, option, value)
[ "def", "setsockopt", "(", "self", ",", "option", ",", "value", ")", ":", "return", "self", ".", "llc", ".", "setsockopt", "(", "self", ".", "_tco", ",", "option", ",", "value", ")" ]
Set the value of the given socket option and return the current value which may have been corrected if it was out of bounds.
[ "Set", "the", "value", "of", "the", "given", "socket", "option", "and", "return", "the", "current", "value", "which", "may", "have", "been", "corrected", "if", "it", "was", "out", "of", "bounds", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/llcp/socket.py#L64-L68
227,388
nfcpy/nfcpy
src/nfc/llcp/socket.py
Socket.accept
def accept(self): """Accept a connection. The socket must be bound to an address and listening for connections. The return value is a new socket object usable to send and receive data on the connection.""" socket = Socket(self._llc, None) socket._tco = self.llc.accept(self._tco) return socket
python
def accept(self): """Accept a connection. The socket must be bound to an address and listening for connections. The return value is a new socket object usable to send and receive data on the connection.""" socket = Socket(self._llc, None) socket._tco = self.llc.accept(self._tco) return socket
[ "def", "accept", "(", "self", ")", ":", "socket", "=", "Socket", "(", "self", ".", "_llc", ",", "None", ")", "socket", ".", "_tco", "=", "self", ".", "llc", ".", "accept", "(", "self", ".", "_tco", ")", "return", "socket" ]
Accept a connection. The socket must be bound to an address and listening for connections. The return value is a new socket object usable to send and receive data on the connection.
[ "Accept", "a", "connection", ".", "The", "socket", "must", "be", "bound", "to", "an", "address", "and", "listening", "for", "connections", ".", "The", "return", "value", "is", "a", "new", "socket", "object", "usable", "to", "send", "and", "receive", "data", "on", "the", "connection", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/llcp/socket.py#L102-L109
227,389
nfcpy/nfcpy
src/nfc/llcp/socket.py
Socket.send
def send(self, data, flags=0): """Send data to the socket. The socket must be connected to a remote socket. Returns a boolean value that indicates success or failure. A false value is typically an indication that the socket or connection was closed. """ return self.llc.send(self._tco, data, flags)
python
def send(self, data, flags=0): """Send data to the socket. The socket must be connected to a remote socket. Returns a boolean value that indicates success or failure. A false value is typically an indication that the socket or connection was closed. """ return self.llc.send(self._tco, data, flags)
[ "def", "send", "(", "self", ",", "data", ",", "flags", "=", "0", ")", ":", "return", "self", ".", "llc", ".", "send", "(", "self", ".", "_tco", ",", "data", ",", "flags", ")" ]
Send data to the socket. The socket must be connected to a remote socket. Returns a boolean value that indicates success or failure. A false value is typically an indication that the socket or connection was closed.
[ "Send", "data", "to", "the", "socket", ".", "The", "socket", "must", "be", "connected", "to", "a", "remote", "socket", ".", "Returns", "a", "boolean", "value", "that", "indicates", "success", "or", "failure", ".", "A", "false", "value", "is", "typically", "an", "indication", "that", "the", "socket", "or", "connection", "was", "closed", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/llcp/socket.py#L111-L118
227,390
nfcpy/nfcpy
src/nfc/llcp/socket.py
Socket.sendto
def sendto(self, data, addr, flags=0): """Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by addr. Returns a boolean value that indicates success or failure. Failure to send is generally an indication that the socket was closed.""" return self.llc.sendto(self._tco, data, addr, flags)
python
def sendto(self, data, addr, flags=0): """Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by addr. Returns a boolean value that indicates success or failure. Failure to send is generally an indication that the socket was closed.""" return self.llc.sendto(self._tco, data, addr, flags)
[ "def", "sendto", "(", "self", ",", "data", ",", "addr", ",", "flags", "=", "0", ")", ":", "return", "self", ".", "llc", ".", "sendto", "(", "self", ".", "_tco", ",", "data", ",", "addr", ",", "flags", ")" ]
Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by addr. Returns a boolean value that indicates success or failure. Failure to send is generally an indication that the socket was closed.
[ "Send", "data", "to", "the", "socket", ".", "The", "socket", "should", "not", "be", "connected", "to", "a", "remote", "socket", "since", "the", "destination", "socket", "is", "specified", "by", "addr", ".", "Returns", "a", "boolean", "value", "that", "indicates", "success", "or", "failure", ".", "Failure", "to", "send", "is", "generally", "an", "indication", "that", "the", "socket", "was", "closed", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/llcp/socket.py#L120-L126
227,391
nfcpy/nfcpy
src/nfc/ndef/bt_record.py
BluetoothConfigRecord.simple_pairing_hash
def simple_pairing_hash(self): """Simple Pairing Hash C. Received and transmitted as EIR type 0x0E. Set to None if not received or not to be transmitted. Raises nfc.ndef.DecodeError if the received value or nfc.ndef.EncodeError if the assigned value is not a sequence of 16 octets.""" try: if len(self.eir[0x0E]) != 16: raise DecodeError("wrong length of simple pairing hash") return bytearray(self.eir[0x0E]) except KeyError: return None
python
def simple_pairing_hash(self): """Simple Pairing Hash C. Received and transmitted as EIR type 0x0E. Set to None if not received or not to be transmitted. Raises nfc.ndef.DecodeError if the received value or nfc.ndef.EncodeError if the assigned value is not a sequence of 16 octets.""" try: if len(self.eir[0x0E]) != 16: raise DecodeError("wrong length of simple pairing hash") return bytearray(self.eir[0x0E]) except KeyError: return None
[ "def", "simple_pairing_hash", "(", "self", ")", ":", "try", ":", "if", "len", "(", "self", ".", "eir", "[", "0x0E", "]", ")", "!=", "16", ":", "raise", "DecodeError", "(", "\"wrong length of simple pairing hash\"", ")", "return", "bytearray", "(", "self", ".", "eir", "[", "0x0E", "]", ")", "except", "KeyError", ":", "return", "None" ]
Simple Pairing Hash C. Received and transmitted as EIR type 0x0E. Set to None if not received or not to be transmitted. Raises nfc.ndef.DecodeError if the received value or nfc.ndef.EncodeError if the assigned value is not a sequence of 16 octets.
[ "Simple", "Pairing", "Hash", "C", ".", "Received", "and", "transmitted", "as", "EIR", "type", "0x0E", ".", "Set", "to", "None", "if", "not", "received", "or", "not", "to", "be", "transmitted", ".", "Raises", "nfc", ".", "ndef", ".", "DecodeError", "if", "the", "received", "value", "or", "nfc", ".", "ndef", ".", "EncodeError", "if", "the", "assigned", "value", "is", "not", "a", "sequence", "of", "16", "octets", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/bt_record.py#L101-L112
227,392
nfcpy/nfcpy
src/nfc/ndef/bt_record.py
BluetoothConfigRecord.simple_pairing_rand
def simple_pairing_rand(self): """Simple Pairing Randomizer R. Received and transmitted as EIR type 0x0F. Set to None if not received or not to be transmitted. Raises nfc.ndef.DecodeError if the received value or nfc.ndef.EncodeError if the assigned value is not a sequence of 16 octets.""" try: if len(self.eir[0x0F]) != 16: raise DecodeError("wrong length of simple pairing hash") return bytearray(self.eir[0x0F]) except KeyError: return None
python
def simple_pairing_rand(self): """Simple Pairing Randomizer R. Received and transmitted as EIR type 0x0F. Set to None if not received or not to be transmitted. Raises nfc.ndef.DecodeError if the received value or nfc.ndef.EncodeError if the assigned value is not a sequence of 16 octets.""" try: if len(self.eir[0x0F]) != 16: raise DecodeError("wrong length of simple pairing hash") return bytearray(self.eir[0x0F]) except KeyError: return None
[ "def", "simple_pairing_rand", "(", "self", ")", ":", "try", ":", "if", "len", "(", "self", ".", "eir", "[", "0x0F", "]", ")", "!=", "16", ":", "raise", "DecodeError", "(", "\"wrong length of simple pairing hash\"", ")", "return", "bytearray", "(", "self", ".", "eir", "[", "0x0F", "]", ")", "except", "KeyError", ":", "return", "None" ]
Simple Pairing Randomizer R. Received and transmitted as EIR type 0x0F. Set to None if not received or not to be transmitted. Raises nfc.ndef.DecodeError if the received value or nfc.ndef.EncodeError if the assigned value is not a sequence of 16 octets.
[ "Simple", "Pairing", "Randomizer", "R", ".", "Received", "and", "transmitted", "as", "EIR", "type", "0x0F", ".", "Set", "to", "None", "if", "not", "received", "or", "not", "to", "be", "transmitted", ".", "Raises", "nfc", ".", "ndef", ".", "DecodeError", "if", "the", "received", "value", "or", "nfc", ".", "ndef", ".", "EncodeError", "if", "the", "assigned", "value", "is", "not", "a", "sequence", "of", "16", "octets", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/bt_record.py#L124-L135
227,393
nfcpy/nfcpy
src/nfc/ndef/handover.py
HandoverRequestMessage.add_carrier
def add_carrier(self, carrier_record, power_state, aux_data_records=None): """Add a new carrier to the handover request message. :param carrier_record: a record providing carrier information :param power_state: a string describing the carrier power state :param aux_data_records: list of auxiliary data records :type carrier_record: :class:`nfc.ndef.Record` :type power_state: :class:`str` :type aux_data_records: :class:`~nfc.ndef.record.RecordList` >>> hr = nfc.ndef.HandoverRequestMessage(version="1.2") >>> hr.add_carrier(some_carrier_record, "active") """ carrier = Carrier(carrier_record, power_state) if aux_data_records is not None: for aux in RecordList(aux_data_records): carrier.auxiliary_data_records.append(aux) self.carriers.append(carrier)
python
def add_carrier(self, carrier_record, power_state, aux_data_records=None): """Add a new carrier to the handover request message. :param carrier_record: a record providing carrier information :param power_state: a string describing the carrier power state :param aux_data_records: list of auxiliary data records :type carrier_record: :class:`nfc.ndef.Record` :type power_state: :class:`str` :type aux_data_records: :class:`~nfc.ndef.record.RecordList` >>> hr = nfc.ndef.HandoverRequestMessage(version="1.2") >>> hr.add_carrier(some_carrier_record, "active") """ carrier = Carrier(carrier_record, power_state) if aux_data_records is not None: for aux in RecordList(aux_data_records): carrier.auxiliary_data_records.append(aux) self.carriers.append(carrier)
[ "def", "add_carrier", "(", "self", ",", "carrier_record", ",", "power_state", ",", "aux_data_records", "=", "None", ")", ":", "carrier", "=", "Carrier", "(", "carrier_record", ",", "power_state", ")", "if", "aux_data_records", "is", "not", "None", ":", "for", "aux", "in", "RecordList", "(", "aux_data_records", ")", ":", "carrier", ".", "auxiliary_data_records", ".", "append", "(", "aux", ")", "self", ".", "carriers", ".", "append", "(", "carrier", ")" ]
Add a new carrier to the handover request message. :param carrier_record: a record providing carrier information :param power_state: a string describing the carrier power state :param aux_data_records: list of auxiliary data records :type carrier_record: :class:`nfc.ndef.Record` :type power_state: :class:`str` :type aux_data_records: :class:`~nfc.ndef.record.RecordList` >>> hr = nfc.ndef.HandoverRequestMessage(version="1.2") >>> hr.add_carrier(some_carrier_record, "active")
[ "Add", "a", "new", "carrier", "to", "the", "handover", "request", "message", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/handover.py#L172-L189
227,394
nfcpy/nfcpy
src/nfc/ndef/handover.py
HandoverSelectMessage.pretty
def pretty(self, indent=0): """Returns a string with a formatted representation that might be considered pretty-printable.""" indent = indent * ' ' lines = list() version_string = "{v.major}.{v.minor}".format(v=self.version) lines.append(("handover version", version_string)) if self.error.reason: lines.append(("error reason", self.error.reason)) lines.append(("error value", self.error.value)) for index, carrier in enumerate(self.carriers): lines.append(("carrier {0}:".format(index+1),)) lines.append((indent + "power state", carrier.power_state)) if carrier.record.type == "urn:nfc:wkt:Hc": carrier_type = carrier.record.carrier_type carrier_data = carrier.record.carrier_data lines.append((indent + "carrier type", carrier_type)) lines.append((indent + "carrier data", repr(carrier_data))) else: if carrier.type == "application/vnd.bluetooth.ep.oob": carrier_record = BluetoothConfigRecord(carrier.record) elif carrier.type == "application/vnd.wfa.wsc": carrier_record = WifiConfigRecord(carrier.record) else: carrier_record = carrier.record lines.append((indent + "carrier type", carrier.type)) pretty_lines = carrier_record.pretty(2).split('\n') lines.extend([tuple(l.split(' = ')) for l in pretty_lines if not l.strip().startswith("identifier")]) for record in carrier.auxiliary_data_records: lines.append((indent + "auxiliary data",)) lines.append((2*indent + "record type", record.type)) lines.append((2*indent + "record data", repr(record.data))) lwidth = max([len(line[0]) for line in lines]) lines = [(line[0].ljust(lwidth),) + line[1:] for line in lines] lines = [" = ".join(line) for line in lines] return ("\n").join([indent + line for line in lines])
python
def pretty(self, indent=0): """Returns a string with a formatted representation that might be considered pretty-printable.""" indent = indent * ' ' lines = list() version_string = "{v.major}.{v.minor}".format(v=self.version) lines.append(("handover version", version_string)) if self.error.reason: lines.append(("error reason", self.error.reason)) lines.append(("error value", self.error.value)) for index, carrier in enumerate(self.carriers): lines.append(("carrier {0}:".format(index+1),)) lines.append((indent + "power state", carrier.power_state)) if carrier.record.type == "urn:nfc:wkt:Hc": carrier_type = carrier.record.carrier_type carrier_data = carrier.record.carrier_data lines.append((indent + "carrier type", carrier_type)) lines.append((indent + "carrier data", repr(carrier_data))) else: if carrier.type == "application/vnd.bluetooth.ep.oob": carrier_record = BluetoothConfigRecord(carrier.record) elif carrier.type == "application/vnd.wfa.wsc": carrier_record = WifiConfigRecord(carrier.record) else: carrier_record = carrier.record lines.append((indent + "carrier type", carrier.type)) pretty_lines = carrier_record.pretty(2).split('\n') lines.extend([tuple(l.split(' = ')) for l in pretty_lines if not l.strip().startswith("identifier")]) for record in carrier.auxiliary_data_records: lines.append((indent + "auxiliary data",)) lines.append((2*indent + "record type", record.type)) lines.append((2*indent + "record data", repr(record.data))) lwidth = max([len(line[0]) for line in lines]) lines = [(line[0].ljust(lwidth),) + line[1:] for line in lines] lines = [" = ".join(line) for line in lines] return ("\n").join([indent + line for line in lines])
[ "def", "pretty", "(", "self", ",", "indent", "=", "0", ")", ":", "indent", "=", "indent", "*", "' '", "lines", "=", "list", "(", ")", "version_string", "=", "\"{v.major}.{v.minor}\"", ".", "format", "(", "v", "=", "self", ".", "version", ")", "lines", ".", "append", "(", "(", "\"handover version\"", ",", "version_string", ")", ")", "if", "self", ".", "error", ".", "reason", ":", "lines", ".", "append", "(", "(", "\"error reason\"", ",", "self", ".", "error", ".", "reason", ")", ")", "lines", ".", "append", "(", "(", "\"error value\"", ",", "self", ".", "error", ".", "value", ")", ")", "for", "index", ",", "carrier", "in", "enumerate", "(", "self", ".", "carriers", ")", ":", "lines", ".", "append", "(", "(", "\"carrier {0}:\"", ".", "format", "(", "index", "+", "1", ")", ",", ")", ")", "lines", ".", "append", "(", "(", "indent", "+", "\"power state\"", ",", "carrier", ".", "power_state", ")", ")", "if", "carrier", ".", "record", ".", "type", "==", "\"urn:nfc:wkt:Hc\"", ":", "carrier_type", "=", "carrier", ".", "record", ".", "carrier_type", "carrier_data", "=", "carrier", ".", "record", ".", "carrier_data", "lines", ".", "append", "(", "(", "indent", "+", "\"carrier type\"", ",", "carrier_type", ")", ")", "lines", ".", "append", "(", "(", "indent", "+", "\"carrier data\"", ",", "repr", "(", "carrier_data", ")", ")", ")", "else", ":", "if", "carrier", ".", "type", "==", "\"application/vnd.bluetooth.ep.oob\"", ":", "carrier_record", "=", "BluetoothConfigRecord", "(", "carrier", ".", "record", ")", "elif", "carrier", ".", "type", "==", "\"application/vnd.wfa.wsc\"", ":", "carrier_record", "=", "WifiConfigRecord", "(", "carrier", ".", "record", ")", "else", ":", "carrier_record", "=", "carrier", ".", "record", "lines", ".", "append", "(", "(", "indent", "+", "\"carrier type\"", ",", "carrier", ".", "type", ")", ")", "pretty_lines", "=", "carrier_record", ".", "pretty", "(", "2", ")", ".", "split", "(", "'\\n'", ")", "lines", ".", "extend", "(", "[", "tuple", "(", "l", ".", "split", "(", "' = '", ")", ")", "for", "l", "in", "pretty_lines", "if", "not", "l", ".", "strip", "(", ")", ".", "startswith", "(", "\"identifier\"", ")", "]", ")", "for", "record", "in", "carrier", ".", "auxiliary_data_records", ":", "lines", ".", "append", "(", "(", "indent", "+", "\"auxiliary data\"", ",", ")", ")", "lines", ".", "append", "(", "(", "2", "*", "indent", "+", "\"record type\"", ",", "record", ".", "type", ")", ")", "lines", ".", "append", "(", "(", "2", "*", "indent", "+", "\"record data\"", ",", "repr", "(", "record", ".", "data", ")", ")", ")", "lwidth", "=", "max", "(", "[", "len", "(", "line", "[", "0", "]", ")", "for", "line", "in", "lines", "]", ")", "lines", "=", "[", "(", "line", "[", "0", "]", ".", "ljust", "(", "lwidth", ")", ",", ")", "+", "line", "[", "1", ":", "]", "for", "line", "in", "lines", "]", "lines", "=", "[", "\" = \"", ".", "join", "(", "line", ")", "for", "line", "in", "lines", "]", "return", "(", "\"\\n\"", ")", ".", "join", "(", "[", "indent", "+", "line", "for", "line", "in", "lines", "]", ")" ]
Returns a string with a formatted representation that might be considered pretty-printable.
[ "Returns", "a", "string", "with", "a", "formatted", "representation", "that", "might", "be", "considered", "pretty", "-", "printable", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/handover.py#L431-L468
227,395
nfcpy/nfcpy
src/nfc/dep.py
Target.activate
def activate(self, timeout=None, **options): """Activate DEP communication as a target.""" if timeout is None: timeout = 1.0 gbt = options.get('gbt', '')[0:47] lrt = min(max(0, options.get('lrt', 3)), 3) rwt = min(max(0, options.get('rwt', 8)), 14) pp = (lrt << 4) | (bool(gbt) << 1) | int(bool(self.nad)) nfcid3t = bytearray.fromhex("01FE") + os.urandom(6) + "ST" atr_res = ATR_RES(nfcid3t, 0, 0, 0, rwt, pp, gbt) atr_res = atr_res.encode() target = nfc.clf.LocalTarget(atr_res=atr_res) target.sens_res = bytearray.fromhex("0101") target.sdd_res = bytearray.fromhex("08") + os.urandom(3) target.sel_res = bytearray.fromhex("40") target.sensf_res = bytearray.fromhex("01") + nfcid3t[0:8] target.sensf_res += bytearray.fromhex("00000000 00000000 FFFF") target = self.clf.listen(target, timeout) if target and target.atr_req and target.dep_req: log.debug("activated as " + str(target)) atr_req = ATR_REQ.decode(target.atr_req) self.lrt = lrt self.gbt = gbt self.gbi = atr_req.gb self.miu = atr_req.lr - 3 self.rwt = 4096/13.56E6 * pow(2, rwt) self.did = atr_req.did if atr_req.did > 0 else None self.acm = not (target.sens_res or target.sensf_res) self.cmd = chr(len(target.dep_req)+1) + target.dep_req if target.brty == "106A": self.cmd = b"\xF0" + self.cmd self.target = target self.pcnt.rcvd["ATR"] += 1 self.pcnt.sent["ATR"] += 1 log.info("running as " + str(self)) return self.gbi
python
def activate(self, timeout=None, **options): """Activate DEP communication as a target.""" if timeout is None: timeout = 1.0 gbt = options.get('gbt', '')[0:47] lrt = min(max(0, options.get('lrt', 3)), 3) rwt = min(max(0, options.get('rwt', 8)), 14) pp = (lrt << 4) | (bool(gbt) << 1) | int(bool(self.nad)) nfcid3t = bytearray.fromhex("01FE") + os.urandom(6) + "ST" atr_res = ATR_RES(nfcid3t, 0, 0, 0, rwt, pp, gbt) atr_res = atr_res.encode() target = nfc.clf.LocalTarget(atr_res=atr_res) target.sens_res = bytearray.fromhex("0101") target.sdd_res = bytearray.fromhex("08") + os.urandom(3) target.sel_res = bytearray.fromhex("40") target.sensf_res = bytearray.fromhex("01") + nfcid3t[0:8] target.sensf_res += bytearray.fromhex("00000000 00000000 FFFF") target = self.clf.listen(target, timeout) if target and target.atr_req and target.dep_req: log.debug("activated as " + str(target)) atr_req = ATR_REQ.decode(target.atr_req) self.lrt = lrt self.gbt = gbt self.gbi = atr_req.gb self.miu = atr_req.lr - 3 self.rwt = 4096/13.56E6 * pow(2, rwt) self.did = atr_req.did if atr_req.did > 0 else None self.acm = not (target.sens_res or target.sensf_res) self.cmd = chr(len(target.dep_req)+1) + target.dep_req if target.brty == "106A": self.cmd = b"\xF0" + self.cmd self.target = target self.pcnt.rcvd["ATR"] += 1 self.pcnt.sent["ATR"] += 1 log.info("running as " + str(self)) return self.gbi
[ "def", "activate", "(", "self", ",", "timeout", "=", "None", ",", "*", "*", "options", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "1.0", "gbt", "=", "options", ".", "get", "(", "'gbt'", ",", "''", ")", "[", "0", ":", "47", "]", "lrt", "=", "min", "(", "max", "(", "0", ",", "options", ".", "get", "(", "'lrt'", ",", "3", ")", ")", ",", "3", ")", "rwt", "=", "min", "(", "max", "(", "0", ",", "options", ".", "get", "(", "'rwt'", ",", "8", ")", ")", ",", "14", ")", "pp", "=", "(", "lrt", "<<", "4", ")", "|", "(", "bool", "(", "gbt", ")", "<<", "1", ")", "|", "int", "(", "bool", "(", "self", ".", "nad", ")", ")", "nfcid3t", "=", "bytearray", ".", "fromhex", "(", "\"01FE\"", ")", "+", "os", ".", "urandom", "(", "6", ")", "+", "\"ST\"", "atr_res", "=", "ATR_RES", "(", "nfcid3t", ",", "0", ",", "0", ",", "0", ",", "rwt", ",", "pp", ",", "gbt", ")", "atr_res", "=", "atr_res", ".", "encode", "(", ")", "target", "=", "nfc", ".", "clf", ".", "LocalTarget", "(", "atr_res", "=", "atr_res", ")", "target", ".", "sens_res", "=", "bytearray", ".", "fromhex", "(", "\"0101\"", ")", "target", ".", "sdd_res", "=", "bytearray", ".", "fromhex", "(", "\"08\"", ")", "+", "os", ".", "urandom", "(", "3", ")", "target", ".", "sel_res", "=", "bytearray", ".", "fromhex", "(", "\"40\"", ")", "target", ".", "sensf_res", "=", "bytearray", ".", "fromhex", "(", "\"01\"", ")", "+", "nfcid3t", "[", "0", ":", "8", "]", "target", ".", "sensf_res", "+=", "bytearray", ".", "fromhex", "(", "\"00000000 00000000 FFFF\"", ")", "target", "=", "self", ".", "clf", ".", "listen", "(", "target", ",", "timeout", ")", "if", "target", "and", "target", ".", "atr_req", "and", "target", ".", "dep_req", ":", "log", ".", "debug", "(", "\"activated as \"", "+", "str", "(", "target", ")", ")", "atr_req", "=", "ATR_REQ", ".", "decode", "(", "target", ".", "atr_req", ")", "self", ".", "lrt", "=", "lrt", "self", ".", "gbt", "=", "gbt", "self", ".", "gbi", "=", "atr_req", ".", "gb", "self", ".", "miu", "=", "atr_req", ".", "lr", "-", "3", "self", ".", "rwt", "=", "4096", "/", "13.56E6", "*", "pow", "(", "2", ",", "rwt", ")", "self", ".", "did", "=", "atr_req", ".", "did", "if", "atr_req", ".", "did", ">", "0", "else", "None", "self", ".", "acm", "=", "not", "(", "target", ".", "sens_res", "or", "target", ".", "sensf_res", ")", "self", ".", "cmd", "=", "chr", "(", "len", "(", "target", ".", "dep_req", ")", "+", "1", ")", "+", "target", ".", "dep_req", "if", "target", ".", "brty", "==", "\"106A\"", ":", "self", ".", "cmd", "=", "b\"\\xF0\"", "+", "self", ".", "cmd", "self", ".", "target", "=", "target", "self", ".", "pcnt", ".", "rcvd", "[", "\"ATR\"", "]", "+=", "1", "self", ".", "pcnt", ".", "sent", "[", "\"ATR\"", "]", "+=", "1", "log", ".", "info", "(", "\"running as \"", "+", "str", "(", "self", ")", ")", "return", "self", ".", "gbi" ]
Activate DEP communication as a target.
[ "Activate", "DEP", "communication", "as", "a", "target", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/dep.py#L417-L460
227,396
nfcpy/nfcpy
src/nfc/ndef/message.py
Message.pretty
def pretty(self): """Returns a message representation that might be considered pretty-printable.""" lines = list() for index, record in enumerate(self._records): lines.append(("record {0}".format(index+1),)) lines.append((" type", repr(record.type))) lines.append((" name", repr(record.name))) lines.append((" data", repr(record.data))) lwidth = max([len(line[0]) for line in lines]) lines = [(line[0].ljust(lwidth),) + line[1:] for line in lines] lines = [" = ".join(line) for line in lines] return ("\n").join([line for line in lines])
python
def pretty(self): """Returns a message representation that might be considered pretty-printable.""" lines = list() for index, record in enumerate(self._records): lines.append(("record {0}".format(index+1),)) lines.append((" type", repr(record.type))) lines.append((" name", repr(record.name))) lines.append((" data", repr(record.data))) lwidth = max([len(line[0]) for line in lines]) lines = [(line[0].ljust(lwidth),) + line[1:] for line in lines] lines = [" = ".join(line) for line in lines] return ("\n").join([line for line in lines])
[ "def", "pretty", "(", "self", ")", ":", "lines", "=", "list", "(", ")", "for", "index", ",", "record", "in", "enumerate", "(", "self", ".", "_records", ")", ":", "lines", ".", "append", "(", "(", "\"record {0}\"", ".", "format", "(", "index", "+", "1", ")", ",", ")", ")", "lines", ".", "append", "(", "(", "\" type\"", ",", "repr", "(", "record", ".", "type", ")", ")", ")", "lines", ".", "append", "(", "(", "\" name\"", ",", "repr", "(", "record", ".", "name", ")", ")", ")", "lines", ".", "append", "(", "(", "\" data\"", ",", "repr", "(", "record", ".", "data", ")", ")", ")", "lwidth", "=", "max", "(", "[", "len", "(", "line", "[", "0", "]", ")", "for", "line", "in", "lines", "]", ")", "lines", "=", "[", "(", "line", "[", "0", "]", ".", "ljust", "(", "lwidth", ")", ",", ")", "+", "line", "[", "1", ":", "]", "for", "line", "in", "lines", "]", "lines", "=", "[", "\" = \"", ".", "join", "(", "line", ")", "for", "line", "in", "lines", "]", "return", "(", "\"\\n\"", ")", ".", "join", "(", "[", "line", "for", "line", "in", "lines", "]", ")" ]
Returns a message representation that might be considered pretty-printable.
[ "Returns", "a", "message", "representation", "that", "might", "be", "considered", "pretty", "-", "printable", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/message.py#L161-L173
227,397
nfcpy/nfcpy
src/nfc/tag/tt1_broadcom.py
Topaz.format
def format(self, version=None, wipe=None): """Format a Topaz tag for NDEF use. The implementation of :meth:`nfc.tag.Tag.format` for a Topaz tag creates a capability container and an NDEF TLV with length zero. Data bytes of the NDEF data area are left untouched unless the wipe argument is set. """ return super(Topaz, self).format(version, wipe)
python
def format(self, version=None, wipe=None): """Format a Topaz tag for NDEF use. The implementation of :meth:`nfc.tag.Tag.format` for a Topaz tag creates a capability container and an NDEF TLV with length zero. Data bytes of the NDEF data area are left untouched unless the wipe argument is set. """ return super(Topaz, self).format(version, wipe)
[ "def", "format", "(", "self", ",", "version", "=", "None", ",", "wipe", "=", "None", ")", ":", "return", "super", "(", "Topaz", ",", "self", ")", ".", "format", "(", "version", ",", "wipe", ")" ]
Format a Topaz tag for NDEF use. The implementation of :meth:`nfc.tag.Tag.format` for a Topaz tag creates a capability container and an NDEF TLV with length zero. Data bytes of the NDEF data area are left untouched unless the wipe argument is set.
[ "Format", "a", "Topaz", "tag", "for", "NDEF", "use", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt1_broadcom.py#L40-L49
227,398
nfcpy/nfcpy
src/nfc/tag/tt1_broadcom.py
Topaz512.format
def format(self, version=None, wipe=None): """Format a Topaz-512 tag for NDEF use. The implementation of :meth:`nfc.tag.Tag.format` for a Topaz-512 tag creates a capability container, a Lock Control and a Memory Control TLV, and an NDEF TLV with length zero. Data bytes of the NDEF data area are left untouched unless the wipe argument is set. """ return super(Topaz512, self).format(version, wipe)
python
def format(self, version=None, wipe=None): """Format a Topaz-512 tag for NDEF use. The implementation of :meth:`nfc.tag.Tag.format` for a Topaz-512 tag creates a capability container, a Lock Control and a Memory Control TLV, and an NDEF TLV with length zero. Data bytes of the NDEF data area are left untouched unless the wipe argument is set. """ return super(Topaz512, self).format(version, wipe)
[ "def", "format", "(", "self", ",", "version", "=", "None", ",", "wipe", "=", "None", ")", ":", "return", "super", "(", "Topaz512", ",", "self", ")", ".", "format", "(", "version", ",", "wipe", ")" ]
Format a Topaz-512 tag for NDEF use. The implementation of :meth:`nfc.tag.Tag.format` for a Topaz-512 tag creates a capability container, a Lock Control and a Memory Control TLV, and an NDEF TLV with length zero. Data bytes of the NDEF data area are left untouched unless the wipe argument is set.
[ "Format", "a", "Topaz", "-", "512", "tag", "for", "NDEF", "use", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt1_broadcom.py#L100-L110
227,399
nfcpy/nfcpy
src/nfc/tag/tt1.py
Type1Tag.read_all
def read_all(self): """Returns the 2 byte Header ROM and all 120 byte static memory. """ log.debug("read all static memory") cmd = "\x00\x00\x00" + self.uid return self.transceive(cmd)
python
def read_all(self): """Returns the 2 byte Header ROM and all 120 byte static memory. """ log.debug("read all static memory") cmd = "\x00\x00\x00" + self.uid return self.transceive(cmd)
[ "def", "read_all", "(", "self", ")", ":", "log", ".", "debug", "(", "\"read all static memory\"", ")", "cmd", "=", "\"\\x00\\x00\\x00\"", "+", "self", ".", "uid", "return", "self", ".", "transceive", "(", "cmd", ")" ]
Returns the 2 byte Header ROM and all 120 byte static memory.
[ "Returns", "the", "2", "byte", "Header", "ROM", "and", "all", "120", "byte", "static", "memory", "." ]
6649146d1afdd5e82b2b6b1ea00aa58d50785117
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt1.py#L387-L392