PageRenderTime 41ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/src/python/flow.py

https://github.com/bewest/unapy
Python | 213 lines | 198 code | 13 blank | 2 comment | 5 complexity | 7d0a71696ad35c9ac6eef8b608ecf064 MD5 | raw file
  1. import sys
  2. import logging
  3. log = logging.getLogger('tool')
  4. from unapy import cli
  5. from unapy import flow
  6. from unapy.commands import at
  7. from pprint import pformat
  8. class TCPATRUN(flow.ATFlow):
  9. def get_config(self):
  10. self.tcpatruncfg = self.session.process(at.TCPATRUNCFG.query( ))
  11. log.info(' '.join( map( pformat, [
  12. self.tcpatruncfg,
  13. self.tcpatruncfg.getData( ) ]) ))
  14. def get_active_instances(self):
  15. self.active_instances = self.session.process(at.TCPATRUND.query( ))
  16. def flow(self, req):
  17. self.get_config()
  18. self.get_active_instances( )
  19. class PDPContext(flow.ATFlow):
  20. apns = None
  21. def _get_config(self):
  22. # TODO: make this return something from a config file or database or cli
  23. # options
  24. default = {
  25. 'apn': [ ]
  26. }
  27. return {
  28. 'apn': [
  29. { 'cid': 1, 'name': 'webtrial.globalm2m.net' },
  30. ],
  31. 'auth': [
  32. ],
  33. 'attach': True,
  34. }
  35. def flow(self, req):
  36. config = self._get_config()
  37. self.set_module_verbose_error()
  38. self.get_apns( )
  39. for apn in config.get('apn', [ ]):
  40. if apn['name'] != self.get_apns:
  41. self.set_apn(**apn)
  42. if config.get('attach', False):
  43. if not self.is_attached( ):
  44. self.attach_grps( )
  45. def get_active_cids(self):
  46. self.cids = self.session.process(at.SGACT.query( ))
  47. def get_ip_addr(self):
  48. self.ip_addr_info = self.session.process(at.CGPADDR.assign(1))
  49. return self.ip_addr_info
  50. def get_apns(self):
  51. command = self.session.process(at.CGDCONT.query( ))
  52. self.apns = command.getData( )
  53. return self.apns
  54. def get_apn(self, ctx=1):
  55. r = ''
  56. if self.apns is None:
  57. self.get_apns( )
  58. try:
  59. r = self.apns[ctx].name
  60. except IndexError, e: pass # no apn
  61. return r
  62. def set_apn(self, name='webtrial.globalm2m.net', cid=1, pdp="IP"):
  63. oldapn = self.get_apn(cid)
  64. newapn = '"%s"' % oldapn
  65. if oldapn != name:
  66. name = '"%s"' % name
  67. pdp = '"%s"' % pdp
  68. command = self.session.process(at.CGDCONT.assign(cid, pdp, name))
  69. self.get_apns( )
  70. newapn = self.get_apn(cid)
  71. return newapn
  72. def set_module_verbose_error(self):
  73. command = self.session.process(at.CMEE.assign(2))
  74. log.info(command.getData( ))
  75. def is_registered(self):
  76. command = self.session.process(at.CREG.query())
  77. result = command.getData( )
  78. return result[1]
  79. def attach_grps(self):
  80. self.session.process(at.CGATT.assign(1))
  81. def is_attached(self):
  82. attached = self.session.process(at.CGATT.query()).getData( )
  83. return attached
  84. def hello(self):
  85. attached = link.process(at.CGATT.query()).data
  86. if int(attached[0][0]) == 0:
  87. print "GPRS PDP context not attached: %s" % attached
  88. attached = link.process(at.CGATT.assign(1))
  89. activated = link.process(at.SGACT.query()).data
  90. print "GPRS PDP context attached: %s" % attached
  91. print "GPRS PDP context activated: %s" % activated
  92. if int(attached[0][0]):
  93. print "context attached"
  94. if int(activated[0][1]) != 1:
  95. print "attempt sgact"
  96. link.process(at.SGACT.assign(1,1))
  97. print "ip address: ", ip_addr(link)
  98. class Flow(flow.ATFlow):
  99. """Doesn't do much except check SIM status."""
  100. def check_sim(self, link):
  101. command = link.process(at.QSS.query())
  102. qss = command.getData( )
  103. self.log.info("sim status %r" % (qss, ))
  104. return qss
  105. def flow(self, req):
  106. self.log.info("do stuff with request here. %r" % req )
  107. req.io.setTimeout( 3 )
  108. req.sim_status = self.check_sim(req)
  109. print "SIM ENABLED: %s" % req.sim_status.status
  110. class FlowTool(object):
  111. Flow = None
  112. def __init__(self, link, flows, opts):
  113. self.flows = flows
  114. self.session = flow.Session(link, self)
  115. #self.args, self.options =
  116. def selectFlow(self, name, options={}):
  117. self.Flow = self.flows[name]
  118. def runSelected(self):
  119. flows = self.Flow(self.session)
  120. log.info("starting to run flows")
  121. for flow in flows( ):
  122. flow(self.session)
  123. @classmethod
  124. def getFlows(klass):
  125. """Should return a dict of flows. The keys are the names of the commands, and the values are Flow objects.
  126. The flow objects are inspected by the tool to generate help and options
  127. automatically.
  128. """
  129. return { 'qss' : Flow, 'tcpatrun': TCPATRUN,
  130. 'gsm' : PDPContext,
  131. }
  132. class Application(cli.CLIApp):
  133. def custom_pre_run(self):
  134. super(type(self), self).custom_pre_run()
  135. logging.basicConfig( )
  136. self.set_logger_level(logging.getLogger(__name__))
  137. logging.getLogger('tool').setLevel(logging.INFO)
  138. #self.set_logger_level()
  139. self.tool = FlowTool(self.link, self.flows, (self.args, self.options))
  140. #self.tool.selectFlow('qss')
  141. self.interpret_args( )
  142. def set_custom_options(self):
  143. usage = """%prog [options] command options
  144. commands:
  145. {commands}
  146. """
  147. cmd_help = [ ]
  148. self.flows = FlowTool.getFlows( )
  149. for cmd in self.flows:
  150. cmd_help.append(" %s" % cmd)
  151. super(type(self), self).set_custom_options()
  152. self.parser.set_usage(usage.format(commands="\n".join(cmd_help)))
  153. pass
  154. def interpret_args(self):
  155. args = list(self.args)
  156. flow = None
  157. try:
  158. flow = args.pop( )
  159. self.tool.selectFlow(flow)
  160. except (IndexError, KeyError), e:
  161. if flow not in [ '', 'help', 'ls', 'list' ]:
  162. print "unsupported flow: %r" % flow
  163. self.parser.print_usage( )
  164. sys.exit(0)
  165. def setup_pre_options(self):
  166. super(type(self), self).setup_pre_options()
  167. def run(self):
  168. self.tool.runSelected( )
  169. if __name__ == '__main__':
  170. app = Application( )
  171. app( )
  172. #####
  173. # EOF