開始使用服務點Getting started with Point of Service

服務點、銷售點或服務點裝置是用來協助零售交易的電腦週邊設備。Point of service, point of sale, or Point of Service devices are computer peripherals used to facilitate retail transactions. 服務點裝置的範例包括電子收銀機、條碼掃描器、磁條讀取器和收據印表機。Examples of Point of Service devices include electronic cash registers, barcode scanners, magnetic stripe readers, and receipt printers.

在此,您將瞭解使用服務 Api 的 Windows 執行階段點來與服務裝置互動的基本概念。Here you’ll learn the basics of interfacing with Point of Service devices by using the Windows Runtime Point of Service APIs. 我們會討論裝置列舉、檢查裝置功能、宣告裝置和裝置共用。We’ll cover device enumeration, checking device capabilities, claiming devices, and device sharing. 我們使用條碼掃描器裝置做為範例,但幾乎這裡所有的指引都適用於任何 UWP 相容的服務點裝置。We use a barcode scanner device as an example, but almost all the guidance here applies to any UWP-compatible Point of Service device. (如需所支援裝置的清單,請參閱 服務點裝置支援)。(For a list of supported devices, see Point of Service device support).

找出和連接至服務點週邊設備Finding and connecting to Point of Service peripherals

服務點裝置必須先與執行應用程式的電腦進行配對,應用程式才能使用該裝置。Before a Point of Service device can be used by an app, it must be paired with the PC where the app is running. 有幾個方式可以連接至服務點裝置,若不是藉由程式設計的方式,就是透過 [設定] App。There are several ways to connect to Point of Service devices, either programmatically or through the Settings app.

使用 [設定] App 連接至裝置Connecting to devices by using the Settings app

條碼掃描器等服務點裝置接上電腦時,該裝置就像任何其他裝置一樣地出現其中。When you plug a Point of Service device like a barcode scanner into a PC, it shows up just like any other device. 您可以在 [設定] App 的 [裝置] > [藍牙與其他裝置] 區段中找到。You can find it in the Devices > Bluetooth & other devices section of the Settings app. 您可以在那裡選取 [新增藍牙或其他裝置],與服務點裝置進行配對。There you can pair with a Point of Service device by selecting Add Bluetooth or other device.

有些服務點裝置必須使用服務點 API,以程式設計方式來列舉,否則這些裝置無法在 [設定] App 中出現。Some Point of Service devices may not appear in the Settings app until they are programmatically enumerated by using the Point of Service APIs.

使用 GetDefaultAsync 取得單一服務點裝置Getting a single Point of Service device with GetDefaultAsync

在簡單的使用案例中,可能只有一部服務點週邊設備連接至 App 執行所在的電腦,您想要盡快加以設定。In a simple use case, you may have just one Point of Service peripheral connected to the PC where the app is running and want to set it up as quickly as possible. 若要這樣做,請使用 GetDefaultAsync 方法來擷取預設裝置,如下所示。To do that, retrieve the “default” device with the GetDefaultAsync method as shown here.

using Windows.Devices.PointOfService;

BarcodeScanner barcodeScanner = await BarcodeScanner.GetDefaultAsync();

如果找到預設裝置,即可開始宣告所擷取的裝置物件。If the default device is found, the device object retrieved is ready to be claimed. 「宣告」一部裝置會將其獨佔存取權授與應用程式,防止多個處理程序的命令發生衝突。“Claiming” a device gives an application exclusive access to it, preventing conflicting commands from multiple processes.

注意

如果有多個服務點裝置連接至電腦,GetDefaultAsync 會傳回找到的第一個裝置。If more than one Point of Service device is connected to the PC, GetDefaultAsync returns the first device it finds. 因此,除非您確定應用程式只有顯示一個服務點裝置,否則請使用 FindAllAsyncFor this reason, use FindAllAsync unless you’re sure that only one Point of Service device is visible to the application.

使用 FindAllAsync 列舉裝置集合Enumerating a collection of devices with FindAllAsync

連接至多個裝置時,您必須列舉 PointOfService 裝置物件的集合,才能找到您要宣告的裝置。When connected to more than one device, you must enumerate the collection of PointOfService device objects to find the one you want to claim. 例如,下列程式碼會建立目前連接的所有條碼掃描器的集合,然後搜尋集合中具有特定名稱的掃描器。For example, the following code creates a collection of all the barcode scanners currently connected, and then searches the collection for a scanner with a specific name.

using Windows.Devices.Enumeration;
using Windows.Devices.PointOfService;

string selector = BarcodeScanner.GetDeviceSelector();       
DeviceInformationCollection deviceCollection = await DeviceInformation.FindAllAsync(selector);

foreach (DeviceInformation devInfo in deviceCollection)
{
    Debug.WriteLine("{0} {1}", devInfo.Name, devInfo.Id);
    if (devInfo.Name.Contains("1200G"))
    {
        Debug.WriteLine(" Found one");
    }
}

限定裝置選取範圍Scoping the device selection

連接至裝置時,您可能會想要將搜尋限制在 App 可存取之服務點週邊設備的子集。When connecting to a device, you may want to limit your search to a subset of Point of Service peripherals that your app has access to. 您可以使用 GetDeviceSelector 方法,將選取範圍限定為僅擷取透過特定方法 (藍牙、USB 等) 連接的裝置。Using the GetDeviceSelector method, you can scope the selection to retrieve devices connected only by a certain method (Bluetooth, USB, etc.). 您可以建立選取器,搜尋透過 [藍牙][IP][本機][所有連接類型] 連接的裝置。You can create a selector that searches for devices over Bluetooth, IP, Local, or All connection types. 這相當實用,因為相較於本機 (有線) 探索,無線裝置探索需要很長的時間。This can be useful, as wireless device discovery takes a long time compared to local (wired) discovery. 您可以將 FindAllAsync 限制為 [本機] 連接類型,確保本機裝置連線的等待時間可確定。You can ensure a deterministic wait time for local device connection by limiting FindAllAsync to Local connection types. 例如,此程式碼會擷取所有可透過本機連線存取的條碼掃描器。For example, this code retrieves all barcode scanners accessible via a local connection.

string selector = BarcodeScanner.GetDeviceSelector(PosConnectionTypes.Local);
DeviceInformationCollection deviceCollection = await DeviceInformation.FindAllAsync(selector);

使用 DeviceWatcher 回應裝置連線變更Reacting to device connection changes with DeviceWatcher

當您的 App 執行時,裝置有時會中斷或更新,或是需要加入新的裝置。As your app runs, sometimes devices will be disconnected or updated, or new devices will need to be added. 您可以使用 DeviceWatcher 類別來存取裝置相關事件,讓您的 App 可以適當回應。You can use the DeviceWatcher class to access device-related events, so your app can respond accordingly. 以下是 DeviceWatcher 使用方式的範例,如果新增、移除或更新裝置,就會呼叫其中的方法虛設常式。Here’s example of how to use DeviceWatcher, with method stubs to be called if a device is added, removed, or updated.

DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher(selector);
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Removed += DeviceWatcher_Removed;
deviceWatcher.Updated += DeviceWatcher_Updated;

void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
{
    // TODO: Add the DeviceInformation object to your collection
}

void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
{
    // TODO: Remove the item in your collection associated with DeviceInformationUpdate
}

void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
    // TODO: Update your collection with information from DeviceInformationUpdate
}

檢查服務點裝置的功能Checking the capabilities of a Point of Service device

即使在同一裝置類別 (例如條碼掃描器),每個裝置的屬性可能在各型號之間都會有相當大的差別。Even within a device class, such as barcode scanners, the attributes of each device may vary considerably between models. 如果應用程式需要特定裝置屬性,您可能需要檢查每個連接的裝置物件,以判斷是否支援屬性。If your app requires a specific device attribute, you may need to inspect each connected device object to determine whether the attribute is supported. 例如,您的企業或許需要使用特定條碼列印模式來建立標籤。For example, perhaps your business requires that labels be created using a specific barcode printing pattern. 以下是您可檢查以判斷連接的條碼掃描器是否支援特定符號學的方式。Here’s how you could check to see whether a connected barcode scanner supports a symbology.

注意

符號學是條碼用來編碼訊息的語言對應。A symbology is the language mapping that a barcode uses to encode messages.

try
{
    BarcodeScanner barcodeScanner = await BarcodeScanner.FromIdAsync(deviceId);
    if (await barcodeScanner.IsSymbologySupportedAsync(BarcodeSymbologies.Code32))
    {
        Debug.WriteLine("Has symbology");
    }
}
catch (Exception ex)
{
    Debug.WriteLine("FromIdAsync() - " + ex.Message);
}

使用 Device.Capabilities 類別Using the Device.Capabilities class

Device.Capabilities 類別是所有服務點裝置類別的屬性,可用來取得關於每個裝置的一般資訊。The Device.Capabilities class is an attribute of all Point of Service device classes and can be used to get general information about each device. 例如,此範例會判斷裝置是否支援統計資料報告,若不支援,則擷取任何受支援類型的統計資料。For example, this example determines whether a device supports statistics reporting and, if it does, retrieves statistics for any types supported.

try
{
    if (barcodeScanner.Capabilities.IsStatisticsReportingSupported)
    {
        Debug.WriteLine("Statistics reporting is supported");

        string[] statTypes = new string[] {""};
        IBuffer ibuffer = await barcodeScanner.RetrieveStatisticsAsync(statTypes);
    }
}
catch (Exception ex)
{
    Debug.WriteLine("EX: RetrieveStatisticsAsync() - " + ex.Message);
}

宣告服務點裝置Claiming a Point of Service device

在使用服務點裝置可供作用中輸入或輸出之前,您必須宣告該裝置,並授與應用程式對其許多功能的獨佔存取權。Before you can use a Point of Service device for active input or output, you must claim it, granting the application exclusive access to many of its functions. 此範例示範如何在您使用上述其中一個方法找到裝置後,宣告條碼掃描器裝置。This code shows how to claim a barcode scanner device, after you’ve found the device by using one of the methods described earlier.

try
{
    claimedBarcodeScanner = await barcodeScanner.ClaimScannerAsync();
}
catch (Exception ex)
{
    Debug.WriteLine("EX: ClaimScannerAsync() - " + ex.Message);
}

保留裝置Retaining the device

透過網路或藍牙連線使用服務點裝置時,您可能希望與網路上的其他應用程式共用該裝置 When using a Point of Service device over a network or Bluetooth connection, you may wish to share the device with other apps on the network. (如需詳細資訊,請參閱共用裝置)。有時候,您可能想要佔住裝置長時間使用。(For more info about this, see Sharing Devices.) In other cases, you may want to hold on to the device for prolonged use. 此範例示範如何在其他應用程式要求釋放已宣告的條碼掃描器之後保留該裝置。This example shows how to retain a claimed barcode scanner after another app has requested that the device be released.

claimedBarcodeScanner.ReleaseDeviceRequested += claimedBarcodeScanner_ReleaseDeviceRequested;

void claimedBarcodeScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e)
{
    e.RetainDevice();  // Retain exclusive access to the device
}

輸入和輸出Input and output

當您宣告裝置之後,裝置幾乎已可供使用。After you’ve claimed a device, you’re almost ready to use it. 若要接收裝置的輸入,您必須設定並啟用委派才能收到資料。To receive input from the device, you must set up and enable a delegate to receive data. 在以下範例中,我們會宣告條碼掃描器裝置、設定其解碼屬性,然後呼叫 EnableAsync 以啟用裝置的解碼輸入。In the example below, we claim a barcode scanner device, set its decode property, and then call EnableAsync to enable decoded input from the device. 此程序在不同裝置類別中各有不同,如需有關如何設定非條碼裝置委派的指引,請參閱 UWP app 範例This process varies between device classes, so for guidance about how to set up a delegate for non-barcode devices, refer to the relevant UWP app sample.

try
{
    claimedBarcodeScanner = await barcodeScanner.ClaimScannerAsync();
    if (claimedBarcodeScanner != null)
    {
        claimedBarcodeScanner.DataReceived += claimedBarcodeScanner_DataReceived;
        claimedBarcodeScanner.IsDecodeDataEnabled = true;
        await claimedBarcodeScanner.EnableAsync();
    }
}
catch (Exception ex)
{
    Debug.WriteLine("EX: ClaimScannerAsync() - " + ex.Message);
}


void claimedBarcodeScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
{
    string symbologyName = BarcodeSymbologies.GetName(args.Report.ScanDataType);
    var scanDataLabelReader = DataReader.FromBuffer(args.Report.ScanDataLabel);
    string barcode = scanDataLabelReader.ReadString(args.Report.ScanDataLabel.Length);
}

在應用程式之間共用裝置Sharing a device between apps

服務點裝置經常用於多個 App 必須在一小段時間內存取這些裝置的案例。Point of Service devices are often used in cases where more than one app will need to access them in a brief period. 在本機 (USB 或其他有線連線) 或透過藍牙或 IP 網路連接至多個 App 時,可以共用裝置。A device can be shared when connected to multiple apps locally (USB or other wired connection), or through a Bluetooth or IP network. 視每個 App 的需求而定,某一個處理程序可能需要在裝置上處置其宣告。Depending on the needs of each app, one process may need to dispose of its claim on the device. 這個程式碼會處置我們宣告的條碼掃描器裝置,並允許其他 App 宣告和使用該裝置。This code disposes of our claimed barcode scanner device, allowing other apps to claim and use it.

if (claimedBarcodeScanner != null)
{
    claimedBarcodeScanner.Dispose();
    claimedBarcodeScanner = null;
}

注意

已宣告和未宣告的服務點裝置類別都會實作 IClosable 介面Both the claimed and unclaimed Point of Service device classes implement the IClosable interface. 如果裝置透過網路或藍牙應用程式連接至 App,則必須先處置已宣告及未宣告的物件,其他 App 才能進行連接。If a device is connected to an app via network or Bluetooth, both the claimed and unclaimed objects must be disposed of before another app can connect.

另請參閱See also