[转载]蓝牙4-Android BLE开发官方文档翻译
AndroidBLE开发——Android手机与BLE终端通信初识

AndroidBLE开发——Android⼿机与BLE终端通信初识设备:MX5⼿机⼀台,农药残留检测仪⼀台(BLE终端设备)⽬的:实现⼿机控制仪器,如发送打印指令,仪器能进⾏打印操作等关于如何打开蓝⽛,配置相关权限,搜索BLE设备等步骤⽹上有很多资料,这⾥就不多做作解释了,本⽂主要讲通信⽅⾯的内容。
需要注意的是搜索BLE设备的结果是异步返回的,在BluetoothAdapter.LeScanCallback这个回调中返回,并且搜索过程是⼀个⾮常耗电的过程,所以我们应该做好相应处理,例如可以让它搜索10s就停⽌搜索等。
在我们理解Android设备与BLE终端设备通信过程之前,我们需要来先了解⼏个类:BluetoothGatt:BluetoothGatt 是我们⽤的最多,也是我们最重要的⼀个类,为了尽可能通俗的理解,这⾥我们可以把它看成Android ⼿机与BLE终端设备建⽴通信的⼀个管道,只有有了这个管道,我们才有了通信的前提。
BluetoothGattService:蓝⽛设备的服务,在这⾥我们把BluetoothGattService⽐喻成班级。
⽽Bluetoothdevice我们把它⽐喻成学校,⼀个学校⾥⾯可以有很多班级,也就是说我们每台BLE终端设备拥有多个服务,班级(各个服务)之间通过UUID(唯⼀标识符)区别。
BluetoothGattCharacteristic:蓝⽛设备所拥有的特征,它是⼿机与BLE终端设备交换数据的关键,我们做的所有事情,⽬的就是为了得到它。
在这⾥我们把它⽐喻成学⽣,⼀个班级⾥⾯有很多个学⽣,也就是说我们每个服务下拥有多个特征,学⽣(各个特征)之间通过UUID(唯⼀标识符)区别。
总结:当我们想要⽤⼿机与BLE设备进⾏通信时,实际上也就相当于我们要去找⼀个学⽣交流,⾸先我们需要搭建⼀个管道,也就是我们需要先获取得到⼀个BluetoothGatt,其次我们需要知道这个学⽣在哪⼀个班级,学号是什么,这也就是我们所说的serviceUUID,和charUUID。
蓝牙中英文翻译

BluetoothIntroductionBluetooth is a forever, limited radio connect that resides o n a microchip. It was originally expanded through Swedish mo bile phone creator Ericsson in 1994 as a method to let lap top computers make calls above a mobile phone. As then, num erous organizations have signed on to create Bluetooth the low-power thoughtless wireless average for a broad variety ofdevices (LeVitus, 216-220). Industry spectators anticipate Bluetooth to be fitted in billions of devices through 2005. DiscussionDeveloped by engineers at Ericsson in the late 1990s, Blue tooth is more and more special technology that facilitates t houghtless wireless communication among a diversity of electro nic devices. Its mainly important aspect is that it permits devices to “talk”(relocate and orchestrate data) wirelessly with each other, terminating the requirement for the outwar dly continuous tangle of cables, cords, and adapters importan t for numerous today’s expertise.The Bluetooth Special Interest Group (SIG) was formed in 1 998 to manage the expansion and prologue of Bluetooth knowle dge (LeVitus, 216-220). IBM, Intel, Toshiba and Nokia connected with Ericsson as the beginning associates of the SIG, and in exc ess of 8,000 organizations have contracted since. So as to trade products with the Bluetooth requirement and logo, manufacturers should be associates of the SIG and the devices should meet well-outlined credentials. These procedures makesure that Bluetooth wireless devices international may converse with each other, apart from company or nation ofderivation.Speed and RangeRange is application specific and although a minimum rangeis mandated by the Core Specification, there is not a limit and manufacturers can tune their implementation to support the use case they are enabling.Range may vary depending on class of radio used in an impl ementation:·Class 3 radios-have a range of up to 1 meter or 3 feet ·Class 2 radios-most commonly found in mobile devices, have arange of 10 meters or 33 feet.·Class 1 radios-used primarily in industrial use cases,have a range of 100 meters or 300 feet.That creates Bluetooth technology appropriate for transporting lesser files for example cell phone contracts and text documents, also as lower-quality pictures and audio (Kumkum, 160-162).At these relocate speeds; Bluetooth may not actually deal st reaming video or high-quality pictures and audio at this end, except this possibly will alter in the future when fresh Bl uetooth standards are initiated.Simple and Competent to UtilizeCreating and configuring Bluetooth allowed devices is modera tely uncomplicated, with little extra commotion than acquire the two devices close to one another and twist them on.There is no requirement to mount drivers or further software to complex an ad-hoc, personal wireless network (Kumkum, 160-162). It has a uniform organization, meaning that some two wireless products attributing Bluetooth technology,despite of productor nation of origin, have the ability to converse faultlessly with each other.Common ApplicationsOne of the mainly ordinary applications of Bluetooth is hand s -free cell phone procedure. About each cell phone fashioned in our day has constructed Bluetooth (Meier, 15-20). Only pair phone with a Bluetooth headset, and he may talk whereas his phone is in his purse or pocket. Several of today’s car stereo s as well have fitted Bluetooth for hands-free calling in his vehicle. And if his vehicle has a plant stereo or grown-up aftermarket one that he merely doesn’t wish to restore, he may yet like hands-free identifying with a Bluetooth car kit. Bluetooth 3.0Bluetooth 3.0 is the fresh Bluetooth wireless typical adopted through the Bluetooth SIG on April 21, 2009. The fresh st andard supports elevated data remove speeds and constructs ah ead the preceding standards (Meier, 15-20). With its superior speed, the technology has the probable to transfigure the co nsumer electronics industry.PROTOCOLThe Bluetooth technology standard is set to make different a pplications can “communicate”with each other. Remote device s in communication use the same protocol stacks, while diffe rent applications need different protocol stacks. But, every application needs the data link layer and physical layer of the Bluetooth technology.The whole Bluetooth protocol stacksis shown as blow. Not any application should use all of the protocols, but one or some lists of these. The chart b elow shows the relationship between protocols, but the relati onship may change in some applications.The completely protocol stacks include Bluetooth special proto cols (like LMP and L2CAP) and not special ones (such as OB EX and UDP). The basic principle for designing protocol and protocol stacks is that use existing highlevel protocol as p ossible, ensure the combination of protocols and Bluetooth te chnology, and take the best advantage of the software and h ardware which adapt to the Bluetooth technology standards. Th e open Bluetooth technology makes device manufacturers can ch oose protocols freely as they like or used to.The protocols in Bluetooth protocol system.There are four layers in Bluetooth protocol system accordingto the SIG:·Core protocols·Cable replacement protocols·Telephony control protocols·Adopted protocolsExcept the protocol layers above, the standard also defines Host/Controller Interface (HCI),which provides command interface for baseband controller, connection manager, hardware state and control register.Bluetooth core protocols consist of the special protocols mad e by SIG. Most Bluetooth devices need core protocols, while other protocols are used depend on needs of the application. After all, cable replacement protocols, technology control p rotocols and adopted protocols based on the core protocols c onstitute the object-oriented protocols.·Core protocols·LMP (Link Management Protocol)Used for control of the radio link between two devices. Implemented onthe controllers.It identifies and encrypts through launching, exchanging and checking the connection, and decides the size of baseband da ta packets through conference. It also controls the power mo de and work cycle of wireless equipment, and connection stat us of unit equipment in piconet.·L2CAP (Logical Link Control & Adaptation Protocol)This protocol is used to multiplex multiple logical connectio ns between two devices using different higher level protocols, and provides segmentation and reassembly of on-air packets.In Basic mode, L2CAP provides packets with a payload configu rable up to 64kB, with 672 bytes as the default MTU, and 48 bytes as the minimum mandatory supported MTU.In Retransmission & Flow Control modes, L2CAP can be configu red for reliable or isochronous data per channel by performi ng retransmissions and CRC checks.Bluetooth Core Specification Addendum 1 adds two additional L 2CAP modes to the core specification. These modes effectively deprecate original Retransmission and Flow Control modes:·Enhanced Retransmission Mode (ERTM): This mode is an improv ed version of the original retransmission mode. This mode pr ovides a reliable L2CAP channel.·Streaming Mode (SM): This is a very simple mode, with no retransmissionor flow control. This mode provides an unreliabl e L2CAP channel.Reliability in any of these modes is optionally and/or addit ionally guaranteed by the lower layer Bluetooth BDR/EDR air interface by configuring the number of retransmissions and fl ush timeout (time after which the radio will flush packets).In-order sequencing is guaranteed by the lower layer.Only L2CAP channels configured in ERTM or SM may be operated over AMP logical links.·SDP (Service Discovery Protocol)Service Discovery Protocol (SDP) allows a device to discover services supported by other devices, and their associated par ameters. For example, when connecting a mobile phone to a B luetooth headset, SDP will be used for determining which Blu etooth profiles are supported by the headset (Headset Profile, Hands Free Profile, Advanced Audio Distribution Profile (A2DP) etc.) and the protocol multiplexer settings needed to connect to each of them. Each service is identified by a Universally Unique Identifier (UUID), with official services (Bluetooth profiles) assigned a short form UUID (16 bits rather than t he full 128)/vichitra·Cable replacement protocols(RFCOMM)Radio frequency communications (RFCOMM) is a cable replacement protocol used to create a virtual serial data stream. RFCOMM provides for binary data transport and emulates EIA-232 (formerly RS-232) control signals over the Bluetooth baseband layer.RFCOMM provides a simple reliable data stream to the user, similar to TCP. It is used directly by many telephony relat ed profiles as a carrier for AT commands, as well as being a transport layer for OBEX over Bluetooth.·Telephony control protocols (TCP).Telephony control protocol-binary (TCS BIN) is the bit-oriented protocol that defines the call control signaling for the establishment of voice and data calls between Bluetoothdevices. Additionally, “TCS BIN defines mobility management p rocedures for handling groups of Bluetooth TCS devices.”TCS-BIN is only used by the cordless telephony profile, which failed to attract implementers. As such it is only of historical interest.Adopted protocolsAdopted protocols are defined by other standards-making organizations and incorporated into Bluetooth’s protocol stack, allowing Bluetooth to create protocols only when necessary. T he adopted protocols include:·Point-to-Point Protocol (PPP): Internet standard protocol for transporting IP datagrams over a point-to-point link.·TCP/IP/UDP: For communicating with the device connected to Internet.·Object Exchange Protocol (OBEX): Session-layer protocol for the exchange of objects, providing a model for object and operation representation. It uses the client-server mode.· Wireless Application Environment/Wireless Application Protocol (WAE/WAP):WAE specifies an application framework for wireless devices and WAP is an open standard to provide mobile users access to telephony and information services.TechnologySPECTRUM AND INTERFERENCEBluetooth technology operates in the unlicensed industrial, sc ientific and medical (ISM) band at 2.4 to 2.485 GHz, usinga spread spectrum, frequency hopping, full-duplex signal at a nominal rate of 1600 hops/sec. The 2.4 GHz ISM band is ava ilable and unlicensed in most countries.SIM frequency band is open to all radio system, So the useof a certain frequency band will meet unpredictable interfe rence sources. Therefore, Bluetooth designs special fast ackno wledge and frequency hopping technique to ensure the stabilit y of link. Frequency hopping technique to divide the band i nto many frequency hopping channels, in a connection, radio transceiver “jump”from a channel to another constantly acc ording to certain code sequence. Only sender and receiver co mmunicate according to this law, and the rest of interferenc e may not press the same rule. The instantaneous bandwidth of Frequency hopping is very narrow, but through the spread spectrum technology it can make the narrow bandwidth one h undred times expanded into wideband, making the influence of interference may become very small. Comparing to other syst ems that work in the same frequency band, frequency hopping of Bluetooth works faster, data packet of Bluetooth is sho rter, which make it more stable than the other.ERROR CORRECTIONBluetooth supports circuit switching and packet switching two techniques, and defines two types of link connection, namel y connection-oriented synchronous link (SCO) and connectionless-oriented asynchronous link (ACL).Bluetooth use three error correction models:1/3 Forward Error Correction (FEC), 2/3forward Forward Error Correction and Au tomatic Repeat Request (ARQ). Purpose to the error correction is to reduce the possibility of retransmission, while at t he same time increase the extra expenses, but in a reasonab le errorless environment, redundant bids will reduce output. So the packet definition itself also keeps flexible ways. He nce the software can be defined whether to adopt FEC. In general, when the channel noise is large, Bluetooth system will uses FEC, in order to ensure the quality of communication: as to SCO link, 1/3 FEC is used; 2/3 FEC is used in ACL link. In Unnumbered ARQ, the data send in a time slot must receive a confirmation of receipt in the next time slot. On ly when the data is checked to be without mistake after he ader error detection and CRC at receiver will the confirmati on sent to sender, or an error message will be sent back. RANGERange is application specific and although a minimum range i s mandated by the Core Specification, there is not a limit and manufacturers can tune their implementation to support the use case they are enabling.Range may vary depending on class of radio used in an impl ementation:Class 3 radios-have a range of up to 1 meter or 3 feet. Class 2 radios-most commonly found in mobile devices , have a range of 10 meters or 33 feet.Class 1 radios-used primarily in industrial use cases , have a range of 100 meters or 300 feet.POWERIn order to make a Bluetooth equipment can also be in conn ection even in a very low power state, Bluetooth stipulates three energy saving state: Park state, Hold state and Snif f state. The energy saving efficiency of these states declin es one by one.The most commonly used radio is Class 2 and users 2.5mW of power. Bluetooth technology is designed to have very low p ower consumption. This is reinforced in the specification byallowing radios to be powered down when inactive.The Generic Alternate MAC/PHY in Version 3.0 HS enables the discovery of remote AMPs for high speed devices and tums on the radio only when needed for data transfer giving a p ower optimization benefit as well as aiding in the security of the radios.Bluetooth low energy technology, optimized for devices requiri ng maximum battery life instead of a high data transfer rat e, consumers between 1/2 and 1/100 the power of classic Blu etooth technology.SECURITYMobility and open of Bluetooth system makes safety problems extremely important. Although the frequency modulation techniqu e used by Bluetooth system has already provided a certain s ecurity, but Bluetooth system still need safety management to link layer and application layer. In link layer, Bluetooth system provides authentication, encryption and key management, and other functions. Each user has a Personal Identificatio n Number (PIN), which will be translated into 128 bit link key for one-way or both-way certification. Once the authentication finished, link will use encryphon key to encrypt. The link layer security mechanism provides a great deal of certification schemes and a flexible encryption scheme (means allow the consultation of the length of password). This me chanism is very important when the equipments in communicatio n are from different countries, because some countries will specify maximum password length. Bluetooth system will select the smallest maximum allowable password length of all equip ments in the piconet.Bluetooth system also supports the high level of protocol st ack in different applications of special security mechanisms. Bluetooth security mechanism builds trust relationship betwee n devices relying on pins. Once this relationship established , these pins can be stored in the equipment, in order to connection more quickly the next time.Source: Baidu Library蓝牙介绍蓝牙是一种永久、有限的无线连接,驻留在微芯片上。
蓝牙技术外文翻译文献

蓝牙技术外文翻译文献(文档含中英文对照即英文原文和中文翻译)蓝牙的起源与发展摘要本文论述蓝牙技术的起源与发展。
重点介绍蓝牙技术的基本原理以及蓝牙技术在当今时间的作用。
论述了蓝牙技术的优点与缺陷以及未来的发展趋势关键字:协议、技术、应用、发展介绍蓝牙是一个永远的,有限的无线电连接驻留在一个芯片。
它最初是在1994年扩大,作为一种方法,让笔记本电脑作出上述呼吁手机通过瑞典手机爱立信的创造者。
然后,许多组织已经签署了创建蓝牙低功耗平均各种各样的设备(LeVitus,216-220)的无线轻率。
业内观众预期蓝牙在安装设备的十亿美元,到2005年。
讨论蓝牙是由爱立信工程师在20世纪90年代末开发,越来越多的特殊的技术,有利于无线通信电子设备的多样性之间的轻率。
其主要的一个重要方面是,它允许设备“对话”(搬迁和协调数据)无线对方,终止向外不断纠结,电线,电缆和适配器许多今天的专长重要的要求。
蓝牙特别兴趣小组(SIG)成立于1998年,管理蓝牙知识的扩展和序幕(LeVitus,216-220)。
IBM,英特尔,东芝,诺基亚与爱立信的SIG开始联营,超过8000组织承包以来。
因此,贸易与蓝牙的要求和标志的产品,制造商应该是联营公司的SIG和设备应符合轮廓的凭据。
这些程序确保蓝牙无线设备的国际可与对方交谈,除了派生公司或国家。
速度和范围范围是特定应用和核心规范的规定,虽然最小的范围内是不是有限制,制造商可以调整其实施,以支持使用的情况下,他们正在使。
范围可能有所不同取决于在执行用无线电类:3级收音机 - 有一个范围可达1米或3英尺2类无线电 - 移动设备中最常用的发现,有一个10米或33英尺的范围1类无线电 - 主要用于工业用途的案件中,有一个100米或300英尺的范围创建适合运送较小的文件,例如手机合同和文本文件的蓝牙技术,也为低质量的图像和音频(Kumkum,160-162)。
在这些搬迁速度;蓝牙可能无法实际处理视频流或高品质的图片和音频,为此,除这可能会在未来改变时,新鲜的蓝牙标准发起。
Android Bluetooth API 翻译

Android.bluetoothandroid.bluetooth提供了皆如扫描设备、连接设备以及对设备间的数据传输进行管理的类,这些类对蓝牙设备进行功能性管理。
蓝牙模块API提供的应用包括了:●扫描其它蓝牙设备●通过查询本地蓝牙适配器来匹配蓝牙设备●建立RFCOMM(无线射频通信协议)的通道/端口●从其他的蓝牙设备中连接到指定的端口●传输数据到其他设备,或者从其他设备中接收数据如需运用这些API来执行蓝牙通信,应用程序必须声明BLUETOOTH许可。
对于皆如寻找设备请求等的一些附加功能,也同样需要BLUETOOTH_ADMIN许可。
如需要使用蓝牙API的更详细的指引,参看Bluetooth Dev Guide topic.ClassesBluetoothAdapter代表本地的蓝牙适配器设备BluetoothClass代表一个描述了设备通用特性和功能的蓝牙类BluetoothClass.Device定义了所有设备类的常量BluetoothClass.Device.Major定义了所有主要设备类的常量BluetoothClass.Service定义了所有服务类的常量BluetoothDevice代表一个远程的蓝牙设备BluetoothServerSocket监听蓝牙服务的端口BluetoothSocket一个双向连接的蓝牙端口public final classBluetoothAdapterextends Objectng.Object↳ android.bluetooth.BluetoothAdapterClass Overview代表本地的蓝牙适配器设备。
BluetoothAdapter类让用户能执行基本的蓝牙任务。
例如:初始化设备的搜索,查询可匹配的设备集,使用一个已知的MAC地址来初始化一个BluetoothDevice类,创建一个BluetoothServerSocket类以监听其它设备对本机的连接请求等。
蓝牙-翻译

蓝牙-翻译ABSTRACTMore and more digital electronics products through new technology to enhance their performance and strength. Current development trend, the future consumerelectronics products will have two important development indicators, one of these open technologies to use Bluetooth technology, wireless, local area network, a network of portable devices extension of the body. Another is the memory size of unity, encryption and lightweight applications. Bluetooth is a short-range wireless communications, technical specifications, its original goal is to replace the existing handheld computers, mobile phones and other digital devices on a cable connection. Early in the development of the Bluetooth specification, on the establishment of a unified global target, to a global public release, working band and open for global unity 2.4GHz industrial, scientific and medical (Industrial, Scientific and Medical, ISM) band. From the current application view, as Bluetooth small size, low power, its application is not limited to computer peripherals can be integrated into almost any digital device among Particularly those less demanding on the data transmission rate of mobile devices and portable devices.Bluetooth aimed at three categories of applications: voice / data access,peripherals, Internet and Personal Area Network. Voice / data access is one computing device through a secure wireless link to connect to a communications device, complete with wide-area communications network interconnection. Peripheral equipment is connected to a variety of peripherals via Bluetooth link toconnect to the host.The main application is the personal area network and personal information sharing and exchange. The emergence of a new technology, people's expectations tend to hold it high, often short term is not satisfactory, because any new technology need to have a process, Bluetooth is no exception; technical standards harmonization, Zhi Shi the advantage of sharing property rights is very clear, I believe that through the joint efforts of the industry, its future is limitless in the long run may exceed people's imagination.When you use computers, entertainment systems or telephones, the various pieces and parts of the systems make up a community of electronic devices. These devices communicate with each other using a variety of wires, cables, radio signals and infrared light beams, and an even greater variety of connectors, plugs and protocols.There are lots of different ways that electronic devices can connect to one another.For example:Component cablesElectrical wiresEthernet cablesWiFiInfrared signalsThe art of connecting things is becoming more and more complex every day. In this article, we will look at a method of connecting devices, called Bluetooth, that canstreamline the process. A Bluetooth connection is wireless and automatic, and it has a number of interesting features that can simplify our daily lives.1.1Purpose and meaning of researchMore and more digital electronic products with new technology to increase performance and capabilities of itself. At the current development trend, the future there will be two important consumer electronics development indicators, one is use open technology, Bluetooth technology to wireless local area network and portable devices become an extension of the network. Another is the unification of the memory specifications, encryption, and lightweight applications. Whether you like it or not, "Bluetooth plan" this noun has reached almost any state, whether it is business platform, the general public television or financial reports are not only more than once the project progress and news, having said that, but few people understand the meaning and context of the plan, only know that there is such a plan is underway, and huge, seems to be full of infinite hope. Bluetooth technology for information construction of our country, is both challenge and opportunity. We sincerely hope that with our country independent intellectual property rights of Bluetooth products on the market at an early date, also hope to have more people pay attention to and support the growth and development of Bluetooth technology in our country, perhaps in the near future, people will be surprised to find that our work and life are gradually become "blue". Bluetooth is a short-range wireless communication specification, its initial goal is to replace the existing handheld computers, mobile phones and other digital equipment cable connection. In setting at the beginning of the Bluetooth specification, the establishment of a unified global goal, to the global public, working frequency band for the global unification open 2.4 GHz Industrial, Scientific and Medical, Industrial, Scientific and Medical, ISM frequency band. From thepoint of the present application, because the Bluetooth small size, low power, its application is not limited to computer peripherals, can be integrated into almost any digital device, especially those requirements for data transfer rate is not high and portable and mobile devices.1.2 The Origin of BluetoothBluetooth in the 10th century unification of Denmark and Sweden a Scandinavian king's name. It breeds are magical prospects: for mobile phone, and no longer need the attachment between headphones; On a personal computer, between the host and the keyboard, display and printer can get rid of the tumultuous attachment; In a larger scope, refrigerators, microwave ovens and other household appliances can be connected to the computer network, to realize intelligent operation. Invention is the Swedish telecoms giant Ericsson Bluetooth technology. Because the technology has the very good application prospect, in May 1998, five of the world's top communication/computer company: Ericsson, Nokia, Toshiba, IBM and Intel after consultations, jointly set up the Bluetooth (Bluetooth SIG) common interest group, the purpose is to accelerate its development, promotion and application. After the wireless communication technology, quickly got including MOTOROLA, 3 com, lucent, a large number of Siemens company's consistent support, has joined the Bluetooth SIG company has reached more than 2000, including many of the world's most famous enterprise in the field of computer, communication and consumer electronics, and even cars and camera manufacturers and manufacturers. A public specification can get industry so much attention and support, this shows that products will be based on the Bluetooth technology has broadapplication prospect and huge potential market. Bluetooth common interest group is now renamed Bluetooth promotion group.1.3 The Definition of BluetoothBy Bluetooth (Bluetooth) technology, is actually a short-range radio technology, using the "Bluetooth" technology, can effectively simplify the PDA, notebook computer and mobile phone communication between mobile phones and other mobile communication terminal equipment, can successfully simplify between these devices and the Internet, the Internet communication, so that the modern communication equipment and data transmission between the Internet become more efficiently, to broaden the way with wireless communications. Said very popular, is Bluetooth technology makes the modern some easily carry mobile communications equipment and computer equipment, without cable can be connected to the Internet, and can realize the wireless Internet, the scope of its practical application can also be extended to all kinds of electrical appliances product information such as home appliance, consumer electronics and cars, forming a huge wireless communication network."Bluetooth" technology belongs to a kind of short distance wireless connection technology, low cost, is a way to realize the openness of the voice and data wireless transmission scheme, therefore, the wireless communication of "Bluetooth" just show a little shoot tips, has caused the global communications industry and the close attention of users.Bluetooth MechanismBy embedding short-range transceivers that are inexpensive and tiny, into new electronic devices that are available nowadays, Bluetooth achieves its goal. In addition to three voice channels,Bluetooth can transfer data at data transferring speed up to 721 Kbps. As Bluetooth operates on radio band, at frequency of 2.45 GHz, that is unlicensed and globally available, people or “international travelers” have no obstructions to use Bluetooth-enabled equipment. Moreover, Bluetooth units might be either externally adapted or built into electronics devices. E.g. in a personal computer, Bluetooth devices can be built into the motherboard as a PC card or on the other hand it can be used as an external Bluetooth adaptor through connecting it to a USB port. From the IEEE 802 standard, each Bluetooth device has its own 48-bit address. One feature is that connections are not only point to point, but they can also be multipoint connections. Usually, Bluetooth devices have a maximum range of connection up to 10 meters. However, by increasing the power, the range of connection might be extended to 100 meters. Bluetooth devices have atechnique called frequency hopping. The main purpose of this technique is to protect the devices from radio interference. The mechanism of the technique is that Bluetooth devices change arbitrarily their frequency maximally 1600 times/s. when an error occurs, it will be immediately corrected by the three complimentary error correction schemes that any Bluetooth device has. Bluetooth devices are also provided with built in verification and encryption.When Bluetooth device s are in a “hold” mode they consume approximately 30 micro Amperes from the battery of the electronic devices, such as cell phones and laptops, while they consume a range of 8 to 30 milliamps, less than one tenth of a watt, when they are in the active transmission mode. Moreover, only 0.3 mA are consumed by the radio chip, when in a standbymode, which means that it's less than 3 % of the power that is used by a mobile phone. Also, the radio chip has an excellent power-saving feature that is as soon as the traffic volume lessens, the chip shifts automatically to a low-power mode. The above indicates that Bluetooth devices do not drain precious battery life.But beyond un-tethering devices by replacing the cables, Bluetooth devices can form a small and private ad hoc grouping of devices that are away from fixed network infrastructures by providing universal bridges. These bridges are to connect between a device, data networks and a peripheral interface. Furthermore, noisy radio frequency environment does not affect Bluetooth devices since they are designed to use a scheme called frequency hopping scheme and as well as a fast acknowledgment in order to make the link active and strong. After sending or receiving a packet, Bluetooth radio modules keep away from in terference from other radio signals by jumping “hopping” to a new frequency. The Bluetooth radio uses shorter packets and jumps “hops” faster than other systems that are operatin g in the identical frequency band the thing that makes the Bluetooth radio more active and stronger than other systems. In addition, these fast hopping from a frequency to another and the short packages decrease the impact of domestic microwave ovens. Random noise may affect long-distance links. However, Forward Error Correction (FEC) is used to eliminate this impact. The encoding is, then ideal for an uncoordinated environment.At the bit level, Bluetooth security is guaranteed. Users can control the authentication by using a 128 bit key where radio signals are coded with 8 to 128 bits. The Bluetooth radio transmissions match the safety standards that are required by the countries where the technology is used with respect to the effectsof radio transmissions on the human body. Bluetooth enabled devices' emissions are less than those from industry-standard cordless phones. Also, Bluetooth module do not interfere, cause harm or even affect public or private telecommunications network.Bluetooth and the InternetOne of the most important advantages of Bluetooth is that it enables you to connect a device provided with internet connectivity to another device that is not. E.g. you might connect your hand phone that has a built-in Bluetooth to your laptop that has a Wi-Fi via Bluetooth connection. Then, via you laptop's Wi-Fi, if exists, to a Wi-Fi router. Once your laptop is connected to the internet you can enable your hand phone to be connected to the internet as well. Moreover, this example goes correctly to most of the devices that have Bluetooth technology not only hand phones. Buying a device that has a Wi-Fi or buying another that has a Bluetooth technology is sometimes a confusing choice. One may think that by choosing Bluetooth he/she will not be able to connect to the internet and in this case choosing a Wi-Fi would be better.However, this is not such a really correct choice. Since, from the above example, you can modify your device to get connected to the internet via the Bluetooth technology purchasing a device that has a Bluetooth technology is a better choice as you can get two technologies in one ; internet connectivity (the function of Wi-Fi is achieved) and Bluetooth technology.Some Other Applications1.A Bluetooth-mouse could be used at a further distance from a monitor, and while moving about in the room.2.A Bluetooth-keyboard could be used further away from themonitor. This would reduce eye-strain for persons who are long-sighted. Increasing the distance would also reduce exposure to electromagnetic radiation from the monitor.3.A Bluetooth-keyboard could also be used to address more than one computer, in a dynamic, switchless manner.4.You can use your e-mail while your laptop lies in a briefcase; when your laptop receives an E-mail your mobile phone will immediately alert you and then, you can read the received e-mails in your mobile phone's display.5.A businessman may enable his laptop to find a suitable printer once he enters a company. As soon as a suitable printer is found, data will be sent from the laptop to that printer via Bluetooth connection to print it out.6.Make a connection to printers and faxes without messy cables.7.Wireless connection to video projectors and digital cameras.8.An easy and elegance connection from cell phone to handsfree headset.9.A useful connection between Bluetooth interface to office private branch exchange (PBX).10.Smooth creating of dial up networks and automatic e-mail./doc/e54790284.html,e mobile phones as office wireless phones./doc/e54790284.html,e of personal computers or PDAs (Personal Digital Assistants) as hands-free phone.13.Automatic transferring and swapping of files, software, electronic business cards, calendars etc.14.Dancing couples at a dance hall could receive the music through their headsetsand pick the dance of their choiceNot to mention many more to come.T he ProblemWhen any two devices need to talk to each other, they have to agree on a number of points before the conversation can begin. The first point of agreement is physical: Will they talk over wires, or through some form of wireless signals? If they use wires, how many are required -- one, two, eight, 25? Once the physical attributes are decided, several more questions arise:How much data will be sent at a time? For instance, serial ports send data 1 bit ata time, while parallel ports send several bits at once.How will they speak to each other? All of the parties in an electronic discussion need to know what the bits mean and whether the message they receive is the same message that was sent. This means developing a set of commands and responses known as a protocol.Bluetooth offers a solution to the problem.How Bluetooth Creates a ConnectionBluetooth takes small-area networking to the next level by removing the need for user intervention and keeping transmission power extremely low tosave battery power. Picture this: You're on your Bluetooth-enabledcell phone, standing outside the door to your house. You tell the person on the other end of the line to call you back in five minutes so you can get in the house and put your stuff away. As soon as you walk in the house, the map you received on your cell phone from your car's Bluetooth-enabled GPS system isautomatically sent to yourBluetooth-enabled computer, because your cell phone picked up a Bluetooth signal from your PC and automatically sent the data you designated for transfer. Five minutes later, when your friend calls you back, your Bluetooth-enabled home phone rings instead of your cell phone. The person called the same number, but your home phone picked up the Bluetooth signal from your cell phone and automatically re-routed the call because it realized you were home. And each transmission signal to and from your cell phone consumes just 1 milliwatt of power, so your cell phone charge is virtually unaffected by all of this activity.Bluetooth is essentially a networking standard that works at two levels:It provides agreement at the physical level -- Bluetooth isa radio-frequency standard.It provides agreement at the protocol level, where products have to agree on when bits are sent, how many will be sent at a time, and how the parties in a conversation can be sure that the message received is the same as the message sent.The big draws of Bluetooth are that it is wireless, inexpensive and automatic. There are other ways to get around using wires, including infraredcommunication. Infrared (IR) refers to light waves of a lower frequency than human eyes can receive and interpret. Infrared is used in most television remote controlsystems. Infrared communications are fairly reliable and don't cost very much to build into a device, but there are a couple of drawbacks. First, infrared is a "line of sight" technology. For example, you have to point the remote control at the television or DVD player to makethings happen. The second drawback is that infrared is almost always a "one to one" technology. You can send data between your desktop computer and your laptop computer, but not your laptop computer andyour PDA at the same time. (SeeHow Remote Controls Work to learn more about infrared communication.)These two qualities of infrared are actually advantageous in some regards. Because infrared transmitters and receivers have to be lined up with each other, interference between devices is uncommon. The one-to-one nature of infrared communications is useful in that you can make sure a message goes only to the intended recipient, even in a room full of infrared receivers.Bluetooth is intended to get around the problems that come with infrared systems. The older Bluetooth 1.0 standard has a maximum transfer speed of 1 megabit per second (Mbps), while Bluetooth 2.0 can manage up to 3 Mbps. Bluetooth 2.0 is backward-compatible with 1.0 devices.Let's find out how Bluetooth networking works.How Bluetooth OperatesBluetooth networking transmits data via low-power radio waves. It communicates on a frequency of 2.45 gigahertz (actually between 2.402 GHz and 2.480 GHz, to be exact). This frequency band has been set aside by international agreement for the use of industrial, scientific and medical devices (ISM).A number of devices that you may already use take advantage of thissame radio-frequency band. Baby monitors, garage-door openers and the newest generation of cordless phones all make use of frequencies in the ISM band. Making sure that Bluetooth and these other devices don't interfere with one another hasbeen a crucial part of the design process.One of the ways Bluetooth devices avoid interfering with other systems is by sending out very weak signals of about 1 milliwatt. By comparison, the most powerful cell phones can transmit a signal of 3 watts. The low power limits the range of a Bluetooth device to about 10 meters (32 feet), cutting the chances of interference between your computer system and your portable telephone or television. Even with the low power, Bluetooth doesn't require line of sight between communicating devices. The walls in your house won't stop a Bluetooth signal, making the standard useful for controlling several devices in different rooms.Bluetooth can connect up to eight devices simultaneously. With all of those devices in the same 10-meter (32-foot) radius, you might think they'd interfere with one another, but it's unlikely. Bluetooth uses a technique called spread-spectrum frequency hopping that makes it rare for more than one device to be transmitting on the same frequency at the same time. In this technique, a device will use 79 individual, randomly chosen frequencies within a designated range, changing from one to another on a regular basis. In the case of Bluetooth, the transmitters change frequencies 1,600 times every second, meaning that more devices can make full use of a limited slice of the radio spectrum. Since every Bluetooth transmitter uses spread-spectrum transmitting automatically, i t’s unlikely that two transmitters will be on the same frequency at the same time. This same technique minimizes the risk that portable phones or baby monitors will disrupt Bluetooth devices, since any interference on a particular frequency will last only a tiny fraction of a second.When Bluetooth-capable devices come within range of one another, an electronic conversation takes place to determine whether they have data to share or whether one needs to control the other. The user doesn't have to press a button or give a command -- the electronic conversation happens automatically. Once the conversation has occurred, the devices -- whether they're part of a computer system or a stereo -- form a network. Bluetooth systems create a personal-area network (PAN), or piconet, that may fill a room or may encompass no more distance than that between the cell phone on a belt-clip and the headset on your head. Once a piconet is established, the members randomly hop frequencies in unison so they stay in touch with one another and avoid other piconets that may be operating in the same room. Let's check out an example of a Bluetooth-connected system.Bluetooth PiconetsLet's say you have a typical modern living room with typical modern stuff inside. There's an entertainment system with a stereo, a DVD player, a satellite TV receiver and a television; there's also a cordless telephone and a personal computer. Each of these systems uses Bluetooth, and each forms its own piconet to talk between the main unit and peripheral.The cordless telephone has one Bluetooth transmitter in the base and another in the handset. The manufacturer has programmed each unit with an address that falls into a range of addresses it has established for a particular type of device. When the base is first turned on, it sends radio signals asking for a response from any units with an address in a particular range. Since the handset has an address in the range, it responds, and a tiny network is formed. Now, even if one of these devices shouldreceive a signal from another system, it will ignore it since it's not from within the network. The computer and entertainment system go through similar routines, establishing networks among addresses in ranges established by manufacturers. Once the networks are established, the systems begin talking among themselves. Eachpiconet hops randomly through the available frequencies, so all of the piconets are completely separated from one another.Now the living room has three separate networks established, each one made up of devices that know the address of transmitters it should listen to and the address of receivers it should talk to. Since each network is changing the frequency of its operation thousands of times a second, it's unlikely that any two networks will be on the same frequency at the same time. If it turns out that they are, then the resulting confusion will only cover a tiny fraction of a second, and software designed to correct for such errors weeds out the confusing information and gets on with the network's business.摘要越来越多数字电子产品借着新科技提升本身的性能和实力。
Android BLE与终端通信(五)——Google API BLE4.0低功耗蓝牙文档解读之案例初探

Android BLE与终端通信(五)——Google API BLE4.0低功耗蓝牙文档解读之案例初探一.概述我们直接翻译Generic Attribute Profile(GATT)—GATT配置文件是一个通用规范,用于在BLE链路上发送和接收被称为“属性”的数据块。
目前所有的BLE应用都基于GATT。
蓝牙SIG规定了许多低功耗设备的配置文件。
配置文件是设备如何在特定的应用程序中工作的规格说明。
注意一个设备可以实现多个配置文件。
例如,一个设备可能包括心率监测仪和电量检测。
Attribute Protocol(ATT)—GATT在A TT协议基础上建立,也被称为GATT/ATT。
ATT对在BLE设备上运行进行了优化,为此,它使用了尽可能少的字节。
每个属性通过一个唯一的的统一标识符(UUID)来标识,每个String类型UUID使用128 bit标准格式。
属性通过ATT被格式化为characteristics和services。
Characteristic 一个characteristic包括一个单一变量和0-n个用来描述characteristic变量的descriptor,characteristic可以被认为是一个类型,类似于类。
Descriptor Descriptor用来描述characteristic变量的属性。
例如,一个descriptor可以规定一个可读的描述,或者一个characteristic变量可接受的范围,或者一个characteristic变量特定的测量单位。
Service service是characteristic的集合。
例如,你可能有一个叫“Heart Rate Monitor(心率监测仪)”的service,它包括了很多characteristics,如“heart rate measurement(心率测量)”等。
你可以在 找到一个目前支持的基于GA TT的配置文件和服务列表。
android开发环境设置和BLE驱动开发说明

• 四、通过扫描得到的地址寻找设备,然后 调用设备的connectGatt与设备进行连接, 代码如下: • Final BluetoothDevice device=mBluetooth.getRemoteDevice(address ); • Device.connectGatt(this,false,mGattCallback); • mGattCallback的类型为 BluetoothGattCallback,该类型处理GATT的 各种事件,如设备连接完毕或断开
BLE代码说明
• 一、判断系统是否支持BLE,代码如下: • if(!getPackageManager().hasSystemFeature(Pac kageManager.FEATURE_BLUETOOTH_LE)) • { • Toast.makeText(this, R.string.ble_not_supported, • Toast.LENGTH_SHORT).show(); • finish(); • }
• 四、调用蓝牙适配器的扫描设备函数,寻找设备。 • mBluetoothAdapter.startLeScan(mLeScanCallback); • // Device scan callback. • private BluetoothAdapter.LeScanCallback mLeScanCallback = • new BluetoothAdapter.LeScanCallback() { • @Override • public void onLeScan(final BluetoothDevice device, int rssi, byte[]scanRecord) { • runOnUiThread(new Runnable() { • @Override • public void run() { • mLeDeviceListAdapter.addDevice(device); • mLeDeviceListAdapter.notifyDataSetChanged(); • } • }); • } • }; • 寻找设备一段时间后,记得调用 mBluetoothAdapter.stopLeScan(mLeScanCallback);
android 蓝牙开发(DOC)

Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输。
本文档描述了怎样利用android平台提供的蓝牙API去实现蓝牙设备之间的通信,蓝牙设备之间的通信主要包括了四个步骤:设置蓝牙设备;寻找局域网内可能或者匹配的设备;连接设备;设备之间的数据传输。
以下是建立蓝牙连接的所需要的一些基本类:BluetoothAdapter类:代表了一个本地的蓝牙适配器。
他是所有蓝牙交互的的入口点。
利用它你可以发现其他蓝牙设备,查询绑定了的设备,使用已知的MAC地址实例化一个蓝牙设备和建立一个BluetoothServerSocket(作为服务器端)来监听来自其他设备的连接。
BluetoothDevice类:代表了一个远端的蓝牙设备,使用它请求远端蓝牙设备连接或者获取远端蓝牙设备的名称、地址、种类和绑定状态。
(其信息是封装在bluetoothsocket中)。
Bluetoothsocket类:代表了一个蓝牙套接字的接口(类似于tcp中的套接字),他是应用程序通过输入、输出流与其他蓝牙设备通信的连接点。
Blueboothserversocket类:代表打开服务连接来监听可能到来的连接请求(属于server端),为了连接两个蓝牙设备必须有一个设备作为服务器打开一个服务套接字。
当远端设备发起连接请求的时候,并且已经连接到了的时候,Blueboothserversocket类将会返回一个bluetoothsocket。
Bluetoothclass类:描述了一个蓝牙设备的一般特点和能力。
他的只读属性集定义了设备的主、次设备类和一些相关服务。
然而,他并没有准确的描述所有该设备所支持的蓝牙文件和服务,而是作为对设备种类来说的一个小小暗示。
下面说说具体的编程实现:首先,要操作蓝牙,先要在AndroidManifest.xml里加入权限<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" /><uses-permissionandroid:name="android.permission.BLUETOOTH" />其次,必须确定你的设备支持蓝牙,并保证他可以用。
android蓝牙ble连接原理

android蓝牙ble连接原理在Android开发中,蓝牙低功耗(BLE)连接是一种用于实现设备之间无线通信的技术。
它比传统蓝牙更省电,适用于物联网应用和其他需要长时间低功耗连接的场景。
下面将介绍Android蓝牙BLE连接的原理。
首先,需要了解BLE连接的两个主要角色:中央设备(Central)和外围设备(Peripheral)。
中央设备通常是Android手机或平板电脑,而外围设备可以是各种蓝牙BLE设备,如传感器、智能手表等。
BLE连接的过程是通过GATT(通用属性配置文件)来实现的。
GATT定义了中央设备和外围设备之间的数据通信协议。
在BLE连接中,GATT分为两个主要部分:服务器和客户端。
外围设备充当服务器的角色,它包含多个服务(Service),每个服务可以有多个特征(Characteristic)。
服务代表外围设备的功能,特征则包含了具体的数据。
每个服务和特征都有一个唯一的标识符,称为UUID,用于唯一标识它们。
中央设备作为客户端,负责与外围设备进行通信。
在建立BLE连接之前,中央设备需要扫描周围的外围设备。
通过扫描可以获取外围设备的UUID,以便中央设备连接到指定的外围设备。
BLE连接的建立是通过以下步骤完成的:1. 扫描外围设备:中央设备通过蓝牙适配器开始扫描周围的外围设备。
扫描时,可以设置过滤条件,以匹配特定的外围设备UUID。
2. 建立连接:当中央设备发现目标外围设备后,可以通过调用`BluetoothDevice.connectGatt()`方法来建立连接。
3. 发现服务:建立连接后,中央设备需要发现外围设备所支持的服务。
通过调用`BluetoothGatt.discoverServices()`方法可以发现外围设备的所有服务。
4. 获取特征:一旦服务发现完成,中央设备可以通过`BluetoothGatt.getService()`方法获取指定UUID的服务。
之后,通过调用`BluetoothGattCharacteristic.getCharacteristic()`方法获取特定UUID的特征。
Bluetooth Specification V4.0 EDR and BLE资料整理

一、产品参数蓝牙版本:Bluetooth Specification V4.0 EDR and BLE串口缓冲区大小512 BytesSPP 设备–>模块,每包最大字节60BytesBLE 设备->模块,每包最大字节20Bytes模块BLE -> iOS 设备,内部分包60 字节每包模块BLE-> Android设备,内部分包20 字节每包模块SPP-> SPP 设备,内部分包60 字节每包启动时间:平衡模式2 Seconds、高速模式1 Second工作模式:平衡模式、高速模式。
收发距离:SPP 30 米,BLE60米通讯距离:SPP 50 米,BLE100米(理想环境下)工作方式:上电自动复位,RESETB管脚可留空。
工作频率:2.4GHz ISM band调制方式:GFSK(Gaussian Frequency Shift Keying)灵敏度:≤-84dBm at 0.1% BER传输速率:SPP 约40%串口效率BLE 约30%串口效率安全特性:Authentication and encryptionEDR 服务:L2CAP,、SDP,、RFCOMM、SPPBLE服务:ATT、GATT,、LE Service: 0xFFE0、Char: 0xFFE1 功耗:SPP 平均约13mA ,BLE平均约9.5mA。
待机约10-17mA 供电电源:+3.3VDC 50mA工作温度:–5 ~ +80 Centigrade外观尺寸:HM-12 26.9mm x 13mm x 2.2 mm7. HM系列蓝牙模块与单片机连接注意要点:HM 系列蓝牙模块的工作电压推荐用3.3V,与3.3V 单片机直接连接即可,当需要与5V 单片机连接时,请在模块RX 引脚与单片机TX 引脚之间串一个1-2K的电阻,再接一个分压电阻接地,保护一下模块RX引脚,防止被烧坏。
7.1、LAYOUT 注意要点HM 系列蓝牙模块工作在2.4G 无线频段,应尽量避免各种因素对无线收发的影响,注意以下几点:7.1.1、包围蓝牙模块的产品外壳避免使用金属,当使用部分金属外壳时,应尽量让模块天线部分远离金属部分。
BLE 蓝牙4.0 介绍

BLE 蓝牙4.0 介绍1,BLE就是低功率蓝牙。
要着重了解两种设备:1,dual-mode双模设备:简单说就是向下兼容。
2,single-mode单模设备:仅仅支持BLE。
关于开发主要讲的是单模设备,它可以只靠纽扣电池即可持续工作。
2,BLE 协议栈PHY物理层在2.4GHz的ISM频段中跳频识别。
LL连接层:控制设备的状态。
设备可能有5中状态:就绪standby,广播advertising,搜索scanning,初始化initiating和连接connected。
广播者传播数据,使得浏览者可以接收到。
initiator就是一个对广播者回复连接请求的设备。
如果广播者接受请求,广播者和initiator初始者就会进入connected连接状态。
一个处于连接状态的设备会有一个角色:master和slave。
初始化这个连接的为master,接受这个连接请求的为slave。
HCI层为host和controller之间通过一个标准接口进行通信提供了一些方法。
这一层可以通过一个软件API或者是硬件接口如UART,SPI和USB。
L2CAP为上层数据提供封装服务。
SM:定义了建立连接和KEY的方法。
GAP:直接与profile和app进行接触,解决设备的发现和连接相关的服务,此外GAP也会初始化安全相关的特色。
ATT协议允许一个设备去显示一些数据,对于其他设备称之为“Attribute属性”,在ATT中,那些显示这些属性的设备被称为server,同等的另一个设备称为client。
LL层的状态master和slave和ATT层的这两个状态无关。
GATT层:是一个服务框架定义了对ATT应用的子程序。
GATT指定了profile的结构。
在BLE中,由profile或者是服务所使用的所有类型的数据都称为characteristic。
发生于两个设备间通过BLE连接进行交换的数据都需经过GATT 子程序处理。
因此,app和profile会直接使用GATT。
android蓝牙bleapp开发(二)--关键概念,连接参数,连接请求

android蓝牙bleapp开发(二)--关键概念,连接参数,连接请求Android蓝牙ble app开发中经常会遇到很多问题,这个时候就需要用到抓包软件进行分析,单单从现象上很难鉴定是设备固件端的问题,还是我们自己app写的不对的问题。
这一点是做android的是比较纠结的,因为固件端经常是和iOS通信没毛问题,android问题偶尔,这个偶尔很经常出现。
(固件基于cc2540 2541)这篇记录的内容是android app开发时遇到的,但是本身的内容却是ble协议的一些内容,ios 也是一样的下一篇会记录下抓包过程与分析。
1、知识储备:要分析ble蓝牙包需要懂一些ble蓝牙协议栈的内容,和一些核心概念。
最关键的几个概念Connection Events:连接事件这个概念比较抽象,之前看了很多解释不明白,ti 宣讲会上讲ppt 讲的很清楚简单的说就是通信建立在连接事件上,每次连接事件时才是真正的通信事件,其余时间时休眠的(低功耗)对应在程序上就是如果连接间隔的时间设置的大于通信间隔,就会出现数据通信不流畅,没有接收到周期性数据,数据一卡顿一卡顿时而没有时而很多Supervision Timeout:超时时间(在这个时间内没有接收到响应就会断开)Slave Latency:这个不好翻译,看图最实在了理解成可以忽略的空白响应数吧Connection Interval:连接间隔简单的理解成连两个连接事件之间的间隔时间呗另外还有:Advertisement InterVals 广播间隔,和名字一个意思2、关于更新连接参数ConnectionParameter Update Request有阅读蓝牙协议栈和一些材料,简单的说就是主机决定连接参数的值( connection interval, slave latency, timeout),从机可以请求更新这些参数,主机决定是不是接受,接受的值是多少。
蓝牙4.0BLE数据传输(二)

蓝牙4.0BLE数据传输(二)在第一部分我们了解了几个专业词汇,接下来我们再了解一下数据的发送一、数据发送在BLE协议栈中进行数据发送分为两个方面,一个事GATT的client主动向service发送数据,另一个是GATT的service主动向client发送数据我们暂且简单的分为主机向从机发送数据,从机主动向主机发送数据。
1、主机向从机发送数据发送可以调用GATT_WriteCharValue函数来实现,该函数会调用协议栈里面与硬件相关的函数最终将数据通过天线发送出去,这里设计对射频模块的操作,例如:打开发射机,调整发射机的发射功率等内容,这些部分协议栈都已经实现了,用户不需要自己写代码实现(这里是废话,可以忽略),只需掌握GATT_writeCharValue函数的使用方法即可。
需要发送的数据填充到value中,然后数据长度填充到len中,即:首先我们得了解一下发送包的结构体typedef struct{uint16 handle; //要写入的属性的句柄(必须是第一个字段)uint8 len; //数据长度uint8 value[ATT_MTU_SIZE-3]; //存数据的数组uint8 sig; //身份验证签名状态(不包括 (0),有效的(1),无效 (2))uint8 cmd; //标记命令} attWriteReq_t;我们再看下数据是怎么发送的:002sNcnygy6KHfoajn2f0&690.jpegGATT_WriteCharValue有三个参数,第一个为连接句柄,第二个参数就是我们要发送的数据包,最后一个参数为时间的TASKID,只要满足以上的发送格式我们就可以把数据发送出去了,是不是很简单啊?2、从机向主机发送数据从机向主机发送数据,并不是用GATT_WriteCharValue这个函数,而至用另外的一种形式----notification,因此,我们需要调用GATT_Notification函数。
Android开发之蓝牙(Bluetooth)操作(一)--扫描已经配对的蓝牙设备

W hatever is worth doing is worth doing well.Never put off the work till tomorrow what you can put off today.A ndroid开发之蓝牙(Bluetooth)操作(一)--扫描已经配对的蓝牙设备分类: android 2012-08-14 16:41 1224人阅读 评论(10) 收藏举报androidbuttonnull通讯apiimport一. 什么是蓝牙(Bluetooth)?1.1 BuleTooth是目前使用最广泛的无线通信协议1.2 主要针对短距离设备通讯(10m)1.3 常用于连接耳机,鼠标和移动通讯设备等.二. 与蓝牙相关的API2.1 BluetoothAdapter:代表了本地的蓝牙适配器2.2 BluetoothDevice代表了一个远程的Bluetooth设备三. 扫描已经配对的蓝牙设备(1)注:必须部署在真实手机上,模拟器无法实现首先需要在AndroidManifest.xml 声明蓝牙权限<user-permission android:name="android.permission.BLUETOOTH" />配对蓝牙需要手动操作:1. 打开设置--> 无线网络 --> 蓝牙 勾选开启2. 打开蓝牙设置 扫描周围已经开启的蓝牙设备(可以与自己的笔记本电脑进行配对),点击进行配对电脑上会弹出提示窗口: 添加设备显示计算与设备之间的配对码,要求确认是否配对手机上也会显示类似的提示.四. 扫描已经配对的蓝牙设备(2)4.1 获得BluetoothAdapter对象4.2 判断当前移动设备中是否拥有蓝牙4.3 判断当前移动设备中蓝牙是否已经打开4.4 得到所有已经配对的蓝牙设备对象实现代码如下:MainActivity:import java.util.Iterator;import java.util.Set;import android.app.Activity;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity {private Button button = null;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main);button = (Button)findViewById(R.id.buttonId);button.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {//获得BluetoothAdapter对象,该API是android 2.0开始支持的BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();//adapter不等于null,说明本机有蓝牙设备if(adapter != null){System.out.println("本机有蓝牙设备!");//如果蓝牙设备未开启if(!adapter.isEnabled()){Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//请求开启蓝牙设备startActivity(intent);}//获得已配对的远程蓝牙设备的集合Set<BluetoothDevice> devices = adapter.getBondedDevices();if(devices.size()>0){for(Iterator<BluetoothDevice> it = devices.iterator();it.hasNext();){BluetoothDevice device = (BluetoothDevice)it.next();//打印出远程蓝牙设备的物理地址System.out.println(device.getAddress());}}else{System.out.println("还没有已配对的远程蓝牙设备!");}}else{System.out.println("本机没有蓝牙设备!");}}});}}。
官方蓝牙4.0基本概念

官方蓝牙4.0基本概念1.中心设备和外围设备以及它们在蓝牙通讯中的角色。
在所有的BLE( Bluetooth low energy,下文简称蓝牙4.0 )通讯中都涉及2个主要的角色:中心设备和外围设备。
它是基于传统的客户-服务器(主从式)结构,一般来说,外围设备有其它设备需要的数据,中心设备使用外围设备提供的数据来完成特定的任务。
像下图所示,心率监测器有有用的数据,Mac或者iOS APP需要这些数据来显示用户的心率。
2.中心设备搜索和连接正在广告的外围设备这里介绍了一个新的名词:广告(advertise)。
外围设备对外广播广告包(advertising packets)形式的数据,一个广告包是一个相对小的一捆包含着外围设备信息的数据,例如包含外围设备的名字和它的主要功能。
举一个例子,一个数字温度调节器会广告(advertise)说它提供房间的目前温度数据,在蓝牙4.0中,广告是外围设备让其它设备发现的主要方法。
另一方面,中心设备,可以扫描和监听任何在广告(advertising)的外围设备,如下图。
中心设备可以向任何它发现正在广告的外围设备请求连接三.外围设备的数据结构这里介绍了两个新名词:服务(services)和特征(characteristics)。
连接外围设备的目的是探索并与其进行数据交互,开始这些之前,我们先来了解下外围设备的数据组成外围设备包含一个或多个服务(services)以及提供了连接信号的强度。
一个服务是一些数据的集合,是设备完成一个特定行为的功能。
例如,一个心率计的服务是从心率传感器读取数据。
服务由特征(characteristics)组成。
一个特征提供外围设备服务的更详细信息。
例如,心率服务只是说明它包含一个描述心率传感器所在的身体部位的特征和一个传输心率测量数据的特征。
图1-3表明了一个心率传感器服务和特征的关系结构4、中心设备检测外围设备并与其进行数据交互一个中心设备与一个外围设备连接成功后,便可以搜索外围设备提供的所有服务和特征。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
添加关注 (/sign_in)
[转载]蓝牙4.0——Android BLE开发官方文档翻译
字数3340 阅读1719 评论2 喜欢19
... } 如果你只想扫描指定类型的外围设备,可以改为调用startLeScan(UUID[], BluetoothAdapter.LeScanCallback)),需要提供 你的app支持的GATT services的UUID对象数组。 作为BLE扫描结果的接口,下面是BluetoothAdapter.LeScanCallback的实现。
发现BLE设备 为了发现BLE设备,使用startLeScan())方法。这个方法需要一个参数BluetoothAdapter.LeScanCallback。你必须实现它 的回调函数,那就是返回的扫描结果。因为扫描非常消耗电量,你应当遵守以下准则: 只要找到所需的设备,停止扫描。 不要在循环里扫描,并且对扫描设置时间限制。以前可用的设备可能已经移出范围,继续扫描消耗电池电量。 下面代码显示了如何开始和停止一个扫描: // 扫描和显示可以提供的蓝牙设备.
// 使用此检查确定BLE是否支持在设备上,然后你可以有选择性禁用BLE相关的功能 if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); finish(); }
开启蓝牙 接下来,你需要确认蓝牙是否开启。调用isEnabled())去检测蓝牙当前是否开启。如果该方法返回false,蓝牙被禁用。下面 的代码检查蓝牙是否开启,如果没有开启,将显示错误提示用户去设置开启蓝牙。
// 确保蓝牙在设备上可以开启 if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }
// 初始化蓝牙适配器 final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter();
安卓4.3(API 18)为BLE的核心功能提供平台支持和API,App可以利用它来发现设备、查询服务和读写特性。相比传统的 蓝牙,BLE更显著的特点是低功耗。这一优点使android App可以与具有低功耗要求的BLE设备通信,如近距离传感器、 心脏速率监视器、健身设备等。 关键术语和概念 Generic Attribute Profile(GATT)—GATT配置文件是一个通用规范,用于在BLE链路上发送和接收被称为“属性”的数据 块。目前所有的BLE应用都基于GATT。 蓝牙SIG规定了许多低功耗设备的配置文件。配置文件是设备如何在特定的应用 程序中工作的规格说明。注意一个设备可以实现多个配置文件。例如,一个设备可能包括心率监测仪和电量检测。 Attribute Protocol(ATT)—GATT在ATT协议基础上建立,也被称为GATT/ATT。ATT对在BLE设备上运行进行了优化, 为此,它使用了尽可能少的字节。每个属性通过一个唯一的的统一标识符( UUID )来标识,每个 String 类型 UUID 使用 128 bit标准格式。属性通过ATT被格式化为characteristics和services。 Characteristic 一个characteristic包括一个单一变量和0n个用来描述characteristic变量的descriptor,characteristic可以被 认为是一个类型,类似于类。 Descriptor Descriptor 用来描述 characteristic 变量的属性。例如,一个 descriptor 可以规定一个可读的描述,或者一个 characteristic变量可接受的范围,或者一个characteristic变量特定的测量单位。 Service service是characteristic的集合。例如,你可能有一个叫“Heart Rate Monitor(心率监测仪)”的service,它包括了很 多characteristics,如“heart rate measurement(心率测量)”等。你可以在 找到一个目前支持的基于GATT的配 置文件和服务列表。 角色和责任 以下是Android设备与BLE设备交互时的角色和责任: 中央 VS 外围设备。 适用于BLE连接本身。中央设备扫描,寻找广播;外围设备发出广播。 GATT 服务端 VS GATT 客户端。决定了两个设备在建立连接后如何互相交流。 为了方便理解,想象你有一个Android手机和一个用于活动跟踪BLE设备,手机支持中央角色,活动跟踪器支持外围(为 了建立BLE连接你需要注意两件事,只支持外围设备的两方或者只支持中央设备的两方不能互相通信)。 当手机和运动追踪器建立连接后,他们开始向另一方传输GATT数据。哪一方作为服务器取决于他们传输数据的种类。例 如,如果运动追踪器想向手机报告传感器数据,运动追踪器是服务端。如果运动追踪器更新来自手机的数据,手机会作为 服务端。 在这份文档的例子中,android app(运行在android设备上)作为GATT客户端。app从gatt服务端获得数据,gatt服务端即 支持Heart Rate Profile(心率配置)的BLE心率监测仪。但是你可以自己设计android app去扮演GATT服务端角色。更多信 息见BluetoothGattServer。
<uses‐permission android:name="android.permission.BLUETOOTH"/>
Hale Waihona Puke <uses‐permission android:name="android.permission.BLUETOOTH_ADMIN"/>"
如果想声明你的app只为具有BLE的设备提供,在manifest文件中包括:
private LeDeviceListAdapter mLeDeviceListAdapter; ... // Device scan callback. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { runOnUiThread(new Runnable() { @Override public void run() { mLeDeviceListAdapter.addDevice(device); mLeDeviceListAdapter.notifyDataSetChanged(); } }); } };
App下载 (/apps/download?utm_medium=topsuggdown&utm_source=noteshow)
登录 (/sign_in)
// 10秒后停止寻找. private static final long SCAN_PERIOD = 10000; ... private void scanLeDevice(final boolean enable) { if (enable) { // 经过预定扫描期后停止扫描 mHandler.postDelayed(new Runnable() { @Override public void run() { mScanning = false; mBluetoothAdapter.stopLeScan(mLeScanCallback); } }, SCAN_PERIOD); mScanning = true; mBluetoothAdapter.startLeScan(mLeScanCallback); } else { mScanning = false; mBluetoothAdapter.stopLeScan(mLeScanCallback); } ... }
设置BLE 你的app能与BLE通信之前,你需要确认设备是否支持BLE,如果支持,确认已经启用。注意如果<usesfeature.../>设置 为false,这个检查才是必需的。 如果不支持BLE,那么你应该适当地禁用部分BLE功能。如果支持BLE但被禁用,你可以无需离开应用程序而要求用户启 动蓝牙。使用BluetoothAdapter两步完成该设置。 获取 BluetoothAdapter 所有的蓝牙活动都需要蓝牙适配器。BluetoothAdapter代表设备本身的蓝牙适配器(蓝牙无线)。整个系统只有一个蓝牙适 配器,而且你的app使用它与系统交互。下面的代码片段显示了如何得到适配器。注意该方法使用getSystemService()] 返回BluetoothManager,然后将其用于获取适配器的一个实例。Android 4.3(API 18)引入BluetoothManager。
BLE权限 为了在app中使用蓝牙功能,必须声明蓝牙权限BLUETOOTH。利用这个权限去执行蓝牙通信,例如请求连接、接受连 接、和传输数据。 如 果 想 让 你 的 app 启 动 设 备 发 现 或 操 纵 蓝 牙 设 置 , 必 须 声 明 BLUETOOTH_ADMIN 权 限 。 注 意 : 如 果 你 使 用 BLUETOOTH_ADMIN权限,你也必须声明BLUETOOTH权限。 在你的app manifest文件中声明蓝牙权限。