Home > Articles > Operating Systems, Server > Microsoft Windows Desktop

  • Print
  • + Share This
This chapter is from the book

Proximity (Near Field Communications)

Near Field Communications (NFC6) is a set of standards based on Radio-Frequency Identification (RFID) standards for smartphones, tablets, smart tags, and other devices to establish communications in extremely close situations (less than a few inches difference). Two main NFC scenarios exist. The first is a tap gesture for a short transmission of information, such as contact information, a URL, or a “smart poster.” The second is a similar gesture used to create a handshake between two devices so they can establish a peer-to-peer connection over wireless to exchange large amounts of information.

NFC not only operates over extremely short distances, but it also has a fairly slow transfer rate, with theoretical speeds between 50 and 100 bytes per second. For this reason, it is useful for exchanging only a small amount of information, unless you use the NFC tap to establish a more persistent connection over a longer range and using faster technology, including Bluetooth, Wi-Fi, and Wi-Fi Direct. The WinRT API fully supports both of these scenarios.

NFC-Only Scenarios

When you exchange information via NFC, you must either send or receive a message encoded in the NFC Data Exchange Format (NDEF). This is a lightweight, platform-independent binary format for exchanging messages. The message allows one or more specific payloads (referred to as NDEF records) to be sent in a single package. Windows provides built-in support for a set of proprietary NDEF records that Windows 8.1 and Windows Phone devices can exchange. You can also format and exchange other types of records that target other platforms or are platform-independent by either building your own payload or using an open source library such as the NDEF Library for Proximity APIs that is available as a NuGet package.7

The ProximityExample project provides some examples of using the Proximity APIs defined in the Windows.Networking.Proximity namespace. The ProximityDevice class provides the simplest API to use and focuses specifically on short-range, short-duration NFC scenarios. To see whether the system has a proximity device available, simply call the GetDefault static method, shown in the constructor of the ViewModel class. Be sure to declare the Proximity capability in the application’s manifest.

this.proximityDevice = ProximityDevice.GetDefault();

The call returns null when a device is not present. If this is the case on your machine, you will not be able to take advantage of NFC exchanges and gestures, but you may still be able to create peer-to-peer connections using Bluetooth, Wi-Fi, or Wi-Fi Direct. You learn more about that in a later section. The proximity device exposes properties for its unique identifier, the maximum number of bytes it can send in a single message, and the bits per second it is capable of transmitting or receiving. You can also register for events that fire when another proximity device comes within range:

this.proximityDevice.DeviceArrived +=
    this.ProximityDeviceDeviceArrived;
this.proximityDevice.DeviceDeparted +=
    this.ProximityDeviceDeviceDeparted;

The events are purely informational and do not provide any specific information. The ProximityDevice parameter of the handler is a reference back to the device that detected the event, which, in most cases, is the default device referenced in the constructor. Other classes exist for enumerating multiple proximity devices, in the rare case that the machine has multiple ones installed. This is a rare scenario because one NFC device is usually sufficient.

An easy way to share information with another NFC device is to use the PublishMessage method on the ProximityDevice class. This method is useful for sharing simple string data with other Windows or Windows Phone devices. It takes two parameters: the message type and the message itself. The message type is a unique identifier that enables other devices to determine how to handle the message. The message type always starts with a protocol, followed by a dot, followed by whatever custom identifier you prefer. In this case, the protocol must always be Windows. (The simple code for publishing and subscribing in this section is shared here for reference purposes but is not part of a specific example project.)

var publishedMessageId =
    proximityDevice.PublishMessage("Windows.WinRTByExampleMessage",
    "This is a simple message.");

The publication is not a transient event. The message will be available until you explicitly stop publishing, so multiple NFC devices over time can connect and subscribe for that message to receive it. To stop publishing, you call the StopPublishingMethod on the ProximityDevice.

proximityDevice.StopPublishingMessage(publishedMessageId);

If you want to know when the message has been transmitted, you can pass a MessageTransmittedHandler as a third parameter when you publish. The handler is called with the proximity device and the identifier for the message. You can use this to log that the message was transmitted, or even unsubscribe in the callback to ensure that the message is sent only once.

private void MessagePublished(ProximityDevice sender,
    long messageId)
{
    proximityDevice.StopPublishingMessage(messageId);
}

To receive a message, you use the SubscribeForMessage method on the ProximityDevice class. You do not have to wait for a device to arrive or depart before you subscribe, and the subscription is valid for any device that publishes that particular message type. The subscription includes a handler that is called whenever the message is received, and it is provided a unique identifier that you can use to unsubscribe when you want to stop receiving the message.

var subscribedMessageId =
    proximityDevice.SubscribeForMessage("Windows.WinRTByExampleMessage",
    MessageReceived);

The method to receive the message is passed the ProximityDevice and a ProximityMessage. The message includes the data as a buffer, the data as a string, and the subscription ID, in case you want to use that to stop subscribing.

private void MessageReceived(ProximityDevice device,
    ProximityMessage message)
{
    var messageText = message.DataAsString;
    device.StopSubscribingForMessage(subscribedMessageId);
}

The subscription method enables you to subscribe to any type of message. For messages that use non-Windows protocols, you need to decode the message. For example, the message type WindowsUri provides a URI, but you must first decode it from UTF16LE:

void messageReceivedHandler(ProximityDevice device,
    ProximityMessage message)
{
    var buffer = message.Data.ToArray();
    var uri = Encoding.Unicode.GetString(buffer, 0, buffer.Length);
}

Note that some devices, such as the Windows Phone, handle URIs at the operating system level. In other words, you cannot override the default behavior. The OS itself intercepts the NFC tag and opens the corresponding program. The program depends on the protocol. HTTP launches the Internet Explorer browser and navigates to the encoded web page, and a mailto protocol results in the default mail program being launched.

You can use the NFC API to write to smart tags, or special tags that use induction to store and publish information. Smart tags have varying capacities, depending on the manufacturer. Publishing to a smart tag always overwrites the data, and most smart tags have a lifetime of several hundred thousand writes. To get the capacity of a smart tag, you can subscribe to the WriteableTag message. This transmits an Int32 message that contains the capacity of the tag.

private void MessageReceived(ProximityDevice device,
    ProximityMessage message)
{
    var capacity = System.BitConvert.ToInt32(
        message.Data.ToArray(), 0);
}

Table 10.1 lists the various message types you can subscribe to.

TABLE 10.1 Common NFC Message Protocols

Protocol

Description

Windows

Consists of raw binary data.

Windows.*

Provides a custom string type proprietary to Windows, where * represents a custom type.

WindowsUri

Consists of a UTF-16LE encoded URI string. Note that the operating system shell intercepts these messages and marshals them to the appropriate protocol handler.

WindowsMime

Contains a specific MIME type—like image/jpeg for a bitmap image.

WriteableTag

Published by smart tags when they come within range of reading or writing. Contains the capacity of the smart tag in bytes.

NDEF[:*]

Consists of formatted NDEF records. Third-party libraries are available to easily encode and decode these record formats.

You also can publish messages for cross-platform compatibility or for the purpose of writing to smart tags. Instead of using the proprietary PublishMessage method, use the PublishBinaryMessage method. You can use this method to publish messages to other NFC devices, but it is also useful for writing messages to smart tags. The following code snippet encodes the URI to launch Skype and calls the echo service on a Windows or Windows Phone device.

var uri = new Uri("skype:echo123?call");
var buffer = Encoding.Unicode.GetBytes(uri.ToString());
var publishId = device.PublishBinaryMessage("WindowsUri:WriteTag",
    buffer.AsBuffer());

Table 10.2 lists various protocols you can use when writing messages to tags.

TABLE 10.2 Message Protocols for Writing to Smart Tags

Protocol

Description

Windows:WriteTag

Publish binary data to a static smart tag

WindowsUri:WriteTag

Write a URI to a static smart tag

LaunchApp:WriteTag

Write a tag that launches an app with specific launch parameters

NDEF:WriteTag

Write a cross-platform message using the NDEF format

To write a tag that launches an app, use the LaunchApp:WriteTag format; then provide a tab-delimited list that starts with the text to pass in as an argument and then includes pairs of platforms and application names. You can find the application name for a Windows 8.1 application in the application manifest. It is in the format of the Package family name (from the Packaging tab) and an exclamation mark. The following tag passes an argument named id with a value of 1 to both the Windows 8.1 ProximityExample app and a fictional app on Windows Phone 8 (the application name on Windows Phone is simply the GUID for the application ID).

var launchTag =
    "id=1\tWindows\tWinRTByExampleProximityExample_req6rhny9ggkj! " +
    "ProximityExample.App\tWindowsPhone\t{063e933a-fc8e-4f0c" +
    "-8395-ab0e84725f0f}";

If the app is present on the target device, it is launched with the arguments passed (the user is always prompted to opt in for the launch whenever this type of tag is encountered). If the app is not present, the device automatically takes the user to the app’s entry in the Windows Store. This makes the tag extremely useful: If you pass out smart tags with the encoding, users can easily discover and install your app, as well as subsequently launch it.

In this section, you learned ways to publish small messages that can be sent to other devices or encoded in smart tags. You also learned how to subscribe to and receive these messages. I mentioned earlier a way to share much more information than permitted by the limited bandwidth and speed of the NFC protocol. In this next section, you explore the tap-to-connect scenario that uses NFC to establish a persistent peer-to-peer connection for exchanging information.

Tap-to-Connect Scenarios

The PeerFinder class enables you to find and interact with other devices capable of peer-to-peer communications. Although a common use case is through NFC, you can also use Bluetooth and Wi-Fi Direct to locate and communicate with peers. The WinRT API abstracts these decisions from you and enables you to focus on the actual process of locating a peer and establishing a socket so that you can stream data back and forth.

Even if you don’t have a proximity device, chances are good that you can take advantage of the ProximityExample sample app to create a peer-to-peer connection. That’s because the WinRT API supports a browse scenario using Wi-Fi Direct, a technology that enables peer-to-peer wireless connections between devices that exists in most modern radios. Using the browsing scenario, you can install the app on two different devices and use them to discover each other.

The proximity APIs support finding peers running the same application. The application is defined by the package family, a unique identifier for your app that is shared across target platforms. For this reason, your app on a machine running Windows 8.1 can easily connect to the same app on a machine running Windows RT. You can also extend the peer to find instances of your app on other platforms, such as Windows Phone and Android. The PeerFinder class contains a dictionary named AlternateIdentities that hosts a list of platforms and application identifiers. In the previous section, you learned how to create a tag that launches the application and can contain multiple platforms and identities. You can add the same identifier to recognize that app as a peer like this:

PeerFinder.AlternateIdentities.Add("WindowsPhone",
    "{063e933a-fc8e-4f0c-8395-ab0e84725f0f}");

You can discover and negotiate the peer connection either through an NFC tap gesture or by browsing Wi-Fi Direct. After the devices recognize each other and initiate the handshake, Windows tries to connect simultaneously using infrastructure (wireless or wired), Wi-Fi Direct, and Bluetooth. It uses whichever connection completes first (most likely, Bluetooth, when available) and passes the connection as an active socket to your app. You can restrict which connection types to allow by setting the static AllowBluetooth, AllowInfrastructure, and AllowWiFiDirect properties on the PeerFinder class.

The PeerSocket class in the example app provides a convenient way to manage a persistent socket connection. It takes a StreamSocket in the constructor and immediately creates a persistent reader and writer to interact with it.

public PeerSocket(StreamSocket socket)
{
    this.socket = socket;
    reader = new DataReader(socket.InputStream);
    writer = new DataWriter(socket.OutputStream);
}

It exposes a write method that uses the DataWriter to send a message to the socket and starts an infinite loop that runs on a background thread to listen for incoming messages. When it receives an incoming message, it raises an event so the app can register for the event, receive the message, and process it (in the case of the sample app, by marshalling it to the UI thread and showing it on the display). It also raises an error event whenever it encounters an error and disposes of both the reader and the writer when its own Dispose method is called.

To begin the process of connecting with a peer, you must first set your app to advertise. This broadcasts its identity over Wi-Fi Direct and makes it available for tap gestures if a proximity device is present. The Wi-Fi Direct mode is referred to as a browsed connect, and the NFC mode is referred to as a triggered connect. The PeerFinder class is instructed to begin advertising in the StartPeerFinder method on the ViewModel class.

First, the app registers to two events: the TriggeredConnectionStateChanged that is raised when an NFC tap gesture is received, and the ConnectionRequested event that is raised when another device browses your device and requests a connection.

PeerFinder.TriggeredConnectionStateChanged +=
    this.PeerFinderTriggeredConnectionStateChanged;
PeerFinder.ConnectionRequested +=
    this.PeerFinderConnectionRequested;

Next, the role is set. Three possible roles exist. In the Peer role (included in the example app), two apps can connect with each other and communicate as peers. In a client/server scenario, one app can serve as the host and must set the Host role; then up to four other apps can connect using the Client role. Note that only Peer roles can browse to each other. The Host role can browse only Client roles, and vice versa.

PeerFinder.Role = PeerRole.Peer;

Finally, some discovery text is set. This is additional text you can share, such as an application name, an invitation to connect, information about the host system, or any other data up to 240 bytes in length. This data is broadcast and can be displayed when browsing. After the data is set, the PeerFinder starts advertising when you call the Start method.

PeerFinder.Role = PeerRole.Peer;
PeerFinder.DiscoveryData = Encoding.UTF8.GetBytes(
    DiscoveryText).AsBuffer();
PeerFinder.Start();

When both peers have started advertising, one of two scenarios can take place. The first is the NFC tap-to-connect scenario. When the proximity devices are tapped together, the TriggeredConnectionStateChanged event is raised. This event fires multiple times as the devices come within range and negotiate a connection.

The event handler for the triggered connection receives a State property of the type TriggeredConnectState (an enumeration). The handler on the viewmodel is called PeerFinderTriggeredConnectionStateChanged. The Listening state indicates that the proximity device is waiting for a tap. When the state is PeerFound or Connecting, the connection is being established and the handler simply updates the status for the user. If the connection fails, a Failed state is passed. The Completed state indicates success, and the arguments contain a Socket property with the active socket between the two devices:

case TriggeredConnectState.Completed:
    this.RouteToUiThread(() =>{this.IsConnecting = false;});
    this.InitializeSocket(args.Socket);
    break;

The InitializeSocket method sets up an instance of the PeerSocket to handle further communications. A state of Canceled means the connection was broken for some reason—for example, the devices moved out of range or a user intervention occurred.

The browse scenario starts when you request a list of available peers. The BrowseCommand method on the viewmodel calls the FindAllPeersAsync method and then loads the results to the list of available peers.

var peers = await PeerFinder.FindAllPeersAsync();

The user can then select a peer and request a connection. The connection is initiated in the ConnectCommand method.

var socket = await PeerFinder.ConnectAsync(
    this.SelectedPeer.Information);
this.InitializeSocket(socket);

Note that the end result is the same as the triggered connection scenario: A socket is obtained and initialized to establish communications. The mode of the connection is transparent to your app, and there is no way to determine whether the connection was made using Bluetooth, infrastructure, or Wi-Fi Direct (unless you have restricted the allowable connection types to a single mode).

If your device is running a version of the app and the connection is requested from another device, a ConnectionRequested event is raised. The viewmodel handles this in the PeerFinderConnectionRequested method. In this scenario, you typically prompt the user to confirm that he or she wants to accept the request, and then either ignore the request or connect. The sample app automatically initiates the connection. The method to connect is identical for the host, client, or peer; the only difference is that, instead of passing a peer from a list of selections, the peer requesting the connection is passed as arguments to the event.

var socket = await PeerFinder.ConnectAsync(args.PeerInformation);
this.InitializeSocket(socket);

If the call succeeds for both peers, a connection is established and duplex communication can be initiated. You can transmit anything over the binary socket—from images, to streaming videos, to text or documents. The sample app simplifies the connection by transmitting only text. The text you enter is sent to the peer via the output stream of the socket, and any text received raises an event that is marshalled to the UI.

To use the sample program, install it on two Windows 8.1 devices that support Wi-Fi Direct or have proximity devices. The easiest way is to build and deploy the source, but you can also use the Store option on the Project Properties menu to create a side load package. Copy the package to a thumb drive and execute the included PowerShell script to install it on the other device.

Run the app on both devices. You must start advertising on both devices to establish a connection. After you’ve started advertising, either tap the devices or tap Browse to use Wi-Fi Direct. If you browse, select another machine and tap Connect. When the connection is established, via either NFC tap or browsing, you can begin to send messages between the two peers (see Figure 10.3).

FIGURE 10.3

FIGURE 10.3 Example of communicating between peers using the Proximity API

Numerous possibilities exist for taking advantage of the peer connection. You can use it to share documents or pictures between devices, archive data, create a chat session, or even share game state in a multiplayer game. The API handles all the necessary low-level handshakes and connectivity so that you can focus on the implementation of your application without worrying about the underlying NFC protocol or even whether the devices connect over Bluetooth or Wi-Fi Direct. The Proximity API is nearly identical on the Windows Phone, making it possible to build apps that span devices and create a truly continuous user experience among Windows PCs, tablets, and phones.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020