Setting up Python in Windows 10

Installing Python under Windows 10 is easy as long as you set up your system environment correctly.

Ready? Here’s your quick guide:

1. Visit the official  Python download page  and grab the Windows installer for the latest version of Python 3. A couple of notes:

  • Python is available in two versions – Python 2 and Python 3. For beginners, that may be confusing. In short, Python 3 is the current and future state of the language; Python 2 is a legacy version that has a large base of users. Python 2 wants to  reach its end of life in January 2020  and will only fix bug till then.
  • By default, the installer provides the 32-bit version. There’s a 64-bit version available. I’m getting stuck with 32-bit for compatibility issues with some older packages.

2. Right-click on the installer and select „Run as Administrator.“ You’ll have two options – choose „Customize Installation.“

3. On the next screen, check all boxes under „Optional Features.“ Click next.

4. Under „Advanced Options,“ set the location where you want to install Python. For ease, I use:

C: \ Python36-32

How to install 32-bit Python 3.6.

Click „Install.“ When the installation finishes, close the installer.

5. Next, set the system’s PATH variable to include directories that include Python components and packages we’ll add later. To do this:

  • Open the Control Panel (easy way: click on the task bar, type „Control Panel,“ then click the icon).
  • In the Control Panel, search for Environment; click Edit the System Environment Variables. Then click the Environment Variables button.
  • In the User Variables section, you want to edit PATH variable or create one. If you’re editing an existing PATH, the values ​​are presented on separate lines in the edit dialog, like this:
C:\Python36-32 
C:\Python36-32\Lib\site-packages\
C:\Python36-32\Scripts\
  • If no PATH variable exists on your system, create one by clicking New. Make PATH the variable name and add the above directories to the variable values section as shown, separated by a semicolon:
C:\Python36-32;C:\Python36-32\Lib\site-packages;C:\Python36-32\Scripts
  • Click OK to close all the Control Panel dialogs.

6. Now, you can open a command prompt (Start Menu > Windows System > Command Prompt) and type:

python

That will load the Python interpreter:

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win 32
Type "help", "copyright", "credits" or license for more information.
>>>

Because of the settings you included in your PATH variable, you can now run this interpreter — and, more important, a script — from any directory on your system.

Type exit() and hit Return to exit the interpreter and get back to a C: prompt.

Optional: Set up useful Python packages

Python 3 comes with the package installer  pip  already in place, Which makes it super easy to add useful packages to your Python installation. The syntax is this (replace  some_package  with a package_name you want to install):

pip install some_package

1. Let’s add a couple of must-have utilities for web scraping:  Requests  and  BeautifulSoup . You can use the install all with one command:

pip install beautifulsoup4 requests

2.  csvkit , which is  covered here , is a great tool for dealing with comma-delimited text files. Add it:

pip install csvkit

You’re now using Python under Windows 10.

Install and configure XAMPP on Windows 10

XAMPP is a free open source software did Provides an easy way for web designers and developers to install The Necessary components to run PHP based software like  WordPress , Drupal, Joomla, and others on Windows, Mac OS X, and Linux.

Apache, MySQL, PHP, and Perl on your computer to create a test environment. XAMPP wants to save you time and frustration.

In this  guide , you’ll learn how to install the XAMPP on your computer running  Windows 10 , how to configure the software, and solve common problems.

Step-by-step guide to install XAMPP:

  1. Download XAMPP from  Apache Friends .

    Download XAMPP for Windows 10

    If you have special version requirements for PHP, then download the version you’re required to install. If you do not have a version requirement, then download the oldest version, it may help you to avoid issues trying to install a PHP based software.

  2. Double-click the file to run the installer.
  3. Click  OK  on the warning to continue.XAMPP warning on Windows
  4. Click  Next .XAMPP setup on Windows 10
  5. XAMPP offers a variety of components that you can install, such as MySQL, phpMyAdmin, PHP, Apache, and more. For the most part, you will want to use most of these components, as it is recommended to leave the default options and click  Next .XAMPP install components
  6. Uncheck the  Learn more about Bitnami for XAMPP  and click  Next .XAMPP installation wizard on Windows 10
  7. Leave the default install location settings or choose another folder to install the software, and click  Next  to begin the installation.XAMPP installation location
  8. During the installation Windows will prompt you to allow certain services to communicate through the firewall. Click Allow access through the firewall for private.XAMPP allow access through Windows Firewall
  9. Click Finish to complete the installation and to start using XAMPP Control Panel.Complete XAMPP installation on Windows 10
  10. Choose your language (English or German), and click Save to complete and open XAMPP Control Panel.XAMPP Control Panel on Windows 10

How to configure XAMPP on Windows 10

The XAMPP Control Panel includes three main sections. In Modules, you will find all the services available. You can run each service by clicking the Start button.

When you start some of the services, including Apache and MySQL, on the right side, you will also see the process ID number and TCP/IP port numbers each service is using. For example, by default Apache uses TCP/IP port 80 and 443, while MySQL uses TCP/IP port 3306.

You can also click the Admin button to get access to the administration dashboard for each service and verify that everything is working correctly.

XAMPP Control Panel

On the right side have a list of buttons to configure various aspects of the control panel, including Config to configure which modules will automatically want to start when you launch XAMPP.

XAMPP Config

Netstart will give you a list of services currently accessing the network, process ID and TCP/IP port information.

XAMPP Netstat

And there are also quick access buttons to open the shell command-line utility, XAMPP install folder, Services, and quick.

Lastly, you get the logs section, where you can get a glance of what happens every time you start a module or change a setting. This is also the first place to look at when something isn’t working.

Apache won't start on Windows 10 error

The default settings should work for most people using XAMPP to create a testing environment to run a website for personal use or a client. However, depending on your setup configuration, you may need to change the TCP/IP port number for the Apache server, the database upload size, or set the password for phpMyAdmin.

To change these settings, you’ll need to use Config button for the corresponding service. For example, you’ll need to open the httpd.conf file to change the settings on the Apache server, and the my.ini file to change the settings for MySQL.

How to fix Apache not starting on XAMPP

The XAMPP installation is very straightforward, but on Windows 10 and other versions of the operating system, sometimes there is a problem that will not allow the Apache server to run.

The issues can be attributed to the World Wide Publishing Service that may be installed and running on port 80 on your Windows PC. Port 80 also happens to be the default TCP/IP port that Apaches uses on XAMPP and no two applications can use the same port in the computer.

You have a few ways to fix the problem as shown below:

Uninstall World Wide Web Services

If you don’t have any applications depending on the World Wide Web Services feature, you can uninstall it using the following steps:

    1. Use the Windows key + X keyboard short to open the Power User menu and select Programs and Features.
    2. Click the Turn Windows features on or off link.Turn Windows features on or off
    3. Expand Internet Information Services and uncheck World Wide Web Services. Here, you can also uncheck FTP Server and Web Management Tools, if you don’t depend on those services.
  1. Click OK.Microsoft IIS - World Wide Web Services
  2. Reboot your computer to complete the task.
  3. Open XAMPP Control Panel and click Start on Apache.

Change the default Apache TCP/IP port

Alternatively, you can configure Apache to run on a different TCP/IP port using the following steps:

  1. One the XAMPP Control Panel, click the Admin button on Apache, and click httpd.conf.
  2. Scroll down and find the line: Listen 80.
  3. Change the 80 for another TCP/IP port number. You can try port 81. After the change the line should read: Listen 81.httpd.conf change TCP/IP port number
  4. Save and close the httpd.conf file.
  5. Click the Start button to run the Apache server.

The only caveat with this configuration change is that you’ll need to append TCP/IP port number on the address every time you want to connect to your website. For example, to access the Apache server on the web browser, you will need to type: localhost:81/dashboard instead of localhost/dashboard.

Manually stop World Wide Web Publishing Service

Another thing you could do is to stop World Wide Web Publishing Service (World Wide Web Services) and change its settings to only start the service manually using the following steps:

  1. Open the Start menu, do a search for Services, and press Enter.
  2. Scroll down, find, and double-click World Wide Web Publishing Service.World Wide Web Publishing Service
  3. Click Stop.
  4. Change the startup type to  manual .
  5. Click  Apply .
  6. Click  OK .Stop and set Manual settings for World Wide Web Publishing Service
  7. On XAMPP Control Panel, click the  Start  button to run the Apache server.

The best way to get Apache working again is by uninstalling the World Wide Web Publishing Service, but if that’s not possible you can change the TPC / IP port number or stop service as necessary.

References – Pureinfotech

Introduction to Microsoft Azure and its Application

Microsoft Azure (formerly Windows Azure) is a cloud computing service created by Microsoft for building, testing, deploying, and managing applications and services through a global network of Microsoft-managed data centers. It provides software as a service (SaaS), platform as a service (PaaS) and infrastructure as a service (IaaS) and supports many different programming languages, tools and frameworks, including both Microsoft-specific and third-party software and systems.

Services –
Microsoft lists over 600 Azure services, of which some are covered below:

Compute

  • Virtual machines, infrastructure as a service (IaaS) allowing users to launch general-purpose Microsoft Windows and Linux virtual machines, as well as preconfigured machines images for popular software packages.
  • App services, platform as a service (PaaS) environment.
  • Web Sites, high density hosting sites that allow developers to build sites using ASP.NET, PHP, Node.js, or Python and can be deployed using FTP, Git, Mercurial, Team Foundation Server or uploaded through the user portal. This feature was announced in preview form at the Microsoft Azure event. [6] Customers can create websites in PHP, ASP.NET, Node.js, or Python, or select from several open source applications from a gallery to deploy. This aspect is one of the services offered by PaaS for the Microsoft Azure Platform. It’s renamed to Web Apps in April 2015.
  • WebJobs, applications that can be deployed to the App Service environment to implement the background processing that can be on schedule, on demand, or run continuously. The Blob, Table and Queue Services can be used to communicate between WebApps and WebJobs and to provide state.

Mobile services

  • Mobile engagement collects real-time analytics that highlight users‘ behavior. It also provides push notifications to mobile devices.
  • HockeyApp can be used to develop, distribute, and beta-test mobile apps.

Storage services

  • Storage Services provides REST and SDK APIs for storing and accessing data on the cloud.
  • Table Service can be read by partition key and primary key. It’s a NoSQL non-relational database.
  • Blob Service provides programs to store unstructured text and binary data as well as HTTP (S) path. Blob service also provides security mechanisms to control access to data.
  • Queue Service lets programs communicate asynchronously by message using queues.
  • File Service allows the storage and access of data on the cloud using the REST APIs or the SMB protocol.

Data management

  • Azure Search provides text search and subset of OData’s structured filters using REST or SDK APIs.
  • Cosmos DB is a NoSQL database service that implements a SQL statement on JSON documents.
  • Redis Cache is a managed implementation of Redis.
  • StorSimple manages storage tasks between on-premises devices and cloud storage.
  • SQL Database, formerly known as SQL Azure Database, works to create, scale and extend applications into the cloud using Microsoft SQL Server technology. It also integrates with Active Directory and Microsoft System Center and Hadoop.
  • SQL Data Warehouse is a data warehousing service designed to handle computational and data intensive queries on datasets exceeding 1TB.
  • Azure Data Factory, is a data integration service that allows creation of data-driven workflows in the cloud for orchestrating and automating data movement and data transformation.
  • Azure Data Lake is a scalable data storage and analytic service for big-data analytics workloads that require developers to run massively parallel queries.
  • Azure HDInsight is a big data relevant service, that deploys Hortonworks Hadoop on Microsoft Azure, and supports the creation of Hadoop clusters using Linux with Ubuntu.
  • Azure Stream Analytics is a serverless scalable event processing engine that enables users to develop and run real-time analytics on multiple streams of data from sources such as devices, sensors, web sites, social media, and other applications.

Messaging
The Microsoft Azure Service Bus allows applications running on Azure premises or off premises devices to communicate with Azure. This helps to build scalable and reliable applications in a service-oriented architecture (SOA). The Azure service bus supports four different types of communication mechanisms:

  • Event Hubs, which provide event and telemetry ingress to the cloud at massive scale, with low latency and high reliability. For example an event hub can be used to track data from cell phones such as a GPS location coordinate in real time.
  • Queues, which allow one-directional communication. A sender application would send the message to the service bus queue, and a receiver would read from the queue. Though there can be multiple readers for the queue only one would process a single message.
  • Topics, which provide one-directional communication using a subscriber pattern. It is similar to a queue, however each subscriber will receive a copy of the message sent to a Topic. Optionally the subscriber can filter out messages based on specific criteria defined by the subscriber.
  • Relays, which provide bi-directional communication. Unlike queues and topics, a relay doesn’t store in-flight messages in its own memory. Instead, it just passes them on to the destination application.

Media services –

A Paas offering that can be used for encoding, content protection, streaming, or analytics.

CDN –

A global content delivery network (CDN) for audio, video, applications, images, and other static files. It can be used to cache static assets of websites geographically closer to users to increase performance. The network can be managed by a REST based HTTP API.

Developer – Application Insights and Visual Studio Team Services

Management –

Azure Automation, provides a way for users to automate the manual, long-running, error-prone, and frequently repeated tasks that are commonly performed in a cloud and enterprise environment. It saves time and increases the reliability of regular administrative tasks and even schedules them to be automatically performed at regular intervals. You can automate processes using runbooks or automate configuration management using Desired State Configuration.

Machine learning

Microsoft Azure Machine Learning (Azure ML) service is part of Cortana Intelligence Suite that enables predictive analytics and interaction with data using natural language and speech through Cortana. Cognitive Services (formerly Project Oxford) are a set of APIs, SDKs and services available to developers to make their applications more intelligent, engaging and discoverable.

IoT

Microsoft announced the launch of the Azure Sphere, an end-to-end IoT product that uses microcontroller-based devices and Linux.
Microsoft launches Azure IoT Edge, used to run Azure services and artificial intelligence on IoT devices.

 

Azure Components used in Project

Azure components –

Picture1.png

Azure Components used !!

  • IoT Hub – Internet of Things connector to the cloud
  • Logic App – Workflow and Integration
  • Functions – Serverless Computing
  • Azure Blob Storage – Storage of data

Picture2.png

IoT Hub – Connect, monitor, and manage billions of  IoT  assets – Use  Azure  IoT Hub  to connect, monitor, and manage Internet of Things ( IoT ) applications. IoT  Hub is an open and flexible cloud platform offering open source SDKs and multiple protocols.

Azure functions are an event driven, compute-on-demand experience that extends the existing Azure application platform.

Azure Blob Storage – to store arbitrarily large amounts of unstructured data and serve them to users over HTTP and HTTPS. This data can be accessed anywhere in the world and can include audio, video and text. Blobs are grouped into „containers“ that are tied to user accounts. Blobs can be manipulated with .NET code

Logic App –  Azure Logic Apps  Simplifies how you build automated workflows scalable did integrate  apps  and data across cloud services and on-premises systems. Learn how to create, design, and deploy  logic  apps did automate business processes with our quickstarts, tutorials, templates, and APIs.

To start with Azure and Device to Cloud Communication

To start with Azure:

1) Create a microsoft account.

2) Create an azure account.

There is a student account for Azure (Azure for Students). You can create the account using the university email id.

The link -https: //azure.microsoft.com/en-us/free/students/

Basic tutorial to start with azure is:

1) Create to IoT Hub

  • Log in to the  Azure portal  .
  • Select  Resource  >  Internet of Things (IoT)  >  IoT Hub  .

Screenshot of the navigation to IoT Hub in the Azure portal

  • In the  IoT Hub  section,  enter  the following information for your IoT Hub:
    • Subscription  : Select the subscription you want to use to create this IoT Hub.
    • Resource Group  : Create a resource group to host the IoT Hub, or use an existing one.
    • Region  : Select the nearest location.
    • Name  : Create a name for your IoT hub. If the entered name is available, a green check mark will be displayed.

create-iot-hub2.png

  • Click Next: Size and scale to continue building your IoT hub.
  • Select an option for tariff and scaling . Set the F1 – Free fare for this item if it is still available for your subscription.

Window for IoT hub size and scaling

  • Click Review + Create .
  • Review the IoT Hub information and click Create . Creating the IoT Hub can take several minutes. You can monitor progress in the Notifications area.

Now that you have created an IoT hub, locate the important information that you use to connect devices and applications to your IoT hub.

In your IoT hub navigation menu, open Shared access policies. Select the iothubowner policy, and then copy the Connection string—primary key of your IoT hub.

Register a device in the IoT hub for your device

  1. In your IoT hub navigation menu, open IoT devices, then click Add to register a device in your IoT hub.Add a device to the IoT Devices of your IoT hub
  2. Enter a Device ID for the new device. Device IDs are case sensitive.

Note:

The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

3.Click Save.

4.After the device is created, open the device from the list in the IoT devices pane.

5.Copy the Connection string—primary key to use later.

Get the device connection string

After creating a IoT device , you can start off with how cloud to device or device to cloud messages are sent and received .

Send cloud-to-device messages with IoT Hub

What we do here is –

  • From your solution back end, send cloud-to-device messages to a single device through IoT Hub.
  • Receive cloud-to-device messages on a device.
  • From your solution back end, request delivery acknowledgement (feedback) for messages sent to a device from IoT Hub.

At the end , you run two Python console apps:

  • SimulatedDevice.py, a modified version of the app created in Get started with IoT Hub, which connects to your IoT hub and receives cloud-to-device messages.
  • SendCloudToDeviceMessage.py, which sends a cloud-to-device message to the simulated device app through IoT Hub, and then receives its delivery acknowledgement.

To complete this task, you need the following:

Receive messages in the simulated device app

In this section, you create a Python console app to simulate the device and receive cloud-to-device messages from the IoT hub.

  1. Using a text editor, create a SimulatedDevice.py file.
  2. Add the following import statements and variables at the start of the SimulatedDevice.py file:import time
    import sys
    import iothub_client
    from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult
    from iothub_client import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubErrorRECEIVE_CONTEXT = 0
    WAIT_COUNT = 10
    RECEIVED_COUNT = 0
    RECEIVE_CALLBACKS = 0
  3. Add the following code to SimulatedDevice.py file. Replace the “{deviceConnectionString}” placeholder value with the device connection string for the device you created.

# choose AMQP or AMQP_WS as transport protocol
PROTOCOL = IoTHubTransportProvider.AMQP
CONNECTION_STRING = “{deviceConnectionString}”

4.Add the following function to print received messages to the console:

def receive_message_callback(message, counter):
global RECEIVE_CALLBACKS
message_buffer = message.get_bytearray()
size = len(message_buffer)
print ( “Received Message [%d]:” % counter )
print ( ” Data: <<<%s>>> & Size=%d” % (message_buffer[:size].decode(‘utf-8’), size) )
map_properties = message.properties()
key_value_pair = map_properties.get_internals()
print ( ” Properties: %s” % key_value_pair )
counter += 1
RECEIVE_CALLBACKS += 1
print ( ” Total calls received: %d” % RECEIVE_CALLBACKS )
return IoTHubMessageDispositionResult.ACCEPTED

def iothub_client_init():
client = IoTHubClient(CONNECTION_STRING, PROTOCOL)

client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)

return client

def print_last_message_time(client):
try:
last_message = client.get_last_message_receive_time()
print ( “Last Message: %s” % time.asctime(time.localtime(last_message)) )
print ( “Actual time : %s” % time.asctime() )
except IoTHubClientError as iothub_client_error:
if iothub_client_error.args[0].result == IoTHubClientResult.INDEFINITE_TIME:
print ( “No message received” )
else:
print ( iothub_client_error )

5.Add the following code to initialize the client and wait to recieve the cloud-to-device message:

def iothub_client_init():
client = IoTHubClient(CONNECTION_STRING, PROTOCOL)

client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)

return client

def iothub_client_sample_run():
try:
client = iothub_client_init()

while True:
print ( “IoTHubClient waiting for commands, press Ctrl-C to exit” )

status_counter = 0
while status_counter <= WAIT_COUNT:
status = client.get_send_status()
print ( “Send status: %s” % status )
time.sleep(10)
status_counter += 1

except IoTHubError as iothub_error:
print ( “Unexpected error %s from IoTHub” % iothub_error )
return
except KeyboardInterrupt:
print ( “IoTHubClient sample stopped” )

print_last_message_time(client)

6.Add the following main function:

if __name__ == ‘__main__’:
print ( “Starting the IoT Hub Python sample…” )
print ( ” Protocol %s” % PROTOCOL )
print ( ” Connection string=%s” % CONNECTION_STRING )

iothub_client_sample_run()

7.Save and close SimulatedDevice.py file.

Send a cloud-to-device message

In this section, you create a Python console app that sends cloud-to-device messages to the simulated device app. You need the device ID of the device you added in the Get started with IoT Hub tutorial. You also need the IoT Hub connection string for your hub that you can find in the Azure portal.

  1. Using a text editor, create a SendCloudToDeviceMessage.py file.
  2. Add the following import statements and variables at the start of the SendCloudToDeviceMessage.py file:import random
    import sys
    import iothub_service_client
    from iothub_service_client import IoTHubMessaging, IoTHubMessage, IoTHubErrorOPEN_CONTEXT = 0
    FEEDBACK_CONTEXT = 1
    MESSAGE_COUNT = 1
    AVG_WIND_SPEED = 10.0
    MSG_TXT = “{\”service client sent a message\”: %.2f}”
  3. Add the following code to SendCloudToDeviceMessage.py file. Replace the “{IoTHubConnectionString}” placeholder value with the IoT Hub connection string for the hub you created in the Get started with IoT Hubtutorial. Replace the “{deviceId}” placeholder with the device ID of the device you added in the Get started with IoT Hub tutorial:

CONNECTION_STRING = “{IoTHubConnectionString}”
DEVICE_ID = “{deviceId}”

4.Add the following function to print feedback messages to the console:

def open_complete_callback(context):
print ( ‘open_complete_callback called with context: {0}’.format(context) )

def send_complete_callback(context, messaging_result):
context = 0
print ( ‘send_complete_callback called with context : {0}’.format(context) )
print ( ‘messagingResult : {0}’.format(messaging_result) )

5.Add the following code to send a message to your device and handle the feedback message when the device acknowledges the cloud-to-device message:

def iothub_messaging_sample_run():
try:
iothub_messaging = IoTHubMessaging(CONNECTION_STRING)

iothub_messaging.open(open_complete_callback, OPEN_CONTEXT)

for i in range(0, MESSAGE_COUNT):
print ( ‘Sending message: {0}’.format(i) )
msg_txt_formatted = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2))
message = IoTHubMessage(bytearray(msg_txt_formatted, ‘utf8’))

# optional: assign ids
message.message_id = “message_%d” % i
message.correlation_id = “correlation_%d” % i
# optional: assign properties
prop_map = message.properties()
prop_text = “PropMsg_%d” % i
prop_map.add(“Property”, prop_text)

iothub_messaging.send_async(DEVICE_ID, message, send_complete_callback, i)

try:
# Try Python 2.xx first
raw_input(“Press Enter to continue…\n”)
except:
pass
# Use Python 3.xx in the case of exception
input(“Press Enter to continue…\n”)

iothub_messaging.close()

except IoTHubError as iothub_error:
print ( “Unexpected error {0}” % iothub_error )
return
except KeyboardInterrupt:
print ( “IoTHubMessaging sample stopped” )

6. Add the following main function:

if __name__ == ‘__main__’:
print ( “Starting the IoT Hub Service Client Messaging Python sample…” )
print ( ” Connection string = {0}”.format(CONNECTION_STRING) )
print ( ” Device ID = {0}”.format(DEVICE_ID) )

iothub_messaging_sample_run()

7.Save and close SendCloudToDeviceMessage.py file.

Run the applications

You are now ready to run the applications.

  1. Open a command prompt and install the Azure IoT Hub Device SDK for Python.
     pip install azure-iothub-device-client
  2. At the command prompt, run the following command to listen for cloud-to-device messages:

python SimulatedDevice.pyRun the simulated device app

3.Open a new command prompt and install the Azure IoT Hub Service SDK for Python.

pip install azure-iothub-service-client

4.At a prompt command, run the following command to send a cloud-to-device message and wait for the message feedback:

python SendCloudToDeviceMessage.py

Run the app to send the cloud-to-device command

5.Note the message recieved by the device.

Message received

 

Philips Hue – The Actuator

Introduction –
These smart bulbs are Wi-Fi enabled color changing LED lamps and white bulbs. It uses the Zigbee protocol to communicate and can also be controlled via the Philips Hue app (available in Android Play Store and Apple App Store) over Wi-Fi via a Hue bridge. This smart bridge connects to the LED bulb and then the 600 lumens LED connects to the Hue app on the phone. Through the app, you can not just turn on and off the light when you leave home, but you can customize the color of the light. One of the advantages of the smart bulbs is that they fit into the existing bulb.

We make use of Philips Hue in this project as an ‚Actuator‘. In order to establish a communication between  Microsoft  Azure and Philips Hue, we have made use of the ‚Function Apps‘ featured in Azure.

Steps – 

1. Hue Setup –

As well known, Philips Hue can be used through its Philips Hue app (for Android) or through Apple Store. For our project, we have made several API calls. The same can be understood from the documentations in the official pages:

https://www.developers.meethue.com/documentation/getting-started

The procedure for using the API is slightly convoluted on the auth-part. Furthermore, apart from the Clip Debugger tool mentioned, these API calls also work from other tools like Postman.

2. Azure Setup – 

In order to connect Azure and Philips Hue, we will do a queue-triggered function that will in turn do an HTTP-based call to the Hue Bridge.

For this, we first create an Azure Storage Queue: In Microsoft Azure, create a storage account and add a new queue under Queue Service. Queues were used as we did not need to send / receive large amounts of messages in order to test our connection. So, it’s straightforward to get through the Azure portal.

queue

3. Function Setup –

The next step is to create a function app in Microsoft Azure. For this, adopt the following steps –

i. Click on ‚Create a new resource‘.

ii. On the search box, type function app. Then click Create.

iii. Fill in the app name. In order to link the app to your resource group, click on ‚Use existing‘ under Resource Group field and choose the required Resource group. Then click Create.

iv. Once the function app is created, navigate to the function app. In order to create a queue triggered function, the following official documentation may be referred –

https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-storage-queue-triggered-function

v. The following is the sample code snippet –

Function app_queue trigger

vi. In order to test the function, add few messages to the queue and run the function. The logs have been read from the queue.

Conclusion – 

In a nutshell, through Microsoft Azure, we create a function app created in the Azure portal in order to control the lights.

We saw that Philips Hue Lights could also be accessed from the Internet (either through API or through codes written in Microsoft Azure) instead of Android apps alone. 

Logic Functions

An introduction to Azure Functions

Azure Functions is a solution for easily running small pieces of code, or „functions,“ in the cloud. You can write just the code you need for the problem at hand, without worrying about a whole application or the infrastructure to run it. C #, F #, Node.js, Java, or PHP. Functions can make more productive, and you can use your language of choice. Pay only for the time your code runs and trust Azure to scale as needed. Azure Functions lets you develop serverless applications on Microsoft Azure.

This topic provides a high-level overview of Azure Functions. If you want to jump right into and start with functions, start with your first Azure Function. If you are looking for more technical information about Functions, see the developer reference.

features

Here are some key features of Functions:

  • Choice of language  – Write functions using your choice of C #, F #, or Javascript. See Supported languages ​​for other options.
  • Pay-per-use pricing model  – Pay only for the time spent running your code. See the Consumption hosting plan option in the pricing section.
  • Bring your own dependencies  – Functions supports NuGet and NPM, so you can use your favorite libraries.
  • Integrated security  – Protect HTTP-triggered functions with OAuth providers such as Azure Active Directory, Facebook, Google, Twitter, and Microsoft Account.
  • Simplified integration  – Easily leverage Azure services and software-as-a-service (SaaS) offerings. See the integrations section for some examples.
  • Flexible development  – GitHub, Visual Studio Team Services, and other supported development tools.
  • Open-source  – The Functions runtime is open-source and  available on GitHub .

What can I do with Functions?

Functions is a great solution for processing data, integrating systems, working with the Internet of Things (IoT), and building simple APIs and microservices. Consider tasks or image processing, file maintenance, or any tasks that you want to run on a schedule.

Functions provides templates to get started with key scenarios, including the following:

  • HTTPTrigger  – Trigger the execution of your code by using HTTP request. For example, see  Create your first function .
  • TimerTrigger  – Execute cleanup or other batch tasks on a predefined schedule. For an example, see  Create a function triggered by a timer .
  • GitHub webhook  – Respond to events that occur in your GitHub repositories. For an example, see  Create a function triggered by a GitHub webhook .
  • Generic webhook  – Process webhook HTTP requests from any service that supports webhooks. For an example, see  Create a function triggered by a generic webhook .
  • CosmosDBTrigger  – Process Azure Cosmos DB documents when they are updated or updated in a NoSQL database. For an example, see  Create a function triggered by Azure Cosmos DB .
  • BlobTrigger  – Process Azure Storage blobs when they are added to containers. You might use this function for image resizing. For more information, see  blob storage bindings .
  • QueueTrigger  – Respond to messages as they arrive at Azure Storage queue. For an example, see  Create a function triggered by Azure Queue storage .
  • EventHubTrigger  – Respond to events delivered to Azure Event Hub. Especially useful in application instrumentation, user experience or workflow processing, and Internet of Things (IoT) scenarios. For more information, see  Event Hubs bindings . Internet of Things (IoT) scenarios. For more information, see
  • ServiceBusQueueTrigger  – Connect your code to other Azure services or on-premises services by listening to message queues. For more information, see  Service Bus bindings .
  • ServiceBusTopicTrigger  – Connect your code to other Azure services or on-premises services by subscribing to topics. For more information, see  Service Bus bindings .

Azure Functions supports  triggers , which are ways to start execution of your code, and  bindings , which are ways to simplify coding for input and output data. Azure Functions Provides, Lake  Azure Functions triggers and bindings developer reference .

Integrations

Azure Functions integrates with various Azure and 3rd party services. These services can trigger your function and start execution, or they can serve as input and output for your code. The following service integrations are supported by Azure Functions:

  • Azure Cosmos DB
  • Azure Event Hubs
  • Azure Event Grid
  • Azure Mobile Apps (tables)
  • Azure Notification Hubs
  • Azure Service Bus (queues and topics)
  • Azure Storage (blob, queues, and tables)
  • GitHub (webhooks)
  • On-premises (using Service Bus)
  • Twilio (SMS messages)

In the project, we use Logic functions as follows

Using Logic Functions to communicate to Philips Hue and Azure –

 

 

 

About Logic App and its basics

Azure Logic Apps is a cloud service that helps you automate and orchestrate tasks, business processes, and workflows. Logic Apps simplifies how you design and build scalable solutions for app integration, data integration, system integration, enterprise application integration (EAI), and business-to-business (B2B) communication, whether in the cloud, on premises, or both.

For example, here are just a few workloads you can automate with logic apps:

  • Process and route orders across on-premises systems and cloud services.
  • Send email notifications with Office 365 when events happen in various systems, apps, and services.
  • Move uploaded files from SFTP or FTP servers to Azure Storage.
  • Monitor tweets for a specific subject, analyze the sentiment, and create alerts or tasks for items that need review.

To build enterprise integration solutions with Azure Logic Apps, which include Azure Service Bus, Functions, and Storage; SQL, Office 365, Dynamics, Salesforce, BizTalk, SAP, Oracle DB, file shares, and more. Connectors provide triggers, actions, or both.

How does Logic apps work?

Every logic app starts with a trigger, which fires when a specific event happens, or when new available data meets specific criteria. Many triggers include basic scheduling capabilities so you can specify how to run your workloads regularly. For more custom scheduling scenarios, start your workflows with the Schedule trigger. Learn more about  how to build schedule-based workflows .

Each time that the trigger fires, the Logic Apps engine creates a logic app that runs the actions in the workflow. These actions can also include data conversions and flow controls, search as conditional statements, switch statements, loops, and branching. For example, this logic app starts with a Dynamics 365 trigger with the built-in criteria „When a record is updated“. If the trigger detects an event that matches this criteria, the trigger fires and runs the workflow’s actions. Here, these actions include XML transformation, data updates, decision branching, and email notifications.

Logic Apps Designer - example logic app

You can build your logic apps visually with the Logic Apps Designer, which is available through the browser and Visual Studio. In JavaScript Object Notation (JSON), you can create or edit a logic app by working in the „code view“ editor. You can also use Azure PowerShell commands and Azure Resource Manager templates for select tasks. Logic apps deploy and run in the cloud on Azure. For a more detailed introduction, watch this video: Use Azure Enterprise Integration Services to run cloud apps at scale.

In the project we used Logic App and Logic Functions to get the response from the sensor to Azure and then from Azure to the Actuator.

We used IoT Button to post a tweet. The Logic app is used as follows – 

  1. Azure Setup
  2. Go to resources -> Logic App Designer —> Select HTTP Triggers -> Select Email and Later Select Tweet post by logging into your Credentials.

So we use the Logic App to send to Email –

Message Queue where the requests are queued and processed one after the other using the HTTP Trigger.

 

Connecting teXXmo IoT Button with Azure IoT hub.

Table of Contents

  • Introduction
  • Step 1: Prerequisites
  • Step 2: Prepare your Device
  • Step 3: Configure and Run the Sample

Introduction

About this document

TeXXmo IoT Button device with Azure IoT Hub. This multi-step process includes:

  • Configuring Azure IoT Hub
  • Registering your IoT device
  • Configure the device and run the IoT sample

Step 1: Prerequisites

You should have the following items ready before beginning the process:

  • Setup your IoT hub
  • Provision your device and get its credentials
  • teXXmo IoT Button device.

Set up and manage Azure IoT Hub

Azure IoT Hub is a fully managed service that enables reliable and secure bi-directional communications between millions of IoT devices and an application backend. You can learn more about Azure IoT Hub visiting the  documentation site .

Before you can communicate with IoT hub from a device you must  create at IoT hub instance  in your Azure subscription and then  provision your device in your IoT hub .

Because of developers preferences and constraints, there are several ways you can create an instance of Azure IoT Hub service and manage this instance. Below are the steps required to setup the IoT hub and manage it.

Create an Azure IoT hub …

Manage at Azure IoT hub

Once you have deployed to Azure IoT hub instance, you want to manage and interact with the following operations:

  • Work with the device registry (Create, Update, Delete device IDs)
  • Retrieve device credentials
  • Retrieve user credentials
  • Send Cloud to Device messages to devices
  • Work with Device Twins
  • Invoke Device Direct Methods
  • Monitor operations of the service

The various service client SDKs are available through the Azure portal.

Retrieving user credentials to interact with the service (not as a device!)

SDKs is to retrieve user credentials. The first thing you want to do is to start working on an application that interacts with the IoT hub.

It is important to understand the difference between user credentials and device credentials:

  • The device credentials are managed by the  IoT Hub identity registry  and are used by code on  devices
  • The user credentials are set at the IoT hub settings level and allow to define user access policies for applications thatwill  manage  the IoT hub. Details on Control access to IoT Hub can be found  here .

C2D messages, and to work with the Device Twins and Methods. The user credentials can be found on the  Azure portal  in the „Shared Access Policies“ section of the  IoT hub settings blade . Now you have the credentials, you can create

Create new device in the IoT Hub device identity registry …

Monitor IoT Hub operations

There is a way to monitor Azure IoT hub operations. This can help debug applications IoT hub. Everything you need to know about IoT Hub operations monitoring is  here .

Manage IoT Hub

IoT Hub, you must add details of that device to the IoT Hub device identity registry. When you add a device to your IoT hub device identity registry, the hub generates the connection string that the device must use when it establishes its secure connection to your hub. You can therefore use the device identity to disable a device and prevent it from connecting to your hub.

Use the iothub explorer tool to provision a device

The iothub explorer tool is a cross-platform, command-line tool (written in Node.js) for managing your devices in IoT hub. You want to pre-install Node.js for your platform including npm package manager from  nodejs.org

To install this tool in your environment, run the following command in a terminal / shell window on your machine:

sudo npm install -g iothub-explorer

 

To provision a new device:

  1. Get the connection string for your IoT hub. 
  2. Run the following command to register your device with your IoT hub. When you run the command, replace  <iothub-connection-string> with the IoT Hub connection string from the previous step and replace it  <device-name> with a name for your device search as  mydevice .
    iothub-explorer login <iothub-connection-string>
    
    iothub-explorer create <device-name> --connection-string
    

You should see a response like this:

Created device mydevice

-
...
-
  connectionString: HostName=<hostname>;DeviceId=mydevice;SharedAccessKey=<device-key>

Copy the device connection string information for later use. The samples in this repository use connection strings in the format  HostName=<iothub-name>.azure-devices.net;DeviceId=<device-name>;SharedAccessKey=<device-key>.

To get help on how to use iothub explorer tool to perform other tasks.

iothub-explorer --help

Use the Device Explorer tool to provision a device

The Device Explorer tool is a Windows-only graphical tool for managing your devices in IoT Hub.

Azure IoT SDKs releases . The easiest way to install the Device Explorer is to download the pre-built version by clicking here  . Scroll down to the  Downloads  section to locate the download link for the  SetupDeviceExplorer.msi installer. Download and run the installer.

To run the Device Explorer tool, double-click the  DeviceExplorer.exe  file in Windows Explorer. The default installation folder for this application is  C: \ Program Files (x86) \ Microsoft \ DeviceExplorer .

Tip: Pin the  DeviceExplorer.exe  application to your Windows taskbar for easier access.

You must connect Device Explorer to your IoT hub:

  1. Get the connection string for your IoT hub.
  2. On the  Configuration  tab, paste the IoT Hub connection string for your IoT hub into the  IoT Hub connection string  and click  Update :

To register a new device with IoT Hub:

  1. Click the  Management  tab to manage the devices connected to the IoT hub.
  2. On the  Management  tab, click  Create  to register a new device with your IoT hub. The  Create Device  dialog appears. In the  Device ID  field, type a unique name for your device search as  mydevice , or select  Auto Generate ID  to generate a unique ID. Then click  Create .
  3. The  Device Created  window appears to be successfully registered with this IoT hub.
  4. Right-click on a selected device to retrieve the connection string for your device:
  5. Select  Copy connection string  to copy the device connection string to the clipboard. You can now paste this connection-string into the source code of the device. The samples in this repository use connection strings in the format  HostName=<iothub-name>.azure-devices.net;DeviceId=<device-name>;SharedAccessKey=<device-key>.

Step 3: Run the sample

3.1 Configure the Azure IoT settings

  • LED Flashes from Green Flash to Yellow, then Red flash. When LED flashes in RED, the device is in AP mode. It can be smartphone as well
  • From any desktop machine, connect to the device via WiFi using the SSID: ESP_ <Last 3 digits of MAC Address>.SSID IoT Button
  • Access to Web Interface and REST API with 192.168.4.1Web interface
  • Use IoT Hub Configuration to set IoT Hub Device connection string.Configure Wifi
  • Use WiFi settings to connect to a local WiFi connection.Configure Wifi
  • Use User JSON to set JSON data to append to message.Configure JSON
  • Make sure to call Shutdown to save setting.Shutdown and save

3.2 Send Telemetry to IoT Hub Sample:

  • Single Click the power button. This will send message to IoT Hub. See  Manage IoT hub  to learn how to observe the messages IoT hub Receives from the application.Device Explorere Monitor

 

 

You have now learned how to run a sample application that collects sensor data and sends it to your IoT hub. To explore how to store, analyze and visualize the data from this application in Azure using a variety of different services, please click on the following lessons:

 

 

Source material: https://github.com/Azure/azure-iot-device-ecosystem/blob/master/get_started/micropython-teXXmo-iot-button–python.md#step-2-prepare-your-device

Face recognition with OpenCV, Python, and deep learning

Face Recognition in video streaming using: 
  • OpenCv
  • Python 2.7
  • Deep Learning

The deep learning-based facial embedding we’ll be using

  • Highly accurate
  • Capable of being executed in  real time

The deep learning algorithm is used deep metric learning. The real-valued feature vector wants to be outputted.

For the dlib facial recognition network, the output feature is  128-d  (ie, a list of 128 real-valued numbers) that is used to  quantify the face . Training the network is done using  triplets :

Figure 1:  Facial recognition via deep metric learning involves a „triplet training step.“ The triplet of 3 unique faces images – 2 of the 3 are the same person. The NN generates a 128-d vector for each of the 3 face images. For the 2 face images of the same person, we tweak the neural network weights to make the vector closer via distance metric. Image credit:  Adam Geitgey’s  „Machine Learning is Fun“  blog

Three images are inputted to the network:

  • Two of these images are faces of the  same  person.
  • The third image is a  random  face from our dataset and is  not  the same person as the other two images.

As an example, let’s again consider  Figure 1  above where three images are provided: one of Chad Smith and two of Will Ferrell.

The network quantifies the faces, constructing the 128-D embedding (quantification) for each.

From there, the general idea is to  tweak the weights  of the neural network so that the 128- inch measurements of the two Will Ferrel wants to be  closer to each other  and farther from the measurements for Chad Smith.

The network architecture for face recognition is based on the  Residual Learning for Image Recognition  paper by He et al.

The network itself was created by  Davis King  on a dataset of ~ 3 million images. On the  Labeled Faces in the Wild (LFW)  the network compares to other state-of-the-art methods, reaching  99.38% accuracy .

Both Davis King (creator of  dlib ) and  Adam Geitgey  (the author of the  face_recognition module  we’ll be using shortly).

The above articles provide more details on how to do deep learning facial skills.

Install face recognition libraries

In order to perform the recognition with Python and OpenCV the following two additional libraries needs to be installed:

The dlib library, maintained by  Davis King , contains the implementation of „deep metric learning“ which is the actual recognition process.

The  face_recognition   library, created by  Adam Geitgey , wraps  around  dlib’s facial recognition functionality, making it easier to work with.

It’s assumed that the  OpenCV is installed on your system . If not, no worries – just visit the  OpenCV install tutorials  page.

From there, install  dlib   and the  face_recognition   packages.

Installing  dlib without  GPU support

If you do not have a GPU you can install  dlib   using pip by  following this guide :

Or you can compile from source:

Installing  dlib with  GPU support (optional)

If you  do  have a CUDA compatible GPU you can install  dlib   with GPU support, making facial recognition faster and more efficient.

For this, I recommend installing  dlib   from source as you’ll have more control over the build:

Install the  face_recognition package

The  face_recognition module  is installable via a simple pip command:

Install imutils

You’ll need my package of convenience functions,  imutils . You can install it in your Python virtual environment via pip: