Using the AzureSphere, I have created the KegMaster to secure the homebrew beer in my Keg Freezer (Keezer). The system allows me to track quantities, to set, monitor, and maintain CO2 pressure in multiple kegs, convey information about the available beverages to users via the KegMaster app, as well as control and measure flow of beverages from each keg.
Story/Background:When tasked with a project that suggested that I “Secure Everything” I had to consider what was most important to me. I considered many different aspects of my life that might benefit from some additional security. Ultimately, I decided that as a homebrewer, I needed a way to best secure and manage my beer supply. I have been using a very basic Keg Freezer (Keezer) for about a year, but I have encountered a few problems I aimed to address with this project.
First, I never knew how much of each beer remained in the kegs. I could estimate, of course, but it always left something to be desired. Second, I had a single CO2 tank to move from keg to keg, and trying to maintain perfect, constant pressure in all of my kegs was nearly impossible. Third, when I have visitors, I often find myself standing watch over my Keezer to tell them about each kind of beer that was available to them, and which keg contained which beer. Fourth, when friends or groups came over, I had no way to monitor their access to the various beverages. When they brought their kids or teens with them, I had no way to control their access to my free-flowing beer.
This project aims to address each of these problems in a holistic, streamlined way. Through the development of the KegMaster, I have enabled myself to monitor the number of pints remaining in each keg. I can even set the number of pints to “reserve” for myself (or for the future), ensuring I always know when my beer supply is running low. Additionally, I am able to set a date in the future when the keg will become accessible - allowing me to age beers without fear of giving my guests access to sub-optimal beverages.
Also, I am able to set a desired CO2 pressure and enable the Azure Sphere to turn the CO2 off and on as needed to maintain that desired level of pressure in each keg.
With the completion of Keg Master version 1.0, guests will now be able to access data about each tap and what it contains. This allows them to see the name, style, description, ABV, IBU, etc… all the information they might need to make an educated decision about their beverage selection.
Finally, the ability to turn taps on and off will allow me better control over who is accessing what taps. Ultimately, the KegMaster will have user profiles to enable minors to pour non-alcoholic beverages like soda and kombucha without giving them access to beer or hard cider. But for now, I still have the ability to control each tap remotely.
When combined, these features provide me with peace of mind, knowing that each of my guests will have an optimal beverage experience, that my beer supply is safe from unauthorized access, and that I have “Secured Everything” within the Keg Master.
Useful LinksSoftware
- KegMaster Azure Sphere App
- KegMaster Satellite App
- KegMaster Xamarin App
- KegMaster Azure Function
- KegMaster Azure App Service
Hardware
Helpful Tutorials
User Manuals and Datasheets
- MT3620 - Azure Sphere Development Board
- PICkit 4 In Circuit Programmer
- PIC18f14K50 MCU Datasheet
- WS2812b (NeoPixel) LED Driver
- HX711 - Load Cell Amplifier and ADC
One of Azure Sphere’s biggest strengths is with seamless integration into Microsoft’s extensive ecosystem of web services. This has been leveraged as some of the core functionality of the Keg Master. Being connected to Azure Web Services opens up opportunities otherwise not afforded to an embedded device. Additionally, the turn-key security offered by the Azure Sphere provides confidence that all of my connected devices are secure, even my home-brew.
Using these services, the KegMaster App allows authenticated users to access a SQL database of Keg information, displaying information in a friendly graphical format. Users that have been designated as ‘Admin’ may also change Keg information by adding or removing kegs, updating their titles and descriptions, enabling or disabling pouring, and adjusting the desired CO2 pressure. Also available to Admin's are more advanced settings such as configuring the availability date (at which time the tap will automatically be enabled) allowing sampling, and setting pour quantities. These are useful for beverages that need to condition in the Keg for some time or require specific pour sizes for optimum and responsible refreshment.
Various data are periodically refreshed by the Azure Sphere and updates pushed if the value has significantly changed. As may be intuitive from the section above, these fields include keg quantity remaining and current pressure. One of the updates that may be less obvious has to do with automatically enabling a tap, based on pre-configured availability date. Automatic tap enablement will also trigger an alert to the user, letting them know which beverage has just become available.
Technical Overview:
The Azure Sphere integrates well with Azure web services, which is something this project uses extensively. For ease of explanation, a flow chart has been created for you to reference.
Starting with the user experience, a guest will need to authenticate via Azure Active Directory to gain access to the KegMaster. Once authenticated, the Xamarin App will query for Kegs via the Azure App Service. Once loaded, an "Admin" user may modify and update keg data. If confirmed, processing of these changes is handed off to the cloud-based Azure Functions. Processing at this level allows ease of dispatching messages to update both the SQL database and to the KegMaster Dispensing System, via the Azure IoTHub to which it is connected.
From the perspective of the KegMaster Dispensing System, a connection is made to the Azure Functions via the Azure IoTHub. Through this, keg data is queried. Once obtained it will set the output control state of the KegMaster, for liquid and gas valves, as well as LEDs. Changes to this control-state will be made when events are received via the Azure Function. All keg data is also periodically polled, to avoid the chance of it becoming out of sync due to a server or system error. Data, such as the current pressure and estimated quantity available are also periodically read from the hardware, and required updates are sent to the SQL database using Azure Functions. For this, IoT Hub message transmission has been optimized to only sending updates if changes to these data are greater than a predetermined threshold.
Certain events will trigger a message from the Azure Function to the user via the Xamarin Mobile App, via its connection to the Azure Notification Hub. For example, when the Azure Sphere automatically enables a tap is based on it’s preset availability date, the user will receive a message.
Software OverviewThe system design utilizes a mixture of firm real-time, soft real-time, and event driven components. Many real-time aspects are offloaded onto the PIC microcontroller. These are things such as reacting to sensor input, maintaining tight tolerances required by the WS2812b LED drivers, sensing changes to input pins, and achieving desired output duty-cycles. Soft real-time components are handled by the Azure Sphere, where periodic processing ensures a responsive system and positive user experience.
The Azure Sphere also manages a connection with the Azure IoT Hub, the interface for reception and transmission of asynchronous messages driving data update and control output. These functions are described with more detail in the following sections.
Azure Sphere Application
The Azure sphere has three main tasks, receiving and updating keg database information, setting the control state of the KegMaster Dispensing System, as well as reading and acting on hardware sensor input. These are similarly separated into three conceptual groups, maintaining a connection to the IoT Hub, fetching keg data, and processing the current keg state. Each keg contains information that drives control valves for liquid and gas. Sensor input for each keg is also read and then either incorporated into the control state and / or sent back to Azure web services to update the keg database.
Each keg is processed within its own thread. Semaphores are used to protect access to data and hardware limited resources such as I2C. Keg data is processed at a real-time periodic rate using built-in time functionality. These features are aided by various POSIX compliant interfaces provided by the Azure Sphere OS. See the software requirements section for additional detail about what the Azure Sphere controls.
Satellite PIC Application
Each PIC MCU manages hardware interface for a different keg. This oversight includes GPIO to actuate valves, interrupt on change pins to log data from the flow meter, logging and initiating ADC readings for the pressure sensor, reading data from the external HX711 24-bit ADC for the load-cell within the scale, and control output for the WS2812b LED driver.
To improve overall system safety and security, a configurable dwell time is used to control how long a liquid or gas valve will remain open. This was implemented to help make the system resilient to loss of connection with the main controller and maintain security against attempts at physical intrusion.
Interface and Control Documentation
- Each PIC shall have a base address of 0x08.
- Each PIC has two resistors, R20 and R22 on the PCB, to set the address offset. These shall be read as a two bit number (0-3) with R20 as the LSB.
- The following messages shall be defined for communication. If a response is indicated, the same format shall be used for both Tx and Rx. Pin ID’s may be found on the schematic within the Satellite PIC repository (or attached to this project).
- Each message shall be terminated with a 16-bit sequence, 0x04FF. NOTE: This was intended for the ability to send multiple messages in one transmission, however, this feature is untested. Messages without this terminator will be ignored.
Azure Functions
Written in C#, using the.NET framework, Azure functions are the glue that binds the system together. Referring back to the Technical Overview, Azure Functions negotiate SQL transactions for both data Selections and Updates for all small transactions (the Azure App Service is used by the Xamarin App for selecting whole rows). Additional processing has been added for data transactions from the Xamarin Application, which will forward updates both to the SQL database and to the Azure Sphere.
Hooks have also been added for when the ‘Alerts’ field is updated, such that whenever an update occurs to this field a notification will also be sent to the Xamarin Application. So far this is only used for when a becomes available based on the configured availability date. Though, any updates to the ‘Alert’ field by the Azure Sphere will be pushed as an alert, so adding new alerts should be relatively straight forward.
Xamarin Mobile Application
Written in C#, the Xamarin application provides the user interface to the Keg Master. This application highly leverages Azure Web services and serves as a conduit for users to view and update keg data. See the Software requirements for further detail.
Azure App Service
Written in C#, using the.NET framework this simple interface enables the Xamarin application to efficiently and safely query and update SQL data. See the software requirements section for additional details.
System and Software RequirementsQuantity Tracking:
The KegMaster shall be capable of:
- Directly determining the quantity of beverage remaining within a Keg (in Pints).
Pressure Maintenance System:
The KegMaster shall be capable of:
- Measuring the current pressure inside of a Keg (in PSI).
- Activation of an actuator to increase CO2 pressure within a keg, according to a user-set control value.
Flow Control and Measurement:
The KegMaster shall be capable of:
- Dispensing quantities of beverage according to a user-set control value.
- Dispensing samples of beverage according to a user-set control value.NOTE: This is applicable when pouring is otherwise disabled.
- Control a liquid valve to enable or disable beverage dispensing, according to a user-set control value.
- Automatically enabling beverage dispensing on a user-set control value (date).
- Alerting users of beverage becoming available.
- Disable pouring when the estimated beverage quantity drops into a user-set control ("reserve") value.
User, Information, Control, and Display:
For each keg, the KegMaster shall be capable of:
- Adding new kegs to the system, for processing and control.
- Removing kegs from the system.
- Display of the following information: - Beverage quantity remaining in the keg. - Current pressure within the keg.
- Display and update of the following information: - Name of the beverage within the keg. - Style of the beverage within the keg. - Description of the beverage within the keg. - Date the keg was added to the KegMaster.
- Display and update of the following control-values: - Date the keg will become available. - Sample quantity (in ounces). - Quantity to reserve (pints). - Desired pressure (PSI). - Enable and disable beverage dispensing. - Enable and disable keg CO2 pressurization.
This project makes use of quite a few technologies that I was previously unfamiliar with (Azure, C#,.NET Framework, Xamarin Studio, App Development, Web services, etc.). As such, example projects and getting started guides were used extensively. For the most part these projects were used for reference only, however, some of these features didn’t make sense for me to reimplement at this time.
In addition to standard C libraries, NuGet Packages used by the Xamarin Mobile Application, and the Azure Sphere SDK 1902, functionality provided via the software resources included as a library includes the following:
- Avnet Azure Sphere Samples - Module used to make and maintain connection with Azure IoT Hub
- Microsoft Azure Sphere Samples - Used as a basis for I2C communication. I need to verify, but I think this library is no longer required.
Software and other deliverables produced for this project are identified by their repository listed below and are configuration identified with the git tag listed.
KegMaster software for Azure Sphere
- https://gitlab.johngrenard.com/JohnGrenard/kegmaster_embedded
- https://github.com/Le-Grenadier/KegMaster_Embedded
- Git Tag: production/1.00
KegMaster software for satellite PIC MCU
- https://gitlab.johngrenard.com/JohnGrenard/kegmaster_satellite
- https://github.com/Le-Grenadier/KegMaster_Satellite
- Git Tag: production/1.00
KegMaster software for Xamarin Phone Application
- https://gitlab.johngrenard.com/JohnGrenard/kegmaster_xamarinapp
- https://github.com/Le-Grenadier/KegMaster_XamarinApp
- Git Tag: production/1.00
Azure App Service
- https://gitlab.johngrenard.com/JohnGrenard/kegmaster_appservice
- https://github.com/Le-Grenadier/KegMaster_AppService
- Git Tag: production/1.00
Azure Function
- https://gitlab.johngrenard.com/JohnGrenard/kegmaster_azurefunctions
- https://github.com/Le-Grenadier/KegMaster_AzureFunctions
- Git Tag: production/1.00
Keg Scale STL Model file
- https://gitlab.johngrenard.com/JohnGrenard/kegmaster_scale
- https://github.com/Le-Grenadier/KegMaster_Scale
- Git Tag: production/1.00
Azure Web Services:
Azure Web Services are the backbone of this project. They serve to mediate communication between the Azure Sphere, SQL Database, and the Xamarin Mobile Application. For a detailed overview of how these are used, please refer to the System Overview and Software Overview sections of this document.
IoT Hub / Connecting Azure Sphere
The IoT Hub is a gateway for the Azure Sphere to the ecosystem that is Azure Web Services. There are many great tutorials online already about how to setup the Azure Sphere, so rather than try and compete with these, I will link to a few of my favorite tutorials on getting started with the Azure Sphere and Azure IoT Hub.
- https://www.hackster.io/news/getting-started-with-microsoft-s-azure-sphere-875f1690ebcf
- https://docs.microsoft.com/en-us/azure/iot-dps/tutorial-provision-device-to-hub
- https://docs.microsoft.com/en-us/azure-sphere/app-development/setup-iot-hub
Set-up Azure AD
The Azure Active Directory (Azure AD) is the first line of defense for the Xamarin Application. Once a user has authenticated with the Azure Active Directory they will have full view of KegMaster data within the SQL database. I have added another line of defense however, even an authenticated user will need to be granted "Admin" permissions by the Azure AD owner prior to being able to modify KegMaster Settings. This will be discussed in further detail below.
I followed a great tutorial when creating the Azure AD, so rather than compete, I will link to the instructions that I followed.
After following the tutorials, take note of the following information for use when setting up the Xamarin Application.
- Azure B2C Tenant URL
- Azure B2C Tenant Host URL
- Client ID
- SignUpSignIn Policy Name
- Edit Profile Policy Name
- Reset Password Policy Name
For Example my connection strings and profiles were as follows (With slight modification for security):
- AADJohnG.onmicrosoft.com
- AADJohnG.b2clogin.com
- a123b45c-1a2b-12b3-1a2b-a1b234cde56f
- b2c_1_signupsignin1
- b2c_1_profileediting1
- B2c_1_passwordreset1
Most of these data may be found in the “User Flows” section under your newly created Azure AD.
The Application ID will be listed under your newly registered application.
Create Azure App Service
The Azure App service will be a foundational method of querying data from the SQL database by the Xamarin Mobile Application. As an added benefit, creation of this app service will also trigger creation of the database. Changes to the base tutorial here were minimal, mostly in specification of the data required. Additionally, much of the effort here will be managed by Microsoft’s Azure App Service publishing framework. I will link to the tutorial I followed/modified, but the steps required should be even more straightforward than that, so be sure to keep reading this section completely before continuing.
Once you have cloned the KegMaster_AppService (linked in the lifecycle data section above), open the solution, right click on the project, and select ‘Publish’.
From there you will choose to ‘create a new app service’.
Follow the proceeding instructions, and take note of the ‘Application URL’. For example mine was as follows:
Once it has been created, navigate to the the new SQL database page via portal.azure.com and make note of the SQL DB Connection String. For reference, a partial screenshot of mine is below.
Create Notification Hub
The Keg Master uses an Azure Notification Hub for one-way asynchronous communications with the user. That is to say, it will send pop-up notifications. The code for this has been included as part of other Keg Master repositories. As such, the only setup involved is in the creation and registering the Hub for your platform. After this, we will provide the Azure Function and Xamarin Mobile Application with a connection string. Providing these connection strings is not unlike giving someone a phone number, so that they know who to call.
Microsoft provides some great instructions for setting up the Hub for your platform. In order to not compete with these great instructions, and to help keep these instructions short, I will provide a link to those. (NOTE: My understanding is that the Simulator is unable to register with notification HUB, this is a hardware only feature. Additionally, I don’t currently have a good way to test Android devices, so I was unable to set-up the Notification Hub connection for Android at this time.)
- iOS: https://docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-ios-push-notification-apns-get-started
- Android: (See NOTE above): https://docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm
After setting up this service you will need to take note of the ‘Notification Hub Connection string’ for use when setting up the Azure Functions and the Xamarin Mobile Application. As I understand, it is advisable to use the ‘Listen’ profile unless you’re confident the ‘Full’ profile is needed for your application.
Create Azure functions
Azure Functions are the glue that binds everything together. They mediate data between other services as well as the Xamarin Application and Azure Sphere. Microsoft’s framework for publishing functions should help make this fairly painless. The only point of confusion I see here will be configuring the ‘connection strings’, which took me a little while to begin to understand.
Here’s a link to a pretty good tutorial on Azure Functions, but what we’ll be doing here is a little more complex under the hood.
https://tutorials.visualstudio.com/first-azure-function/publish
Once you have cloned the KegMaster_AzureFunctions repository, open the solution and publish the project in the same way as for the Azure Application Service. Once published you will be able to select a new ‘function’ service on portal.azure.com, which should look something like this:
From here select ‘configuration’, this will take us to a page where we will be adding a few of the settings we noted earlier. Add the following connection strings: “device_endpoint”, “KegMaster_NotificationHubEndpoint”, and “sqldb_connection”. These are referenced by the KegMaster Functions via the GetEnvironmentVariable() call.
Azure Sphere
After cloning the KegMaster_Embedded repository listed in the ‘Lifecycle Data’ section, configure the ‘MY_CONNECTION_STRING” setting to be your Iot Hub Connection string, which should be something along the lines of
- HostName=KegMasterIotHub.azure-devices.net;DeviceId=KegMaster;SharedAccessKey=..................
You will also need to configure the same URL in the app_mainifest.json file, in order to allow access to this external URL.
At this point you should be able to program the Azure Sphere and have it query for new kegs in the SQL database.
PIC Microcontroller
* A PCB should be ordered and assembled prior to continuing with the following instructions.
After cloning the KegMaster_Satellite repository (listed in the ‘Lifecycle Data’ section above), installing MPLAB X, and the XC 8 compiler you should be able to program the assembled PIC Satellite PCB using the PICkit 4 device.
Quantity Tracking
For this step it will be required to have 3-D printed the Scale Model located above in the KegMaster_Scale repository listed in the ‘Lifecycle Data’ section above. Assemble the keg scale as shown in the pictures above, taking special care to connect the wires as shown.
You will be able to see the wire connections from the pictures above. For the scale to work, connect white wires 'across', black wires 'at a diagonal' and red wires to the board as shown. A channel is provided in the 3-D printed STL file to route wiring for the external connection, starting from VCC, these should be connected ‘red, green, blue, black’ or equivalent, according to your wire colors.h
After assembly, it's a good idea to wash the boards. Flux is usually conductive, and can significantly impact readings from the sensitive HX711 amplifier. Be sure to let them completely dry before use.
CO2 Pressure Maintenance System
The pressure control system consists of a pneumatic actuator, pressure sensor and connections from the CO2 tank to the keg. The layout above demonstrates how these should be assembled. The left most barb fitting should be connected to the CO2. The black tube connected to the left actuator may be replaced with a plug if only one keg pressure system is desired. Otherwise, this pattern may be repeated as many times as desired, with the final actuator containing a plug as previously described.
The second picture depicts final assembly for my configuration.
Flow Control and Measurement
Liquid valves and flow meters should be assembled in a similar manner as depicted in the picture above. Pay special attention to arrows on the bodies of the flow meters and valves to ensure they’re aligned properly with the intended direction of liquid flow.
Conveying information to users
After installing Visual Studio 2019 as well as the Xamarin SDK, download and open the KegMaster_XamarinApp repository listed in the ‘Lifecycle Data’ section above. Update the following connection strings with the settings noted while setting up the Azure Web Services above:
After these settings are configured for your application, you should be able to compile and run the Xamarin Application. However to allow configuration of your kegs, you must make your user an ‘admin’ by setting their ‘Job Title’ to ‘Admin’ within user-settings page of your web-portal to your Azure Active Directory. This is more or less a hack, since I couldn’t find a better way of doing this. It seems that a paid subscription may be required for a better solution.
Final Assembly
We’re almost there! We should now have a working Xamarin Application, Azure application, as well as a bunch of sensors and control valves that need to be connected. These connections may be made according to the following diagram. Use the 12v and 5v power regulators listed in the BOM according to your needs.
NOTE: Please practice proper safety whenever working with electricity. Especially, though, when working with wall-power, or anything else that isn't considered 'low voltage'.
Working with and learning about the Azure Sphere has been a rewarding experience. I am excited to see the additional 'turn-key' security this product provides and how the industry will adopt this technology.
On a more personal level, getting these features for 'free', on top of the security provided by other Azure services, provide me with extra peace of mind, knowing that my guests will have an optimal beverage experience. This project has been a great learning experience, but more importantly has produced a very capable platform for other technologies I'd like to use.
For Keg Master version 1.0, the two ARM M4 cores weren't utilized. In the future I'd like to experiment with adding more real-time processing, such as speech recognition, or more features for the pour (controlling foam, or adding a 'touch-less auto-pour').
Cloud based processing using Web Services is another aspect I'd like to explore. Associating the Xamarin App's user credentials to the current beverage poured could produce some powerful possibilities. Perhaps it could even make sense to add some machine learning. Maybe, something as simple as facial or speech recognition, natural language process (to accept verbal commands), or similar features could be on the horizon.
In all, I'm pleased with the progress I've been able to make on this project in such a short time, and look forward to the possibilities that are yet available. I'm excited to present the Keg Master as one more step toward a world in which we will Secure Everything!
Comments