Example #1
0
 def test_deauthorization_url(self):
     with mock.patch.object(HealthVaultConn, '_get_auth_token'):
         c = HealthVaultConn(app_id="123",
                             app_thumbprint="2",
                             public_key=TEST_PUBLIC_KEY,
                             private_key=TEST_PRIVATE_KEY,
                             wctoken=None,
                             server="6",
                             shell_server="shell.server")
     c.auth_token = "FakeToken"
     url = c.deauthorization_url(
         "http://ourown.server.com/with/some/parts/")
     self.assertIsNotNone(
         re.
         compile('https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format(
             '(targetqs=redirect%3D'
             'http%253A%252F%252Fourown\.server\.com%252Fwith%252Fsome%252Fparts%25'
             '2F%26cred_token%3DFakeToken%26appid%3D123)|(target=APPSIGNOUT)'
         )).match(url))
     # callback URL is optional
     url = c.deauthorization_url()
     self.assertIsNotNone(
         url, 'https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format(
             '(targetqs=cred_token%3D'
             'FakeToken%26appid%3D123)|(target=APPSIGNOUT)'))
 def test_authorization_url(self):
     with mock.patch.object(HealthVaultConn, '_get_auth_token'):
         c = HealthVaultConn(
                 app_id="123", app_thumbprint="2", public_key=TEST_PUBLIC_KEY, private_key=TEST_PRIVATE_KEY,
                 wctoken=None, server="6", shell_server="shell.server"
             )
     url = c.authorization_url("http://ourown.server.com/with/some/parts/")
     self.assertIsNotNone(
         re.compile('https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format(
             '(target=APPAUTH)|(targetqs={0}%26{0})'.format(
                 '(redirect%3Dhttp%253A%252F%252Fourown\.server\.com%252Fwith%252Fsome%252Fparts%252F)|'
                 '(appid%3D123)'))).match(url)
     )
     # callback URL is optional
     url = c.authorization_url()
     self.assertIsNotNone(
         re.compile('https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format(
             '(targetqs=appid%3D123)|(target=APPAUTH)')).match(url)
     )
     # Can include record_id
     url = c.authorization_url(record_id="FooBar")
     self.assertIsNotNone(
         re.compile('https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format(
             '(targetqs={0}%26{0})|(target=APPAUTH)'.format('(extrecordid%3DFooBar)|(appid%3D123)'))
         ).match(url)
     )
     # Or both
     url = c.authorization_url("http://ourown.server.com/with/some/parts/", record_id="FooBar")
     self.assertIsNotNone(
         re.compile('https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format(
             '(targetqs={0}%26{0}%26{0})|(target=APPAUTH)'.format(
                 '(redirect%3Dhttp%253A%252F%252Fourown\.server\.com%252Fwith%252Fsome%252Fparts%252F)|'
                 '(extrecordid%3DFooBar)|(appid%3D123)'))).match(url)
     )
    def test_build_and_send_request(self):
        # construct a conn, mocking all the real work
        AUTH_TOKEN = "AUTHKEY"
        WC_TOKEN = "WCKEY"
        with mock.patch.object(HealthVaultConn, '_get_auth_token') as gat:
            with mock.patch.object(HealthVaultConn, '_get_record_id') as gri:
                gat.return_value = AUTH_TOKEN
                gri.return_value = "8"
                c = HealthVaultConn(
                        app_id="1", app_thumbprint="2", public_key=TEST_PUBLIC_KEY, private_key=TEST_PRIVATE_KEY,
                        wctoken=WC_TOKEN, server="6", shell_server="7"
                    )
        with mock.patch.object(c, '_send_request') as sendRequest:
            c._build_and_send_request(method_name="METHOD", info="<info>BOO</info>")
        payload = sendRequest.call_args[0][0]
        request = ET.fromstring(payload)
#        print elt_to_string(request)
        header = request.find('header')
        method_name = header.find('method').text
        self.assertEqual("METHOD", method_name)
        self.assertEqual("1", header.find('method-version').text)
        self.assertEqual("8", header.find('record-id').text)
        self.assertEqual(AUTH_TOKEN, header.find('auth-session/auth-token').text)
        self.assertEqual(WC_TOKEN, header.find('auth-session/user-auth-token').text)
        self.assertEqual("BOO", request.find('info').text)
Example #4
0
 def test_build_and_send_request(self):
     # construct a conn, mocking all the real work
     AUTH_TOKEN = "AUTHKEY"
     WC_TOKEN = "WCKEY"
     with mock.patch.object(HealthVaultConn, '_get_auth_token') as gat:
         with mock.patch.object(HealthVaultConn, '_get_record_id') as gri:
             gat.return_value = AUTH_TOKEN
             gri.return_value = "8"
             c = HealthVaultConn(app_id="1",
                                 app_thumbprint="2",
                                 public_key=TEST_PUBLIC_KEY,
                                 private_key=TEST_PRIVATE_KEY,
                                 wctoken=WC_TOKEN,
                                 server="6",
                                 shell_server="7")
     with mock.patch.object(c, '_send_request') as sendRequest:
         c._build_and_send_request(method_name="METHOD",
                                   info="<info>BOO</info>")
     payload = sendRequest.call_args[0][0]
     request = ET.fromstring(payload)
     #        print elt_to_string(request)
     header = request.find('header')
     method_name = header.find('method').text
     self.assertEqual("METHOD", method_name)
     self.assertEqual("1", header.find('method-version').text)
     self.assertEqual("8", header.find('record-id').text)
     self.assertEqual(AUTH_TOKEN,
                      header.find('auth-session/auth-token').text)
     self.assertEqual(WC_TOKEN,
                      header.find('auth-session/user-auth-token').text)
     self.assertEqual("BOO", request.find('info').text)
 def test_is_authorized(self):
     with mock.patch.object(HealthVaultConn, '_get_auth_token'):
         c = HealthVaultConn(
                 app_id="1", app_thumbprint="2", public_key=TEST_PUBLIC_KEY, private_key=TEST_PRIVATE_KEY,
                 wctoken=None, server="6", shell_server="7"
             )
     self.assertFalse(c.is_authorized())
     c.authorized = True
     self.assertTrue(c.is_authorized())
Example #6
0
 def test_is_authorized(self):
     with mock.patch.object(HealthVaultConn, '_get_auth_token'):
         c = HealthVaultConn(app_id="1",
                             app_thumbprint="2",
                             public_key=TEST_PUBLIC_KEY,
                             private_key=TEST_PRIVATE_KEY,
                             wctoken=None,
                             server="6",
                             shell_server="7")
     self.assertFalse(c.is_authorized())
     c.authorized = True
     self.assertTrue(c.is_authorized())
Example #7
0
def mvaultentry(request):
	target  = request.GET['target']
	wctoken = ""
	if target == "AppAuthSuccess":
		wctoken = request.GET['wctoken']
	else:
		return HttpResponse("cannot get wctoken")

	hvconn	= HealthVaultConn(wctoken)
	demo	= hvconn.getBasicDemographicInfo()	
	template_values = {'basicdemographic':demo}
	return render_to_response('hvdata.html',template_values)
Example #8
0
 def test_get_record_id(self):
     # get record id parses the response okay
     # need to mock send_request so we can get past getting the auth token
     with mock.patch.object(HealthVaultConn, '_send_request') as sr:
         return_xml = u'''<?xml version="1.0" ?>
         <response>
             <wc:info xmlns:wc="urn:com.microsoft.wc.methods.response.CreateAuthenticatedSessionToken">
                 <token>Foo</token>
             </wc:info>
         </response>'''
         return_tree = ET.fromstring(return_xml)
         sr.return_value = 4, return_xml, return_tree
         with mock.patch.object(HealthVaultConn,
                                '_build_and_send_request') as basr:
             xml = u'''<?xml version="1.0" ?>
             <response>
                 <x:info xmlns:x="urn:com.microsoft.wc.methods.response.GetPersonInfo">
                     <person-info>
                         <person-id>PERSON-ID</person-id>
                         <name>John Doe</name>
                         <selected-record-id>RECORD-ID</selected-record-id>
                     </person-info>
                 </x:info>
             </response>'''
             tree = ET.fromstring(xml)
             basr.return_value = 18, xml, tree
             c = HealthVaultConn(app_id="1",
                                 app_thumbprint="2",
                                 public_key=TEST_PUBLIC_KEY,
                                 private_key=TEST_PRIVATE_KEY,
                                 wctoken="fakewctoken",
                                 server="6",
                                 shell_server="7")
         self.assertEqual("RECORD-ID", c.record_id)
 def run(self):
     """run when our device driver thread is started"""
     self.sd = None
     '''/
     import serial
     self.sd = serial.Serial(
        0,                            #port number
        baudrate=115200,              #baudrate
        bytesize=serial.EIGHTBITS,    #number of databits
        parity=serial.PARITY_NONE,    #enable parity checking
        stopbits=serial.STOPBITS_ONE, #number of stopbits
        timeout=3,                    #set a timeout value
        xonxoff=0,                    #enable software flow control
        rtscts=0,                     #enable RTS/CTS flow control
     )
     '''
     
     try:
         fd = None
         fd = open(path + 'id_secret_token.txt', 'r+')
         id = fd.readline()
         secret = fd.readline()
         token = fd.readline()
         fd.close()
         self.hvconn = HealthVaultConn(path, id, secret, token)
     except:
         traceback.print_exc()
         if fd != None: fd.close()
         self.hvconn = None
     
     ip = SettingsBase.get_setting(self, "server_ip")
     port = int(SettingsBase.get_setting(self, "server_port"))
     server = 'wsgiref'
     run_itty(server, ip, port)
Example #10
0
    def verify_get_data_api(self, xml, expected, methodname):
        """Given one of the methods that gets some XML from HealthVault and returns a dictionary or list,
        verify it returns what we expect

        :param xml: The XML that get_things will return to the method under test
        :param expected: The expected return value of the method under test
        :param methodname: The name of the method under test
        """
        # construct a conn, mocking all the real work
        with mock.patch.object(HealthVaultConn, '_get_auth_token') as gat:
            gat.return_value = "authtoken"
            with mock.patch.object(HealthVaultConn, '_get_record_id') as gri:
                gri.return_value = "1"
                c = HealthVaultConn(app_id="1",
                                    app_thumbprint="2",
                                    public_key=TEST_PUBLIC_KEY,
                                    private_key=TEST_PRIVATE_KEY,
                                    wctoken="5",
                                    server="6",
                                    shell_server="7")
        # call the method under test, mocking the actual network call
        with mock.patch.object(HealthVaultConn,
                               '_build_and_send_request') as basr:
            # convert the xml we were given (top element is <info>) to look like what HealthVault would return
            full_xml_response = '<?xml version="1.0" encoding="ISO-8859-1"?><unneededtag>' + xml + "</unneededtag>"
            basr.return_value = (None, full_xml_response,
                                 ET.fromstring(full_xml_response))
            method_to_test = getattr(c, methodname)
            retval = method_to_test()
        self.assertEqual(expected, retval)
Example #11
0
    def __init__(self, request, client_address, server):
        """We need to init a lot because a new one of these gets created for every request.
        Things we need to keep around we attach to the server object via self.server
        """
        self.server = server  # the superclass __init__ does this anyway

        if not hasattr(self.server, 'conn'):
            wctoken = None
            if os.path.exists("WCTOKEN"):
                with open("WCTOKEN", "r") as f:
                    wctoken = f.read()
                    if not wctoken:
                        os.remove("WCTOKEN")

            record_id = None
            if os.path.exists("RECORD_ID"):
                with open("RECORD_ID", "r") as f:
                    record_id = f.read()

            try:
                self.server.conn = HealthVaultConn(wctoken=wctoken,
                                                   app_id=APP_ID,
                                                   app_thumbprint=THUMBPRINT,
                                                   public_key=APP_PUBLIC_KEY,
                                                   private_key=APP_PRIVATE_KEY,
                                                   record_id=record_id)
            except HealthVaultException as e:
                print e
                # Leave it un-authorized
                # set up un-authorized conn
                self.server.conn = HealthVaultConn(app_id=APP_ID,
                                                   app_thumbprint=THUMBPRINT,
                                                   public_key=APP_PUBLIC_KEY,
                                                   private_key=APP_PRIVATE_KEY,
                                                   record_id=record_id)
            else:
                if self.server.conn.record_id:
                    with open("RECORD_ID", "w") as f:
                        f.write(self.server.conn.record_id)

            # And this is a stupid old-style class, sigh
        # AND THE __init__ PROCESSES THE REQUEST!  ARGGG
        BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request,
                                                       client_address, server)
 def test_deauthorization_url(self):
     with mock.patch.object(HealthVaultConn, '_get_auth_token'):
         c = HealthVaultConn(
             app_id="123", app_thumbprint="2", public_key=TEST_PUBLIC_KEY, private_key=TEST_PRIVATE_KEY,
             wctoken=None, server="6", shell_server="shell.server"
         )
     c.auth_token = "FakeToken"
     url = c.deauthorization_url("http://ourown.server.com/with/some/parts/")
     self.assertIsNotNone(
         re.compile('https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format('(targetqs=redirect%3D'
             'http%253A%252F%252Fourown\.server\.com%252Fwith%252Fsome%252Fparts%25'
             '2F%26cred_token%3DFakeToken%26appid%3D123)|(target=APPSIGNOUT)')).match(url)
     )
     # callback URL is optional
     url = c.deauthorization_url()
     self.assertIsNotNone(
         url,
         'https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format('(targetqs=cred_token%3D'
             'FakeToken%26appid%3D123)|(target=APPSIGNOUT)')
     )
 def CreateAppInstance(request):
     self.hvconn = HealthVaultConn(path)
     
     d = {}
     d['appid'] = HV_APPID
     d['appCreationToken'] = self.hvconn.instance_creation_token
     d['instancename'] = 'iDigi Dia MS_HV presentation'
     d['redirect'] = APP_ACTION_URL
     
     targetqs = urlencode(d)
     url = "%s/redirect.aspx?%s" % (HV_SHELL_URL, urlencode({'target': "CREATEAPPLICATION", 'targetqs': targetqs}))
     raise Redirect(url)
Example #14
0
 def test_connect(self):
     # If we build a conn without a wctoken, it doesn't do the connect
     # though it does get a session token
     # then we can call connect with a wctoken and it'll do it then
     with mock.patch.object(HealthVaultConn, '_get_auth_token') as gat:
         with mock.patch.object(HealthVaultConn, '_get_record_id') as gri:
             gri.return_value = 1
             c = HealthVaultConn(app_id="1",
                                 app_thumbprint="2",
                                 public_key=TEST_PUBLIC_KEY,
                                 private_key=TEST_PRIVATE_KEY,
                                 wctoken=None,
                                 server="6",
                                 shell_server="7")
     self.assertIsNone(c.wctoken)
     self.assertFalse(c.is_authorized())
     gat.assert_any_call()
     self.assertFalse(gri.called)
     self.assertIsNotNone(c.auth_token)
     with mock.patch.object(HealthVaultConn, '_get_auth_token') as gat:
         with mock.patch.object(HealthVaultConn, '_get_record_id') as gri:
             gri.return_value = 8
             c.connect(wctoken="5")
     self.assertEqual("5", c.wctoken)
     gri.assert_any_call()
     self.assertTrue(c.is_authorized())
 def test_connect(self):
     # If we build a conn without a wctoken, it doesn't do the connect
     # though it does get a session token
     # then we can call connect with a wctoken and it'll do it then
     with mock.patch.object(HealthVaultConn, '_get_auth_token') as gat:
         with mock.patch.object(HealthVaultConn, '_get_record_id') as gri:
             gri.return_value = 1
             c = HealthVaultConn(
                     app_id="1", app_thumbprint="2", public_key=TEST_PUBLIC_KEY, private_key=TEST_PRIVATE_KEY,
                     wctoken=None, server="6", shell_server="7"
                 )
     self.assertIsNone(c.wctoken)
     self.assertFalse(c.is_authorized())
     gat.assert_any_call()
     self.assertFalse(gri.called)
     self.assertIsNotNone(c.auth_token)
     with mock.patch.object(HealthVaultConn, '_get_auth_token') as gat:
         with mock.patch.object(HealthVaultConn, '_get_record_id') as gri:
             gri.return_value = 8
             c.connect(wctoken="5")
     self.assertEqual("5", c.wctoken)
     gri.assert_any_call()
     self.assertTrue(c.is_authorized())
Example #16
0
 def get_dummy_health_vault_conn(self):
     """Construct a HealthVaultConn, mocking any network traffic,
     and return it"""
     with mock.patch.object(HealthVaultConn, '_get_auth_token'):
         with mock.patch.object(HealthVaultConn, '_get_record_id') as gri:
             gri.return_value = 8
             c = HealthVaultConn(app_id="1",
                                 app_thumbprint="2",
                                 public_key=TEST_PUBLIC_KEY,
                                 private_key=TEST_PRIVATE_KEY,
                                 wctoken="5",
                                 server="6",
                                 shell_server="7")
     return c
Example #17
0
 def test_get_auth_token(self):
     # At least test that when we connect, get_auth_token is called and calls SendRequest,
     # and parses the response okay and returns it
     with mock.patch.object(HealthVaultConn, '_send_request') as sr:
         return_xml = u'<?xml version="1.0" ?><response><wc:info xmlns:wc="urn:com.microsoft.wc.methods.response.CreateAuthenticatedSessionToken"><token>Foo</token></wc:info></response>'
         return_tree = ET.fromstring(return_xml)
         sr.return_value = 4, return_xml, return_tree
         with mock.patch.object(HealthVaultConn, '_get_record_id') as gri:
             gri.return_value = 1
             c = HealthVaultConn(app_id="1",
                                 app_thumbprint="2",
                                 public_key=TEST_PUBLIC_KEY,
                                 private_key=TEST_PRIVATE_KEY,
                                 wctoken=None,
                                 server="6",
                                 shell_server="7")
     # send request should have been called just once, we didn't provide a wctoken
     self.assertEqual(1, sr.call_count)
     # and we got the auth token from the response
     self.assertEqual("Foo", c.auth_token)
Example #18
0
 def test_very_simple(self):
     # construct a conn, mocking all the real work
     with mock.patch.object(HealthVaultConn, '_get_auth_token') as gat:
         with mock.patch.object(HealthVaultConn, '_get_record_id') as gri:
             gri.return_value = 8
             c = HealthVaultConn(app_id="1",
                                 app_thumbprint="2",
                                 public_key=TEST_PUBLIC_KEY,
                                 private_key=TEST_PRIVATE_KEY,
                                 wctoken="5",
                                 server="6",
                                 shell_server="7")
     self.assertEqual("1", c.app_id)
     self.assertEqual("2", c.app_thumbprint)
     self.assertEqual(TEST_PUBLIC_KEY, c.public_key)
     self.assertEqual(TEST_PRIVATE_KEY, c.private_key)
     self.assertEqual("5", c.wctoken)
     self.assertEqual("6", c.server)
     self.assertEqual("7", c.shell_server)
     self.assertEqual(8, c.record_id)
     # We passed in a wctoken, make sure the methods got called that set up things with HealthVault
     gat.assert_any_call()
     gri.assert_any_call()
Example #19
0
 def test_authorization_url(self):
     with mock.patch.object(HealthVaultConn, '_get_auth_token'):
         c = HealthVaultConn(app_id="123",
                             app_thumbprint="2",
                             public_key=TEST_PUBLIC_KEY,
                             private_key=TEST_PRIVATE_KEY,
                             wctoken=None,
                             server="6",
                             shell_server="shell.server")
     url = c.authorization_url("http://ourown.server.com/with/some/parts/")
     self.assertIsNotNone(
         re.
         compile('https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format(
             '(target=APPAUTH)|(targetqs={0}%26{0})'.format(
                 '(redirect%3Dhttp%253A%252F%252Fourown\.server\.com%252Fwith%252Fsome%252Fparts%252F)|'
                 '(appid%3D123)'))).match(url))
     # callback URL is optional
     url = c.authorization_url()
     self.assertIsNotNone(
         re.compile(
             'https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format(
                 '(targetqs=appid%3D123)|(target=APPAUTH)')).match(url))
     # Can include record_id
     url = c.authorization_url(record_id="FooBar")
     self.assertIsNotNone(
         re.compile(
             'https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format(
                 '(targetqs={0}%26{0})|(target=APPAUTH)'.format(
                     '(extrecordid%3DFooBar)|(appid%3D123)'))).match(url))
     # Or both
     url = c.authorization_url("http://ourown.server.com/with/some/parts/",
                               record_id="FooBar")
     self.assertIsNotNone(
         re.
         compile('https://shell\.server/redirect\.aspx\?[{0}&{0}]'.format(
             '(targetqs={0}%26{0}%26{0})|(target=APPAUTH)'.format(
                 '(redirect%3Dhttp%253A%252F%252Fourown\.server\.com%252Fwith%252Fsome%252Fparts%252F)|'
                 '(extrecordid%3DFooBar)|(appid%3D123)'))).match(url))
class MSHealthVault(PresentationBase, threading.Thread):
    
    def __init__(self, name, core_services):
        self.__name = name
        self.__core = core_services
        ## Settings Table Definition:
        self.queue = Queue.Queue()
        settings_list = [
            Setting(
                name='server_ip', type=str, required=False,
                default_value="192.168.33.106"),
            Setting(
                name='server_port', type=int, required=False,
                default_value="8081"),
            Setting(
                name='tx_interval', type=int, required=False,
                default_value=30),
        ]
        
        ## Channel Properties Definition:
        property_list = [ ]
                                            
        ## Initialize the DeviceBase interface:
        PresentationBase.__init__(self, self.__name, settings_list)
        ## Thread initialization:
        self.__stopevent = threading.Event()
        threading.Thread.__init__(self, name=name)
        threading.Thread.setDaemon(self, True)
        
        ## HealthValut functions:
        http_path = "/hv/"
        
        APP_ADDR_PORT = 'http://' + SettingsBase.get_setting(self, "server_ip") + ':' + str(SettingsBase.get_setting(self, "server_port"))
        APP_ACTION_URL = APP_ADDR_PORT + http_path + 'back'
        html_path = APP_ADDR_PORT + http_path
        
        self.hvconn = None
        self.subscribed_channels = []
        self.tx_started = False
        self.hv_ccr_pump_runing = False
        self.hv_ccr_pump_stoped = False
        self.hv_ccr_pump_restart = False
        
        html_header = '\
                <!DOCTYPE html>\
                <html>\
                <head>\
                    <title>Digi HV Presentation</title>\
                    <style type="text/css">\
                        body {\
                            background: url("http://thecodelesscode.com/images/circuits-back.jpg") 0% 0% repeat;\
                            font-size:2.5em;\
                            margin: 0;\
                            padding: 0;\
                            text-align: center;\
                        }\
                        a:link {color:black; text-decoration:none;}\
                        a:visited {color:black; text-decoration:none;}\
                        a:hover {color:red; text-decoration:underline;}\
                        a:active {color:red; text-decoration:underline;}\
                        .centered {margin: 0 auto; text-align: left; display: table;}\
                    </style>\
                </head>\
                <body><div class="centered">'
        html_footer = '</div></body></html>'
        
        @get('')
        @get('index')
        @get(http_path)
        @get(http_path + 'index')
        def IndexPage(request):
            html = html_header + '\
                <a href="' + html_path + 'create" target="_self">Create new App</a>\
                <br><br>\
                <a href="' + html_path + 'login" target="_self">Login new User</a>\
                <br><br>\
                <a href="' + html_path + 'user_list" target="_self">List of Users</a>\
                <br><br>\
                <a href="' + html_path + 'selected" target="_self">Selected User</a>\
                <br><br>'
            if not self.tx_started:
                #html += '<a href="' + html_path + 'tx_start" target="_self">Start HV Data Tx</a>'
                html += '<a href="' + html_path + 'tx_control" target="_self">Start HV Data Tx</a>'
            else:
                #html += '<a href="' + html_path + 'tx_stop" target="_self">Stop HV Data Tx</a>'
                html += '<a href="' + html_path + 'tx_control" target="_self">Stop HV Data Tx</a>'
            html += '\
                <br><br>\
                <a href="' + html_path + 'channels" target="_self">Channel Explorer</a>'
            html += html_footer
            
            return Response(html, content_type='text/html')
        
        @get(http_path + 'create')
        def CreateAppInstance(request):
            self.hvconn = HealthVaultConn(path)
            
            d = {}
            d['appid'] = HV_APPID
            d['appCreationToken'] = self.hvconn.instance_creation_token
            d['instancename'] = 'iDigi Dia MS_HV presentation'
            d['redirect'] = APP_ACTION_URL
            
            targetqs = urlencode(d)
            url = "%s/redirect.aspx?%s" % (HV_SHELL_URL, urlencode({'target': "CREATEAPPLICATION", 'targetqs': targetqs}))
            raise Redirect(url)
        
        @get(http_path + 'login')
        def LoginNewUser(request):
            if(self.hvconn == None):
                raise Redirect(html_path + 'create')
            
            d = {}
            d['appid'] = self.hvconn.instance_app_id
            d['redirect'] = APP_ACTION_URL
            
            targetqs = urlencode(d)
            url = "%s/redirect.aspx?%s" % (HV_SHELL_URL, urlencode({'target': "APPAUTH", 'targetqs': targetqs}))
                
            raise Redirect(url)
        
        @get(http_path + 'back')
        def ShellRedirectionPoint(request):
            if(self.hvconn == None):
                raise Redirect(html_path + 'create')
            self.hvconn.createAuthenticatedSessionToken()
            html = html_header + '\
                Success\
                <br><br>\
                <a href="' + html_path + 'index" target="_self">Back to Index Page</a>'
            html += html_footer
            return Response(html, content_type='text/html')
        
        @get(http_path + 'user_list')
        def AuthorizedPeopleList(request):
            if(self.hvconn == None):
                raise Redirect(html_path + 'create')
            self.hvconn.getAuthorizedPeople()
            #users = ''
            html = html_header
            for i in self.hvconn.user_dict:
                name = self.hvconn.user_dict[i]["name"]
                html += '\
                <a href="' + html_path + 'select/' + name.replace(' ', '_') + '" target="_self">' + name + '</a>\
                <br><br>'
            html += '\
                <a href="' + html_path + 'index" target="_self">Back to Index Page</a>'
            html += html_footer
            return Response(html, content_type='text/html')
            
        @get(http_path + 'select/(?P<name>\w+)')
        def SelectUser(request, name=None):
            if(self.hvconn == None):
                raise Redirect(html_path + 'create')
            name = name.replace('_', ' ')
            if name == self.hvconn.selected_user:
                message = 'User already selected.'
            else:
                message = 'User not found.'
                for i in self.hvconn.user_dict:
                    if name == self.hvconn.user_dict[i]["name"]:
                        found = 1
                        self.hvconn.userSelect(name)
                        self.hv_ccr_pump_reset()
                        message = 'User selected.'
            html = html_header +'\
                ' + message + '\
                <br><br>\
                <a href="' + html_path + 'index" target="_self">Back to Index Page</a>'
            html += html_footer
            return Response(html, content_type='text/html')
        
        @get(http_path + 'selected')
        def SelectedUser(request):
            if(self.hvconn == None):
                raise Redirect(html_path + 'create')
            user = self.hvconn.selected_user#.replace(' ', '_')
            html = html_header + '\
                Selected User: '******'\
                <br><br>\
                <a href="' + html_path + 'index" target="_self">Back to Index Page</a>'
            html += html_footer
            return Response(html, content_type='text/html')
        
        @get(http_path + 'tx_control')
        def TxControl(request):
            if(self.hvconn == None):
                raise Redirect(APP_ADDR_PORT + '/create')
            
            if not self.tx_started:
                self.tx_started = True
                self.hv_ccr_pump_start()
                html = html_header +'\
                    Auto Data Tx Started!\
                    <br><br>\
                    <a href="' + html_path + 'index" target="_self">Back to Index Page</a>'
            else:
                self.tx_started = False
                self.hv_ccr_pump_stop()
                html = html_header +'\
                    Auto Data Tx Stopped!\
                    <br><br>\
                    <a href="' + html_path + 'index" target="_self">Back to Index Page</a>'
            html += html_footer
                
            return Response(html, content_type='text/html')
        
        
        @get(http_path + 'tx_start')
        def TxStart(request):
            if(self.hvconn == None):
                raise Redirect(APP_ADDR_PORT + '/create')
            if not self.tx_started:
                self.tx_started = True
            self.hv_ccr_pump_start()
            html = html_header +'\
                Auto Data Tx Started!\
                <br><br>\
                <a href="' + html_path + 'index" target="_self">Back to Index Page</a>'
            html += html_footer
            return Response(html, content_type='text/html')
        
        @get(http_path + 'tx_stop')
        def TxStop(request):
            if(self.hvconn == None):
                raise Redirect(html_path + 'create')
            if self.tx_started:
                self.tx_started = False
            self.hv_ccr_pump_stop()
            html = html_header +'\
                Auto Data Tx Stopped!\
                <br><br>\
                <a href="' + html_path + 'index" target="_self">Back to Index Page</a>'
            html += html_footer
            return Response(html, content_type='text/html')
        
        @get(http_path + 'channels')
        def ChannelExplorer(request):
            if(self.hvconn == None):
                raise Redirect(html_path + 'create')
            
            cm = self.__core.get_service("channel_manager")
            cd = cm.channel_database_get()
            channel_list = cd.channel_list()
            
            html = html_header +'\
                Existing Channels:\
                <br><br>'
            for channel_name in channel_list:
                if channel_name in self.subscribed_channels:
                    html += '<a href="' + html_path + 'subscriber/' + channel_name + '" target="_self">Unsubscribe from: '+channel_name+'</a>'
                else:
                    html += '<a href="' + html_path + 'subscriber/' + channel_name + '" target="_self">Subscribe to: '+channel_name+'</a>'
                html += '<br><br>'
            html += '\
                <a href="' + html_path + 'index" target="_self">Back to Index Page</a>'
            html += html_footer
            return Response(html, content_type='text/html')
        
        @get(http_path + 'subscriber/(?P<channel_name>[\w\-._%]+)')
        def ChannelSubscriber(request, channel_name=None):
            if(self.hvconn == None):
                raise Redirect(html_path + 'create')
            channel_name=channel_name.replace('%20', ' ')
            if channel_name in self.subscribed_channels:
                #unsubscribe:
                self.unsubscriber(channel_name)
                self.subscribed_channels.remove(channel_name)
            else:
                #subscribe:
                self.subscriber(channel_name)
                self.subscribed_channels.append(channel_name)
            raise Redirect(html_path + 'channels')
        
        @get(http_path + 'get')
        def GetThing(request):
            if(self.hvconn == None):
                raise Redirect(APP_ADDR_PORT + '/create')
            try:
                personaldemographic = "92ba621e-66b3-4a01-bd73-74844aed4f5b"
                
                response_str = self.hvconn.getBasicThing(personaldemographic)
                return Response(response_str, content_type='text/xml')
                
            except:
                traceback.print_exc()
                
            return Response(response_str, content_type='text/xml')
        ##############################################################################
        @get(http_path + 'put_ccr')
        def PutThing_CCR(request):
            if(self.hvconn == None):
                raise Redirect(APP_ADDR_PORT + '/create')
            
            try:
                personaldemographic = "92ba621e-66b3-4a01-bd73-74844aed4f5b"
                ccr = "1e1ccbfc-a55d-4d91-8940-fa2fbf73c195"
                
                response_str = self.hvconn.getBasicThing(personaldemographic)
                
                dom = minidom.parseString(response_str)
                
                node = dom.getElementsByTagName("first")
                first_name = node.pop().firstChild.nodeValue    
                
                node = dom.getElementsByTagName("last")
                family_name = node.pop().firstChild.nodeValue    
                
                node = dom.getElementsByTagName("y")
                year = node.pop().firstChild.nodeValue
                
                node = dom.getElementsByTagName("m")
                month = node.pop().firstChild.nodeValue
                
                node = dom.getElementsByTagName("d")
                day = node.pop().firstChild.nodeValue
                
                date_of_birth = year + '-' + month + '-' + day
        
            except:
                traceback.print_exc()
                
            ccr_xml = self.Channels_to_CCR(first_name, family_name, date_of_birth)
            response_str = self.hvconn.putBasicThing(ccr, ccr_xml)
            
            return Response(response_str, content_type='text/xml')
        
    def apply_settings(self):
        """\
            Called when new configuration settings are available.
       
            Must return tuple of three dictionaries: a dictionary of
            accepted settings, a dictionary of rejected settings,
            and a dictionary of required settings that were not
            found.
        """
        SettingsBase.merge_settings(self)
        accepted, rejected, not_found = SettingsBase.verify_settings(self)
        if len(rejected) or len(not_found):
            print "Settings rejected/not found: %s %s" % (rejected, not_found)

        SettingsBase.commit_settings(self, accepted)

        return (accepted, rejected, not_found)

    def start(self):
        """Start the device driver.  Returns bool."""
        threading.Thread.start(self)
        return True

    def stop(self):
        """Stop the device driver.  Returns bool."""
        self.unsubscriber()
        #self.hv_ccr_pump_runing = False
        self.hv_ccr_pump_stoped = True
        self.__stopevent.set()
        return True
                
    ## HealthVault help functions:
    def subscriber(self, source_name=None):
        cm = self.__core.get_service("channel_manager")
        cp = cm.channel_publisher_get()
        try:
            if(source_name == None):
                print 'subscribe to all channels'
                cp.subscribe_to_all(self.prop_set_input)
            else:
                print 'subscribe to a specific channel: ', source_name
                cp.subscribe(source_name, self.prop_set_input)
            #cp.subscribe_new_channels(self.subscriber) #this is going to subscribe to all new channels!!!
        except:
            traceback.print_exc()
        return True
    
    def unsubscriber(self, source_name=None):
        cm = self.__core.get_service("channel_manager")
        cp = cm.channel_publisher_get()
        try:
            if(source_name == None):
                print 'unsubscribe from all channels'
                cp.unsubscribe_from_all(self.prop_set_input)
            else:
                print 'unsubscribe from a specific channel: ', source_name
                cp.unsubscribe(source_name, self.prop_set_input)
            #cp.unsubscribe_new_channels(self.prop_set_input)
        except:
            traceback.print_exc()
        return True
    
    def prop_set_input(self, sample):
        if(not isinstance(sample, Sample)):
            
            channel_name = sample.name().split('.')[1]
            sample = sample.get()
            if self.sd!= None:
                self.sd.write(sample.value)
            self.queue.put((sample, channel_name))
            
            #print 'New sample arived in channel: ', channel_name
        return True
    
    def Channels_to_CCR(self, name, date_of_birth):
        if self.queue.empty():
            return False
        x = {}
        size = self.queue.qsize()
        for i in range(0, size):
            x[i] = self.queue.get()
            #sample, sample_name = x[i]
            
        #print "Created CCR with %s samples." % size
        ccr_xml, ccr_id = python_ccr_creator.CCR_gen(name, date_of_birth, x)
        ccr_xml += '\n<common><note>ccr_' + ccr_id + '.xml</note></common>'
        return ccr_xml
    
    def hv_ccr_pump_start(self):
        if self.hv_ccr_pump_runing:
            print "Already running?! We will restart then..."
            self.hv_ccr_pump_reset()
        else:
            threading.Thread(target=self.hv_ccr_pump).start()
    
    def hv_ccr_pump_reset(self):
        #self.hv_ccr_pump_runing = False
        self.hv_ccr_pump_stoped = True
        self.hv_ccr_pump_restart = True
    
    def hv_ccr_pump_stop(self):
        #self.hv_ccr_pump_runing = False
        self.hv_ccr_pump_stoped = True
        self.hv_ccr_pump_restart = False
        
    # Threading related functions:
    def hv_ccr_pump(self):
        if(self.hv_ccr_pump_runing): 
            print "This should never happen!"
            return True
        else: print "Ccr_pump is starting..."
        if(self.hvconn == None):
            print "hvconn = None! we will try again later..."
            self.hv_ccr_pump_start()
            return False
        
        #initializing flags
        self.hv_ccr_pump_runing = True
        self.hv_ccr_pump_restart = False
        tx_interval = int(SettingsBase.get_setting(self, "tx_interval"))
        
        personaldemographic = "92ba621e-66b3-4a01-bd73-74844aed4f5b"
        ccr = "1e1ccbfc-a55d-4d91-8940-fa2fbf73c195"
        
        response_str = self.hvconn.getBasicThing(personaldemographic)
        
        dom = minidom.parseString(response_str)
        
        node = dom.getElementsByTagName("full")
        name = node.pop().firstChild.nodeValue    
        
        try:
            node = dom.getElementsByTagName("y")
            year = node.pop().firstChild.nodeValue
            
            node = dom.getElementsByTagName("m")
            month = node.pop().firstChild.nodeValue
            
            node = dom.getElementsByTagName("d")
            day = node.pop().firstChild.nodeValue
            
            date_of_birth = '%s-%s-%s' % (year, month, day)
        except:
            date_of_birth = 'unknown'
        
        self.hv_ccr_pump_stoped = False
        while self.hv_ccr_pump_stoped==False:#self.hv_ccr_pump_runing:
            time.sleep(tx_interval)
            
            ccr_res = self.Channels_to_CCR(name, date_of_birth)
            if ccr_res != False:
                ccr_xml = ccr_res
                response_str = self.hvconn.putBasicThing(ccr, ccr_xml)
                print response_str
        self.hv_ccr_pump_runing = False
        
        if self.hv_ccr_pump_restart:
            print 'ccr_pump is reseting...'
            self.hv_ccr_pump_start()
        else: print 'ccr_pump is stoping...'
        return True
    
    def run(self):
        """run when our device driver thread is started"""
        self.sd = None
        '''/
        import serial
        self.sd = serial.Serial(
           0,                            #port number
           baudrate=115200,              #baudrate
           bytesize=serial.EIGHTBITS,    #number of databits
           parity=serial.PARITY_NONE,    #enable parity checking
           stopbits=serial.STOPBITS_ONE, #number of stopbits
           timeout=3,                    #set a timeout value
           xonxoff=0,                    #enable software flow control
           rtscts=0,                     #enable RTS/CTS flow control
        )
        '''
        
        try:
            fd = None
            fd = open(path + 'id_secret_token.txt', 'r+')
            id = fd.readline()
            secret = fd.readline()
            token = fd.readline()
            fd.close()
            self.hvconn = HealthVaultConn(path, id, secret, token)
        except:
            traceback.print_exc()
            if fd != None: fd.close()
            self.hvconn = None
        
        ip = SettingsBase.get_setting(self, "server_ip")
        port = int(SettingsBase.get_setting(self, "server_port"))
        server = 'wsgiref'
        run_itty(server, ip, port)
             
# internal functions & classes
    def get_properties(self):
        cm = self.__core.get_service("channel_manager")
        cd = cm.channel_database_get()
        return cd.channel_list()
Example #21
0
def create_connection(wctoken=None, record_id=None, **kwargs):
    """Shortcut to create a HealthVaultConn instance.

    HealthVault configuration parameters can be passed in but default to those
    defined in the project settings. The `wctoken` authenticates this
    connection to retrieve data for a specific user. If the `record_id` of the
    corresponding user is known, it can be passed in to save a network call to
    look up the `record_id`.

    The `sharedsec` and `auth_token` generated by a HealthVaultConn are cached
    to be used again in future connections.

    If HealthVaultConn raises a ValueError, this is caught and an
    :py:exc:`django.core.exceptions.ImproperlyConfigured` exception is thrown
    in its place. Other exceptions thrown by HealthVaultConn are propagated.

    :raises: :py:exc:`django.core.exceptions.ImproperlyConfigured` if settings
        are unspecified, null/blank, or incorrect.
    """
    global sharedsec, auth_token

    # Default configuration parameters from the settings.
    config = {
        'app_id': get_setting('HEALTHVAULT_APP_ID'),
        'app_thumbprint': get_setting('HEALTHVAULT_THUMBPRINT'),
        'public_key': get_setting('HEALTHVAULT_PUBLIC_KEY'),
        'private_key': get_setting('HEALTHVAULT_PRIVATE_KEY'),
        'server': get_setting('HEALTHVAULT_SERVER'),
        'shell_server': get_setting('HEALTHVAULT_SHELL_SERVER'),
    }
    config.update(kwargs)

    # Require that configuration parameters be non-null.
    for key, value in config.items():
        if not value:
            msg = '{0} cannot be null, and must be explicitly ' \
                    'specified or set in your Django settings.'.format(key)
            raise ImproperlyConfigured(msg)

    # Since sharedsec and auth_token go together, reset them if both aren't
    # present.
    if sharedsec and auth_token:
        config['sharedsec'] = sharedsec
        config['auth_token'] = auth_token
    else:
        shared_secret = None
        auth_token = None

    try:
        conn = HealthVaultConn(wctoken=wctoken, record_id=record_id, **config)
    except ValueError as e:
        logger.error(e)
        msg = e.args[0] if e.args else None
        raise ImproperlyConfigured(
            'Public and private keys should be long values: {0}'.format(msg))
    except HealthVaultException as e:
        # We must reset sharedsec and auth_token in the case that the ones we
        # have are expired or invalid and can't be reused.
        sharedsec = None
        auth_token = None
        logger.error(e)
        raise e

    # Save the sharedsec and auth_token for future use.
    sharedsec = conn.sharedsec
    auth_token = conn.auth_token

    return conn