star This is a sample chapter from a free eBook I am co-authoring with Cory G. Stevenson, Data Solution Architect & Data Scientist with Microsoft.
The eBook is based upon the HL7 FHIR on Azure Device Framework from the HL7 FHIR on Azure eBook available here Downlaod


Recently we were brought in to design and develop an IoT solution for an Medical Device manufacturer. Their devices are used through out the world.

Business Requirements

The Software Update Service is to be one of several Microservices that will comprise the complete IoT System. These services include Provisioning, Management, Logging, Analysis, Monitoring and Security

INFO: The chapter before this one, is about Configuring our Azure Cosmos DB Data Repository for HL7 FHIR Resources.

Functional Requirements

  • The service would support an Multi-Tenancy Architecture.
  • Ability to have the software updates as close as possible to their customers Medical Device System (MDS), Virtual Medical Device (VMD) or a Channel.
  • A Form-Post from a web application will be used to send the software update file, along with metadata to the Software Update Service.
  • All Device Data was to be stored as HL7 FHIR Resources.
  • All data must be encrypted at Rest and Intransit.

NOTE: There are three HL7 FHIR Medical Device Resources: Device, DeviceMetric, and DeviceComponent.

In FHIR, the “Device” is the “administrative” resource for the device (it does not change much and has manufacturer information etc.), whereas the DeviceComponent and DeviceMetric (which is really a kind of DeviceComponent) model the physical part, including operation status and is much more volatile.

The physical composition of a Device is done by the DeviceComponents pointing to their “parent” component using DeviceComponent.parent. All components point to the “logical” Device they belong to, using DeviceComponent.source.

HL7 FHIR has a REST API. The API is hosted in an Azure Web Application. It can be used by Practitioners and Healthcare EHR systems to query the Device Resources.

Solution

INFO: Device, DeviceMetric, DeviceComponent documents have been created from the Device was Provisioned.

We decided to create an Azure Microservice for the complete Software Update Service. This would provide support for multi-tenancy.

  • An Azure Function App would receive the software update from a Form-Data POST.
  • An Azure Durable Function would send the software update to the Medical Device System (MDS), Virtual Medical Device (VMD) or a Channel.
  • Azure Cosmos DB SQL API would be used as an HL7 FHIR Server.
  • Azure Cosmos DB would be used to store the software update file as an Document Attachment to the FHIR DeviceComponent Resource.
  • The Software Update files would be stored in Azure Content Delivery Network (CDN) using Azure Blob Storage. The files will be cached at physical nodes in the United States, Europe, Asia, Australia, and South America.
  • Our Cosmos DB Database Account will use Global Distribution to the regions in the United States, Europe, Asia, Australia, and South America.
  • All the Azure Services support data encryption both at Rest and Intransit.

INFO: The setup and configuration of the HL7 FHIR on Azure Cosmos DB, along with the HL7 FHIR Rest Api is outside the scope of the solution.

Architecture

Posting Device Software Update to HL7 FHIR Server (Azure Cosmos DB)

Form-Data


Steps

  1. Web App does a Form-Data POST to Function App.
  2. Function App Inserts Software Update file in Azure Blob Storage.
  3. Function App updates HL7 FHIR DeviceComponent Resource (document).
  4. Function App returns Response to Web App.

FormData Function App

Source Code


#region

using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using HttpMultipartParser;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.WindowsAzure.Storage;
using Attachment = Microsoft.Azure.Documents.Attachment;

#endregion

namespace CosmosDBFormData
{
    public static class FormData
    {
        private static readonly string Endpoint = ConfigurationManager.AppSettings["endpoint"];
        private static readonly string AuthKey = ConfigurationManager.AppSettings["authKey"];
        private static readonly string Database = ConfigurationManager.AppSettings["database"];
        private static readonly string Collection = ConfigurationManager.AppSettings["collection"];
    
        private static readonly string ConnectionString = ConfigurationManager.AppSettings["storageConnectionString"];
        private static readonly string BlobContainer = ConfigurationManager.AppSettings["blobContainer"];
        private static readonly string CdnUrl = ConfigurationManager.AppSettings["cdnUrl"];

        private static readonly DocumentClient Client = new DocumentClient(new Uri(Endpoint), AuthKey,
            new ConnectionPolicy
            {
                ConnectionMode = ConnectionMode.Direct,
                ConnectionProtocol = Protocol.Tcp
            }
        );
        

        [FunctionName("FormData")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            HttpRequestMessage req, TraceWriter log)
        {
        
            var storageAccount = CloudStorageAccount.Parse(ConnectionString);
            var cloudBlobClient = storageAccount.CreateCloudBlobClient();
            var cloudBlobContainer = cloudBlobClient.GetContainerReference(BlobContainer);
            var data = req.Content.ReadAsStreamAsync();
            var parser = new MultipartFormDataParser(data.Result);
            var deviceId = parser.GetParameterValue("DeviceId");
            var file = parser.Files.FirstOrDefault();
            
            if (file == null)
            {
            
                return req.CreateErrorResponse(HttpStatusCode.BadRequest, "The Attachment File is missing");
            }

            var fileName = file.FileName;
            var attachment = file.Data;
            var feedOptions = new FeedOptions {MaxItemCount = 1};

            try
            {
                // Get the DeviceComponent document
                var doc = Client.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri(Database, Collection),
                    $"SELECT * FROM d WHERE d.resourceType = \'DeviceComponent\' AND d.source.reference = \' Device/\'{deviceId}", feedOptions);

                Document d = doc.FirstOrDefault();

                try
                {
                    var cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);

                    try
                    {
                        await cloudBlockBlob.UploadFromStreamAsync(attachment);
                    }
                    catch (StorageException ex)
                    {
                        return req.CreateErrorResponse(HttpStatusCode.NotFound, ex.Message);
                    }
                    try
                    {
                        await Client.CreateAttachmentAsync(d.Id, new Attachment
                        {
                            Id = fileName,
                            ContentType = file.ContentType,
                            MediaLink = $"{CdnUrl}/{fileName}"
                        });
                        try
                        {
                            var update = await Client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(Database, Collection), d);

                            return req.CreateResponse(HttpStatusCode.OK,update.Resource.Id);
                        }
                        catch (DocumentClientException ex)
                        {
                            var statusCode = ex.StatusCode;
                            return req.CreateErrorResponse((HttpStatusCode) statusCode, ex.Message);
                        }
                    }
                    catch (DocumentClientException ex)
                    {
                        var statusCode = ex.StatusCode;
                        return req.CreateErrorResponse((HttpStatusCode) statusCode, ex.Message);
                    }
                }
                catch (DocumentClientException ex)
                {
                    var statusCode = ex.StatusCode;
                    return req.CreateErrorResponse((HttpStatusCode) statusCode, ex.Message);
                }
            }
            catch (DocumentClientException ex)
            {
                var statusCode = ex.StatusCode;
                return req.CreateErrorResponse((HttpStatusCode) statusCode, ex.Message);
            }
        }
    }
}

HL7 FHIR Resources for Medical Devices

Device Resource Document Template

{
  "resourceType" : "Device",
  // from Resource: id, meta, implicitRules, and language
  // from DomainResource: text, contained, extension, and modifierExtension
  "identifier" : [{ Identifier }], // Instance identifier
  "udi" : { // Unique Device Identifier (UDI) Barcode string
    "deviceIdentifier" : "<string>", // Mandatory fixed portion of UDI
    "name" : "<string>", // Device Name as appears on UDI label
    "jurisdiction" : "<uri>", // Regional UDI authority
    "carrierHRF" : "<string>", // UDI Human Readable Barcode String
    "carrierAIDC" : "<base64Binary>", // UDI Machine Readable Barcode String
    "issuer" : "<uri>", // UDI Issuing Organization
    "entryType" : "<code>" // barcode | rfid | manual +
  },
  "status" : "<code>", // active | inactive | entered-in-error | unknown
  "type" : { CodeableConcept }, // What kind of device this is
  "lotNumber" : "<string>", // Lot number of manufacture
  "manufacturer" : "<string>", // Name of device manufacturer
  "manufactureDate" : "<dateTime>", // Date when the device was made
  "expirationDate" : "<dateTime>", // Date and time of expiry of this device (if applicable)
  "model" : "<string>", // Model id assigned by the manufacturer
  "version" : "<string>", // Version number (i.e. software)
  "patient" : { Reference(Patient) }, // Patient to whom Device is affixed
  "owner" : { Reference(Organization) }, // Organization responsible for device
  "contact" : [{ ContactPoint }], // Details for human/organization for support
  "location" : { Reference(Location) }, // Where the resource is found
  "url" : "<uri>", // Network address to contact device
  "note" : [{ Annotation }], // Device notes and comments
  "safety" : [{ CodeableConcept }] // Safety Characteristics of Device
}

Device Component Document Template

{
  "resourceType" : "DeviceComponent",
  // from Resource: id, meta, implicitRules, and language
  // from DomainResource: text, contained, extension, and modifierExtension
  "identifier" : { Identifier }, // R!  Instance id assigned by the software stack
  "type" : { CodeableConcept }, // R!  What kind of component it is
  "lastSystemChange" : "<instant>", // Recent system change timestamp
  "source" : { Reference(Device) }, // Top-level device resource link
  "parent" : { Reference(DeviceComponent) }, // Parent resource link
  "operationalStatus" : [{ CodeableConcept }], // Current operational status of the component, for example On, Off or Standby
  "parameterGroup" : { CodeableConcept }, // Current supported parameter group
  "measurementPrinciple" : "<code>", // other | chemical | electrical | impedance | nuclear | optical | thermal | biological | mechanical | acoustical | manual+
  "productionSpecification" : [{ // Specification details such as Component Revisions, or Serial Numbers
    "specType" : { CodeableConcept }, // Type or kind of production specification, for example serial number or software revision
    "componentId" : { Identifier }, // Internal component unique identification
    "productionSpec" : "<string>" // A printable string defining the component
  }],
  "languageCode" : { CodeableConcept } // Language code for the human-readable text strings produced by the device
}

Device Metric Document Template

{
  "resourceType" : "DeviceMetric",
  // from Resource: id, meta, implicitRules, and language
  // from DomainResource: text, contained, extension, and modifierExtension
  "identifier" : { Identifier }, // R!  Unique identifier of this DeviceMetric
  "type" : { CodeableConcept }, // R!  Identity of metric, for example Heart Rate or PEEP Setting
  "unit" : { CodeableConcept }, // Unit of Measure for the Metric
  "source" : { Reference(Device) }, // Describes the link to the source Device
  "parent" : { Reference(DeviceComponent) }, // Describes the link to the parent DeviceComponent
  "operationalStatus" : "<code>", // on | off | standby | entered-in-error
  "color" : "<code>", // black | red | green | yellow | blue | magenta | cyan | white
  "category" : "<code>", // R!  measurement | setting | calculation | unspecified
  "measurementPeriod" : { Timing }, // Describes the measurement repetition time
  "calibration" : [{ // Describes the calibrations that have been performed or that are required to be performed
    "type" : "<code>", // unspecified | offset | gain | two-point
    "state" : "<code>", // not-calibrated | calibration-required | calibrated | unspecified
    "time" : "<instant>" // Describes the time last calibration has been performed
  }]
}

Summary

  • You have seen how easy it is to use an Azure Function App to receive a Form-Post.
  • You have learned how to save the Software Update file to CDN as an Cosmos DB Document Attachment.

Next Step

  • You will see how we used Azure Durable Functions to publish the Software Updates to the Azure IoT Hubs.