desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'initialize the modem configuration with settings needed to process commands and send/receive SMS.'
def set_modem_config(self):
self.command('ATE0', raise_errors=False) self.command('AT+CMEE=1', raise_errors=False) self.command('AT+WIND=0', raise_errors=False) self.command('AT+CSMS=1', raise_errors=False) self.command(self.smshandler.get_mode_cmd()) self.command('AT+CNMI=2,2,0,0,0', raise_errors=False)
'Initializes the modem. Must be called after init and connect, but before doing anything that expects the modem to be ready.'
def boot(self, reboot=False):
self._log('Booting') if reboot: self.connect(reconnect=True) self.command('AT+CFUN=1') else: self.connect() self.set_modem_config() try: self._fetch_stored_messages() except errors.GsmError: pass
'Forces a reconnect to the serial port and then a full modem reset to factory and reconnect to GSM network. SLOW.'
def reboot(self):
self.boot(reboot=True)
'Write a string to the modem.'
def _write(self, str):
self._log(repr(str), 'write') try: self.device.write(str) except OSError as err: raise errors.GsmWriteError
'Parse a list of lines (the output of GsmModem._wait), to extract any incoming SMS and append them to GsmModem.incoming_queue. Returns the same lines with the incoming SMS removed. Other unsolicited data may remain, which must be cropped separately.'
def _parse_incoming_sms(self, lines):
output_lines = [] n = 0 while (n < len(lines)): if (lines[n][0:5] != '+CMT:'): output_lines.append(lines[n]) n += 1 continue msg_line = lines[(n + 1)].strip() try: self.command('AT+CNMA') except errors.GsmError: pass...
'Issue a single AT command to the modem, and return the sanitized response. Sanitization removes status notifications, command echo, and incoming messages, (hopefully) leaving only the actual response from the command. If Error 515 (init or command in progress) is returned, the command is automatically retried up to _G...
def command(self, cmd, read_term=None, read_timeout=None, write_term='\r', raise_errors=True):
retries = 0 while (retries < self.max_retries): try: with self.modem_lock: self._write((cmd + write_term)) lines = self.device.read_lines(read_term=read_term, read_timeout=read_timeout) break except errors.GsmError as err: if (g...
'Issues a single AT command to the modem, and returns the relevant part of the response. This only works for commands that return a single line followed by "OK", but conveniently, this covers almost all AT commands that I\'ve ever needed to use. For all other commands, returns None.'
def query(self, cmd, prefix=None):
out = self.command(cmd) if ((len(out) == 2) and (out[(-1)] == 'OK')): if (prefix is None): return out[0].strip() elif (out[0][:len(prefix)] == prefix): return out[0][len(prefix):].strip() return None
'Sends an SMS to _recipient_ containing _text_. Method will automatically split long \'text\' into multiple SMSs up to max_messages. To enforce only a single SMS, set max_messages=1 Raises \'ValueError\' if text will not fit in max_messages'
def send_sms(self, recipient, text):
with self.modem_lock: self.smshandler.send_sms(recipient, text)
'Returns a dict of containing information about the physical modem. The contents of each value are entirely manufacturer dependant, and vary wildly between devices.'
def hardware(self):
return {'manufacturer': self.query('AT+CGMI'), 'model': self.query('AT+CGMM'), 'revision': self.query('AT+CGMR'), 'serial': self.query('AT+CGSN')}
'Returns an integer between 1 and 99, representing the current signal strength of the GSM network, False if we don\'t know, or None if the modem can\'t report it.'
def signal_strength(self):
data = self.query('AT+CSQ') md = re.match('^\\+CSQ: (\\d+),', data) if (md is not None): csq = int(md.group(1)) return (csq if (csq < 99) else False) return None
'Blocks until the signal strength indicates that the device is active on the GSM network. It\'s a good idea to call this before trying to send or receive anything.'
def wait_for_network(self):
while True: csq = self.signal_strength() if csq: return csq time.sleep(1)
'Sends the "AT" command to the device, and returns true if it is acknowledged. Since incoming notifications and messages are intercepted automatically, this is a good way to poll for new messages without using a worker thread like RubyGSM.'
def ping(self):
try: self.command('AT') return True except errors.GsmError: return None
'Strip \'OK\' from end of command response'
def _strip_ok(self, lines):
if ((lines is not None) and (len(lines) > 0) and (lines[(-1)] == 'OK')): lines = lines[:(-1)] return lines
'Fetch stored messages with CMGL and add to incoming queue Return number fetched'
def _fetch_stored_messages(self):
lines = self.command(('AT+CMGL=%s' % self.smshandler.CMGL_STATUS)) lines = self._strip_ok(lines) messages = self.smshandler.parse_stored_messages(lines) for msg in messages: self.incoming_queue.append(msg)
'Returns the next waiting IncomingMessage object, or None if the queue is empty. The optional _ping_ and _fetch_ parameters control whether the modem is pinged (to allow new messages to be delivered instantly, on those modems which support it) and queried for unread messages in storage, which can both be disabled in ca...
def next_message(self, ping=True, fetch=True):
if ping: self.ping() if fetch: self._fetch_stored_messages() if (not self.incoming_queue): return None return self.incoming_queue.pop(0)
':return: A :class:`FeedParserDict`.'
def __getitem__(self, key):
if (key == 'category'): try: return dict.__getitem__(self, 'tags')[0]['term'] except IndexError: raise KeyError, "object doesn't have key 'category'" elif (key == 'enclosures'): norel = (lambda link: FeedParserDict([(name, value) for (name, value) in l...
':return: A :class:`FeedParserDict`.'
def get(self, key, default=None):
try: return self.__getitem__(key) except KeyError: return default
'Return processed HTML as a single string'
def output(self):
return ''.join([str(p) for p in self.pieces])
'Copy Intialise'
def __init__(self, db):
wsgi_intercept.webtest_intercept.WebCase.__init__(self) return
'Hook into the WSGI process'
def setUp(self):
wsgi_intercept.add_wsgi_intercept(self.HOST, self.PORT, create_fn) return
'Mandatory method for all TestCase instances'
def runTest(self):
return
'(Lazy) check debug mode and activate the respective settings'
def check_debug(self):
debug = self._debug base_debug = bool(self.get_base_debug()) if ((debug is None) or (debug != base_debug)): self._debug = base_debug debug = (base_debug or current.request.get_vars.get('debug', False)) from gluon.custom_import import track_changes s3 = current.response.s3 ...
'Which deployment template to use for config.py, layouts.py, menus.py http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Templates'
def get_template(self):
return self.base.get('template', 'default')
'Legacy function, retained for backwards-compatibility with existing 000_config.py instances => modern 000_config.py should just call settings.import_template() @todo: deprecate'
def exec_template(self, path):
self.import_template()
'Import and invoke the template config (new module pattern). Allows to specify multiple templates like: settings.template = ("default", "locations.US") Configurations will be imported and executed in order of appearance @param config: name of the config-module @todo: remove fallback when migration complete (+giving som...
def import_template(self, config='config'):
names = self.get_template() if (not isinstance(names, (list, tuple))): names = [names] for name in names: package = ('templates.%s' % name) self.check_debug() template = None try: template = getattr(__import__(package, fromlist=[config]), config) e...
'Fallback for legacy templates - execute config.py'
def execute_template(self, name):
import os location = 'private' path = os.path.join(current.request.folder, location, 'templates', name, 'config.py') if os.path.exists(path): import sys print >>sys.stderr, ('%s/config.py: script pattern deprecated.' % name) self.base.template_location = location ...
'Which template folder to use for views/layout.html NB Only themes in modules/templates are supported now'
def get_theme(self):
theme = self.base.get('theme', 'default') if ('.' in theme): (theme_location, theme) = theme.split('.', 1) current.response.s3.theme_location = ('%s/' % theme_location) else: current.response.s3.theme_location = '' return theme
'Whether there is a custom Ext theme or simply use the default xtheme-gray - specified as <themefolder>/xtheme-<filename>.css'
def get_base_xtheme(self):
return self.base.get('xtheme')
'Customise a Controller - runs before resource customisation - but prep runs after resource customisation'
def customise_controller(self, tablename, **attr):
customise = self.get(('customise_%s_controller' % tablename)) if customise: return customise(**attr) else: return attr
'Allow use of a Customised module Home page Fallback to cms_index if not configured Fallback to an alt_function if defined in the controller'
def customise_home(self, module, alt_function):
customise = self.get(('customise_%s_home' % module)) if customise: return customise() else: return current.s3db.cms_index(module, alt_function=alt_function)
'Get customisation callback for a resource - runs after controller customisation - but runs before prep'
def customise_resource(self, tablename):
return self.get(('customise_%s_resource' % tablename))
'Whether a Module is enabled in the current template'
def has_module(self, module_name):
return (module_name in self.modules)
'Whether we\'re running from a non-writable CD'
def is_cd_version(self):
return self.base.get('cd_version', False)
'Google Analytics Key'
def get_google_analytics_tracking_id(self):
return self.base.get('google_analytics_tracking_id')
'List of YouTube IDs for the /default/video page'
def get_youtube_id(self):
return self.base.get('youtube_id', [])
'salt to encrypt passwords - normally randomised during 1st run'
def get_auth_hmac_key(self):
return self.auth.get('hmac_key', 'akeytochange')
'Are password changes allowed? - set to False if passwords are being managed externally (OpenID / SMTP / LDAP)'
def get_auth_password_changes(self):
return self.auth.get('password_changes', True)
'To set the Minimum Password Length'
def get_auth_password_min_length(self):
return self.auth.get('password_min_length', int(4))
'List of domains which can use GMail SMTP for Authentication'
def get_auth_gmail_domains(self):
return self.auth.get('gmail_domains', [])
'List of domains which can use Office 365 SMTP for Authentication'
def get_auth_office365_domains(self):
return self.auth.get('office365_domains', [])
'Read the Google OAuth settings - if configured, then it is assumed that Google Authentication is enabled'
def get_auth_google(self):
auth_get = self.auth.get client_id = auth_get('google_id', False) client_secret = auth_get('google_secret', False) if (client_id and client_secret): return {'id': client_id, 'secret': client_secret} else: return False
'Read the Humanitarian.ID OAuth settings - if configured, then it is assumed that Humanitarian.ID Authentication is enabled'
def get_auth_humanitarian_id(self):
auth_get = self.auth.get client_id = auth_get('humanitarian_id_client_id', False) client_secret = auth_get('humanitarian_id_client_secret', False) if (client_id and client_secret): return {'id': client_id, 'secret': client_secret} else: return False
'Use OpenID for Authentication'
def get_auth_openid(self):
return self.auth.get('openid', False)
'Whether Users can register themselves - False to disable self-registration - True to use the default registration page at default/user/register - "index" to use a cyustom registration page defined in private/templates/<template>/controllers.py'
def get_security_self_registration(self):
return self.security.get('self_registration', True)
'Whether to show version info on the about page'
def get_security_version_info(self):
return self.security.get('version_info', True)
'Whether the version info on the About page requires login'
def get_security_version_info_requires_login(self):
return self.security.get('version_info_requires_login', False)
'Which page to go to after login'
def get_auth_login_next(self):
return self.auth.get('login_next', URL(c='default', f='index'))
'Link User accounts to none or more of: * Staff * Volunteer * Member'
def get_auth_registration_link_user_to(self):
return self.auth.get('registration_link_user_to')
'Link User accounts to none or more of: * Staff * Volunteer * Member'
def get_auth_registration_link_user_to_default(self):
return self.auth.get('registration_link_user_to_default')
'Make the selection of Mobile Phone Mandatory during registration'
def get_auth_registration_mobile_phone_mandatory(self):
return self.auth.get('registration_mobile_phone_mandatory', False)
'Have the registration form request the Organisation'
def get_auth_registration_requests_organisation(self):
return self.auth.get('registration_requests_organisation', False)
'See Organisations in User Admin'
def get_auth_admin_sees_organisation(self):
return self.auth.get('admin_sees_organisation', self.get_auth_registration_requests_organisation())
'Make the selection of Organisation required during registration'
def get_auth_registration_organisation_required(self):
return self.auth.get('registration_organisation_required', False)
'Hide the Organisation field in the registration form unless an email is entered which isn\'t whitelisted'
def get_auth_registration_organisation_hidden(self):
return self.auth.get('registration_organisation_hidden', False)
'Default the Organisation during registration'
def get_auth_registration_organisation_default(self):
return self.auth.get('registration_organisation_default')
'Default the Organisation during registration - will return the organisation_id'
def get_auth_registration_organisation_id_default(self):
name = self.auth.get('registration_organisation_default') if name: otable = current.s3db.org_organisation orow = current.db((otable.name == name)).select(otable.id).first() if orow: organisation_id = orow.id else: organisation_id = otable.insert(name=name)...
'Have the registration form request the Organisation Group'
def get_auth_registration_requests_organisation_group(self):
return self.auth.get('registration_requests_organisation_group', False)
'Make the selection of Organisation Group required during registration'
def get_auth_registration_organisation_group_required(self):
return self.auth.get('registration_organisation_group_required', False)
'Have the registration form request the Site'
def get_auth_registration_requests_site(self):
return self.auth.get('registration_requests_site', False)
'Make the selection of site required during registration'
def get_auth_registration_site_required(self):
return self.auth.get('registration_site_required', False)
'Have the registration form request an Image'
def get_auth_registration_requests_image(self):
return self.auth.get('registration_requests_image', False)
'Message someone gets when they register & they need approving'
def get_auth_registration_pending(self):
message = self.auth.get('registration_pending') if message: return current.T(message) approver = self.get_mail_approver() if ('@' in approver): m = ('Registration is still pending approval from Approver (%s) - please wait until confirmation received...
'Message someone gets when they register & they need approving'
def get_auth_registration_pending_approval(self):
message = self.auth.get('registration_pending_approval') if message: return current.T(message) approver = self.get_mail_approver() if ('@' in approver): m = ('Thank you for validating your email. Your user account is still pending for approval by...
'A dictionary of realms, with lists of role UUIDs, to assign to newly-registered users Use key = 0 to have the roles not restricted to a realm'
def get_auth_registration_roles(self):
return self.auth.get('registration_roles', [])
'Whether the first user to register for an Org should get the ORG_ADMIN role for that Org'
def get_auth_org_admin_to_first(self):
return self.auth.get('org_admin_to_first', False)
'Force users to accept Terms of Service before Registering an account - uses <template>/views/tos.html'
def get_auth_terms_of_service(self):
return self.auth.get('terms_of_service', False)
'Redirect the newly-registered user to their volunteer details page'
def get_auth_registration_volunteer(self):
return self.auth.get('registration_volunteer', False)
'Use record approval (False by default)'
def get_auth_record_approval(self):
return self.auth.get('record_approval', False)
'Which tables record approval is required for'
def get_auth_record_approval_required_for(self):
return self.auth.get('record_approval_required_for', [])
'Which tables record approval is not automatic for'
def get_auth_record_approval_manual(self):
return self.auth.get('record_approval_manual', [])
'Which entity types to use as realm entities in role manager'
def get_auth_realm_entity_types(self):
default = ('org_group', 'org_organisation', 'org_office', 'inv_warehouse', 'pr_group') return self.__lazy('auth', 'realm_entity_types', default=default)
'Hook to determine the owner entity of a record'
def get_auth_realm_entity(self):
return self.auth.get('realm_entity')
'Should we set pr_person.realm_entity to that of hrm_human_resource.site_id$pe_id or hrm_human_resource.organisation_id$pe_id if 1st not set'
def get_auth_person_realm_human_resource_site_then_org(self):
return self.auth.get('person_realm_human_resource_site_then_org', False)
'Sets pr_person.realm_entity to organisation.pe_id of member_member'
def get_auth_person_realm_member_org(self):
return self.auth.get('person_realm_member_org', False)
'Activate Entity Role Manager (=embedded Role Manager Tab for OrgAdmins)'
def get_auth_entity_role_manager(self):
return self.auth.get('entity_role_manager', False)
'Which modules are included in the Role Manager - to assign discrete permissions to via UI'
def get_auth_role_modules(self):
T = current.T return self.auth.get('role_modules', OrderedDict([('staff', T('Staff')), ('vol', T('Volunteers')), ('member', T('Members')), ('inv', T('Warehouses')), ('asset', T('Assets')), ('project', T('Projects')), ('survey', T('Assessments')), ('irs', T('Incidents'))]))
'Access levels for the Role Manager UI'
def get_auth_access_levels(self):
T = current.T return self.auth.get('access_levels', OrderedDict([('reader', T('Reader')), ('data_entry', T('Data Entry')), ('editor', T('Editor')), ('super', T('Super Editor'))]))
'Default is Simple Security Policy'
def get_security_policy(self):
return self.security.get('policy', 1)
'Ownership-rule for records without owner: True = not owned by any user (strict ownership, default) False = owned by any authenticated user'
def get_security_strict_ownership(self):
return self.security.get('strict_ownership', True)
'Instance Name - for management scripts. e.g. prod or test'
def get_instance_name(self):
return self.base.get('instance_name', '')
'System Name - for the UI & Messaging'
def get_system_name(self):
return self.base.get('system_name', current.T('Sahana Eden Humanitarian Management Platform'))
'System Name (Short Version) - for the UI & Messaging'
def get_system_name_short(self):
return self.base.get('system_name_short', 'Sahana')
'Debug mode: Serve CSS/JS in separate uncompressed files'
def get_base_debug(self):
return self.base.get('debug', False)
'Allow testing of Eden using EdenTest'
def get_base_allow_testing(self):
return self.base.get('allow_testing', True)
'Whether to allow Web2Py to migrate the SQL database to the new structure'
def get_base_migrate(self):
return self.base.get('migrate', True)
'Whether to have Web2Py create the .table files to match the expected SQL database structure'
def get_base_fake_migrate(self):
return self.base.get('fake_migrate', False)
'Whether to prepopulate the database &, if so, which set of data to use for this'
def get_base_prepopulate(self):
base = self.base setting = base.get('prepopulate', 1) if setting: options = base.get('prepopulate_options') return self.resolve_profile(options, setting) else: return 0
'Whether the guided tours are enabled'
def get_base_guided_tour(self):
return self.base.get('guided_tour', False)
'The Public URL for the site - for use in email links, etc'
def get_base_public_url(self):
public_url = self.base.get('public_url') if (not public_url): env = current.request.env scheme = env.get('wsgi_url_scheme', 'http').lower() host = (env.get('http_host') or '127.0.0.1:8000') self.base.public_url = public_url = ('%s://%s' % (scheme, host)) return public_url
'Should we use CDNs (Content Distribution Networks) to serve some common CSS/JS?'
def get_base_cdn(self):
return self.base.get('cdn', False)
'Get the IP:port of the chat server if enabled or return False'
def get_chat_server(self):
return self.base.get('chat_server', False)
'Should we store sessions in the database to avoid locking sessions on long-running requests?'
def get_base_session_db(self):
result = self.base.get('session_db', False) if result: (db_string, pool_size) = self.get_database_string() if (db_string.find('sqlite') != (-1)): result = False return result
'Should we store sessions in a Memcache service to allow sharing between multiple instances?'
def get_base_session_memcache(self):
return self.base.get('session_memcache', False)
'URL to connect to solr server'
def get_base_solr_url(self):
return self.base.get('solr_url', False)
'Lookup callback to use for imports in the following order: - custom [create, update]_onxxxx - default [create, update]_onxxxx - custom onxxxx - default onxxxx NB: Currently only onaccept is actually used'
def get_import_callback(self, tablename, callback):
callbacks = self.base.get('import_callbacks', []) if (tablename in callbacks): callbacks = callbacks[tablename] if (callback in callbacks): return callbacks[callback] get_config = current.s3db.get_config default = get_config(tablename, callback) if default: return...
'Minimum severity level for logger: "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL". None = turn off logging'
def get_log_level(self):
return ('DEBUG' if self.base.get('debug') else self.log.get('level'))
'True to enable console logging (sys.stderr)'
def get_log_console(self):
return self.log.get('console', True)
'Log file name, None to turn off log file output'
def get_log_logfile(self):
return self.log.get('logfile')
'True to enable detailed caller info in log (filename, line number, function name), useful for diagnostics'
def get_log_caller_info(self):
return self.log.get('caller_info', False)
'Whether to instead of LIKE use REGEXP with groups of diacritic alternatives of characters to enforce accent-insensitive matches in text search (for SQLite and PostgreSQL, neither of which applies collation rules in LIKE) @note: MySQL\'s REGEXP implementation is not multibyte-safe, so AIRegex is ignored for MySQL. @not...
def get_database_airegex(self):
if (self.get_database_type() != 'mysql'): airegex = self.__lazy('database', 'airegex', False) else: airegex = False return airegex