Windows moible, WinCE uses. NET Compact framework for Bluetooth Broadcast Program Development

Source: Internet
Author: User
Tags getstream unsupported
ArticleDirectory
    • Member Definition
    • Start the service
    • Listener thread
    • Broadcast thread
    • Close service
    • Ui Processing
    • Found
    • Subscription
    • Receive messages
Brief Introduction

This article describes how to broadcast Bluetooth using 32feet. net.ProgramAnd demonstrate the implementation of Broadcom stack in Windows javasie.

Background

In the feedback from 32feet. Net in Bluetooth development under. NET Compact framework, camper9999 hopes to implement the Bluetooth broadcast function. This article is an implementation based on 32feet. Net Bluetooth broadcast.

Proposal of sammylpCodeThe failure is actually caused by improper use of the process. This article demonstrates how to use a thread to prevent the suspension of the UI thread and the program's false death.

Another student (Sorry To forget) asked if 32feet. Net supports Broadcom stack. Therefore, the implementation in this article runs on Windows Mobile where Broadcom stack is installed.

Thank you for your feedback and try to answer it in an article.

For more information about Bluetooth development, see the following articles:

Windows Embedded source tools for Bluetooth development under. NET Compact framework

32feet. Net for Bluetooth development under. NET Compact framework

Bluetooth virtual serial port under. NET Compact framework

Pairing Bluetooth devices under. NET Compact framework

30 days of. Net [Windows Mobile applications]-day 02: Bluetooth Manager)

What is broadcast?

Broadcast is the process of sending messages to the public. A major feature of broadcast is that the message sender does not need to know the existence of the message receiver. Real-life broadcast examples include radio broadcast, GPS satellite broadcast, and Ethernet packet broadcast. However, the so-called Bluetooth broadcast is not a strict broadcast. Because there is a discovery, pairing, or even verification process in the Bluetooth communication process, both parties need to shake hands, and there is no way to implement a strict broadcast. This example implements a multicast process (Multicast) by registering and subscribing ).

 

Implement Server

The server monitors and registers services, and sends messages to registered devices. In this example, the server uses PC as the server, but Windows Internet Explorer can be used as the server. The 32feet.net library is basically compatible with PC and CE.

Member Definition
PrivateDescrithlistenerListener;
Private boolListening =True;
PrivateList<Bluetoothclient> Clientlist =NewList<Bluetoothclient> ();
PrivateSystem. threading.ThreadListenthread;
PrivateSystem. threading.ThreadBroadcastthread;

Listener is responsible for listening services, clientlist stores registered devices, listenthread is responsible for listening threads, and broadcastthread is responsible for broadcasting threads.

Start the service
 Bluetoothradio Radio = Bluetoothradio . Primaryradio;
If (Radio = Null )
{
Writemessage ( "No radio hardware or unsupported software stack" );
Return ;
}

// Enable discoverable Mode
Radio. mode = Radiomode . Discoverable;
Writemessage ( "Radio name :" + Radio. Name );
Writemessage ( "Radio Address :" + Radio. localaddress );
Writemessage ( "Radio mode now :" + Radio. mode. tostring ());

Listener = New Descrithlistener ( Bluetoothservice . SerialPort );
Listener. Start ();

Listening = True ;
Listenthread = New System. threading. Thread (Listenloop );
Broadcastthread = New System. threading. Thread (Broadcastloop );
Listenthread. Start ();
Broadcastthread. Start ();
Writemessage ( "Service started! " );

The process for starting a service is:

1. Check whether the bluetooth device is ready.

2. Set the bluetooth device to discoverable.

3. Start the Bluetooth listener. The service type configured here is the serial port service. You also need to configure the serial port service type on the client for communication.

4. Start the listening thread so that the main thread will not be suspended ).

5. Start the broadcast thread.

Listener thread
 Private void Listenloop ()
{
Byte [] Buffer =New byte [4];
String Datatosend = "Thanks for subtasks" ;
Byte [] Databuffer = system. Text. Asciiencoding . ASCII. getbytes (datatosend );

While (Listening)
{
Try
{
Bluetoothclient Client = listener. acceptbluw.thclient ();
Writemessage ("Get a subscribe from" + Client. remotemachinename );
Clientlist. Add (client );
System. Io. Stream NS = client. getstream ();
NS. Write (databuffer, 0, databuffer. Length );
}
Catch
{
Break ;
}
}
Listener. Stop ();
}

The listening thread processes the listening subscription request and adds the subscribed device to the subscription list. Acceptblustmthclient () suspends the modification thread until a new device is subscribed.

Broadcast thread
 Private void Broadcastloop ()
{
List < Bluetoothclient > Tempclientlist = New List < Bluetoothclient > ();

While (Listening)
{
System. threading. Thread . Sleep (5000 );

String Datatosend = "Broadcast message" + System.Datetime . Now. tolongtimestring ();
Byte [] Databuffer = system. Text. Asciiencoding . ASCII. getbytes (datatosend );

Tempclientlist. Clear ();
Foreach ( Bluetoothclient Client In Clientlist)
{
Try
{
System. Io. Stream NS = client. getstream ();
NS. Write (databuffer, 0, databuffer. Length );
Writemessage ( "Sent message" + Client. remotemachinename );
}
Catch
{
// Connection is broken.
Tempclientlist. Add (client );
Continue ;
}
}

// Clean up the broken connections.
Foreach ( Bluetoothclient ClientIn Tempclientlist)
{
Clientlist. Remove (client );
}
}
}

The broadcast thread broadcasts messages to subscribed devices and manages disconnected connections. In actual application, this thread needs to change the business process as needed.

Close service
 
Writemessage ("Service stop! ");
Listening =False;
If(Listener! =Null)
{
Listener. Stop ();
}

Release listening resources.

Ui Processing

Because multiple threads are used, the UI cannot be updated directly. Therefore, you must use the delegate and invoke () functions to update the UI.

Public Delegate voidSafewinformsthreaddelegate(StringMSG );
Private voidWritemessage (StringMSG)
{
SafewinformsthreaddelegateD =NewSafewinformsthreaddelegate(Updateui );
Invoke (D,New Object[] {MSG });
}

Private voidUpdateui (StringMSG)
{
If(Listboxmsg. Items. Count> 100)
{
Listboxmsg. Items. removeat (0 );
}
Listboxmsg. selectedindex = listboxmsg. Items. Add (MSG );
}

 

Client

The client discovers the server device, initiates a subscription request, and then receives broadcast messages. The client uses Windows Mobile with Broadcom stack installed. In fact, it also supports Ms stack.

Found
 Bluetoothradio Radio = Bluetoothradio . Primaryradio;
If (Radio = Null )
{
Writemessage ( "No radio hardware or unsupported software stack" );
Return ;
}

// Broadcom stack doesn' t support the functionality to turn on the Bluetooth, turn it on manually please
// Radio. mode = radiomode. connectable;

// Scan the nearby devices
Listboxdevices. Items. Clear ();
Bluetoothdeviceinfo [] Devices = client. discoverdevices ();
Listboxdevices. datasource = devices;
Listboxdevices. displaymember = "Devicename" ;
Listboxdevices. valuemember = "Deviceaddress" ;

Writemessage ( "Discover successful, please select one device to subscribe ." );

Because the current version of 32feet.net does not support setting the Bluetooth status in Broadcom stack, if the device is a Broadcom stack, You need to block the statements for setting the Bluetooth status. Display the detected devices in ListBox.

Subscription
 
BluetoothaddressDeviceaddress = listboxdevices. selectedvalueAsBluetoothaddress;
Client. Connect (deviceaddress,Bluetoothservice. SerialPort );
Writemessage ("Connected"+ Client. remotemachinename );
Stream = client. getstream ();
Processing ing =True;
System. threading.ThreadT =NewSystem. threading.Thread(Canceloop );
T. Start ();

Connect to the server based on the address of the detected device, and then start the thread to receive messages.

Receive messages
Private voidReceiveloop ()
{
Byte[] Buffer =New byte[255];

While(Grouping)
{
If(Stream. Canread)
{
Stream. Read (buffer, 0,255 );
StringData = system. Text.Asciiencoding. ASCII. getstring (buffer, 0,255 );
Writemessage (data );
}
}
}

Receives messages in the thread to prevent the main UI thread from dying.

 

Source code: Http://files.cnblogs.com/procoder/BtBroadcast.rar

Platform: Visual Studio 2008 + Windows Mobile 5 packet PC SDK

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.