<span id="Label3"></p><p><p>Recently engaged in a period of time bluetooth, some harvest experience and share with you, in fact, the online great God wrote Bluetooth related are more practical and comprehensive, I mainly want to paste my project is not quite the same place.</p></p><p><p>Bluetooth process What I will not repeat here, we can Google for Ourselves. In addition, we recommend a bull with block packaging bluetooth---babybluetooth, personal feeling is good. Anyway</p></p><p><p>first, need to carefully look at the hardware of the documentation (due to my project hardware comparison pit, The document is not detailed I go a lot of detours), the operation of Bluetooth is nothing more than read write and notify. Follow the general steps:</p></p><p><p>1, establish the central role 2, scan peripheral (discover) 3, Connect Peripheral (connect) 4, Scan the peripheral services and features (discover) (these are the general process, do not repeat), now say a few things after scanning to the service and characteristics of the considerations, The service and characteristics of a device tend to be more, in most cases we just care about a few of them, so generally in the discovery of services and features of the callback to match our concerns, these will be based on the hardware of the document specific operation, such as My:</p></p><pre class="brush:csharp;gutter:true;"><pre class="brush:csharp;gutter:true;">For (cbcharacteristic *characteristic in Service.characteristics) { NSLog (@ "service:%@ characteristic:%@, What are the permissions of Characterustics:%lu ", service. Uuid,characteristic. uuid,characteristic.properties); _characteristic = characteristic; Cbuuid *uid = [cbuuid uuidwithstring:@ "0xfff6"]; If ([characteristic. UUID isequal:uid]) { [peripheral setnotifyvalue:yes forcharacteristic:characteristic]; NSLog (@ "start communication"); [manager stopscan]; Execute Write } } </pre></pre><p><p>After performing the operation to <span style="color: #000000;">5, the <strong>peripheral Do data interaction (explore and interact), the data read into two, One is direct read (reading directly), and the other is subscription (subscribe). From the name can basically understand the difference between the Two. The actual use of a specific application to see specific scenarios and characteristics of the properties Themselves. The feature has a properties field (characteristic.properties), which is an integer value that has the following definitions:</strong> </span></p></p><pre class="brush:csharp;gutter:true;"><pre class="brush:csharp;gutter:true;">//print out characteristic permissions, you can see there are many kinds of, this is a ns_options, it can be used for several values, common have read, write,notify,indicate, know that these basic enough, before even one is read and write permissions, the latter two are notifications, two different notification methods. /* typedef ns_options (nsuinteger, cbcharacteristicproperties) {cbcharacteristicpropertybroadcast= 0x01, CBCha racteristicpropertyread= 0x02, cbcharacteristicpropertywritewithoutresponse = 0x04, Cbcharacteristi cpropertywrite= 0x08, cbcharacteristicpropertynotify= 0x10, cbcharacteristicpropertyindicate = 0x20, CB Characteristicpropertyauthenticatedsignedwrites = 0x40, Cbcharacteristicpropertyextendedpropert ies = 0x80, cbcharacteristicpropertynotifyencryptionrequired ns_enum_available (NA, 6_0) = 0x100, cbcharacteristicpropertyindicateencryptionrequired ns_enum_available (NA, 6_0) = 0x200}; */</pre></pre><p><p>Note: This property can also be superimposed, for example, the returned characteristic.properties = 0x26, which has three properties at the same time: Cbcharacteristicpropertywritewithoutresponse <em> Cbcharacteristicpropertywrite </em>Cbcharacteristicpropertyindicate</p></p><p><p>The value of the properties of the interaction in my project is 0x10, which means that you can only receive data in a subscription way. I'm here to subscribe, the code to start the subscription is as Follows:</p></p><pre class="brush:csharp;gutter:true;"><pre class="brush:csharp;gutter:true;">[_peripheral Setnotifyvalue:yes forcharacteristic:_readcharacteristic];</pre></pre><p><p><span style="color: #ff0000;">note: This sentence must be added, otherwise the hardware will not give you return Data. </span></p></p><p><p><span style="color: #ff0000;"><span style="color: #000000;">If Propertites is a subscription, when the device has data return, it is also through a system callback notify me, will go the following way:-(<span class="keyword">void) peripheral: (<span class="keyword">cbperipheral *) Peripheral <span class="vars"> Didupdatevalueforcharacteristic: (<span class="keyword">cbcharacteristic *) characteristic<span class="vars"> error: (<span class="keyword">nserror *) Error. This method is called after you write the data, provided the proxy is Set. I was in the process of development encountered this problem, I do write operation after this method does not go, I began to think is the process logic problem, and then finally solved, because the write is unsuccessful, so, If this method does not go the reason is one that is Bluetooth did not receive the correct data you send. Because this function starts with "did", The function is not called by you, the system is automatically called after the condition is reached, and there is no call only because the condition is not reached, of course, if you set up the Agent. </span></span></span></span></span></span></span><br></span></p></p><p><p><span style="color: #ff0000;"><span style="color: #000000;"><span class="keyword"><span class="keyword"><span class="vars"><span class="keyword"><span class="vars"><span class="keyword">Here the data can be sent to receive the basic needs are OK.</span></span></span></span></span></span></span></span></p></p><p><p><span style="color: #ff0000;"><span style="color: #000000;"><span class="keyword"><span class="keyword"><span class="vars"><span class="keyword"><span class="vars"><span class="keyword">In addition, I would like to say some small attention to send the data, I think the data in my project is still more troublesome, involving more places. Bluetooth received data is NSData format, return is also nsdata, so generally to convert into Nsdata. Here are the conversions in several formats (all reproduced, hereby stated):</span></span></span></span></span></span></span></span></p></p><p><p><span style="color: #ff0000;"><span style="color: #000000;"><span class="keyword"><span class="keyword"><span class="vars"><span class="keyword"><span class="vars"><span class="keyword">1, the string is converted to NSData (not encoded):</span></span></span></span></span></span></span></span></p></p><pre class="brush:csharp;gutter:true;"><pre class="brush:csharp;gutter:true;">-(nsdata *) converthexstrtodata: (nsstring *) str { if (!STR | | [str length] = = 0) { return nil; } Nsmutabledata *hexdata = [[nsmutabledata alloc] initwithcapacity:8]; Nsrange range; If ([str length]% 2 = = 0) { range = nsmakerange (0, 2); } else { range = nsmakerange (0, 1); } for (nsinteger i = range.location; i < [str length]; i + = 2) { unsigned int anint; NSString *hexcharstr = [str substringwithrange:range]; Nsscanner *scanner = [[nsscanner alloc] initwithstring:hexcharstr]; [scanner scanhexint:&anint]; NSData *entity = [[nsdata alloc] initwithbytes:&anint length:1]; [hexdata appenddata:entity]; Range.location + = range.length; Range.length = 2; } NSLog (@ "hexdata:%@", hexdata); Return hexdata;}</pre></pre><p><p>For example, nsstring *modelstr = @ "1311212313";</p></p><p><p>NSLog (@ "nsdata =%@", [self converthexstrtodata:modelstr]);</p></p><p><p><span style="color: #ff0000;"><span style="color: #000000;"><span class="keyword"><span class="keyword"><span class="vars"><span class="keyword"><span class="vars"><span class="keyword">Printing results:</span></span></span></span></span></span></span></span></p></p><p><p><strong>NSData = <13112123 13>,length = 5</strong></p></p><p><p><span style="color: #ff0000;"><strong>Note that the comparison with the methods below</strong></span></p></p><pre class="brush:objc;gutter:true;"><pre class="brush:objc;gutter:true;">-(Byte) strtobyte: (nsstring *) str{ int endminutes = [str intvalue]; byte Endminutebyte = (byte) 0xff&endminutes; Return endminutebyte;}</pre></pre><p><p>Or the above string, do the following</p></p><pre class="brush:objc;gutter:true;"><pre class="brush:objc;gutter:true;">NSString *modelstr = @ "1311212313"; Byte nameuser[10]; for (int i = 0; i<10;i++) { nsstring *bytestr = [modelstr substringwithrange:nsmakerange (i, 1)]; nameuser[i] = [self strtobyte:bytestr]; } NSData *nameuserdata = [nsdata datawithbytes:nameuser length:12]; NSLog (@ "nsdata =%@%zd", nameuserdata,nameuserdata.length);</pre></pre><p><p>Print result:<strong>nsdata = <01030101 02010203 0103>,length = ten</strong></p></p><p><p><span style="color: #000000;">The above two cases are converted to the corresponding NSData method, which can be used according to the data length provided by the Document.</span></p></p><p><p><span style="color: #000000;">2, the method of calculating summation and (checksum) (<strong>CHECKSUM)</strong></span></p></p><p><p>As the name implies, the summation and that is the sum of the data to be asked, the general rule is the sum of the first n-1 bytes of low-byte, checksum=0x100-checksum (the checksum of the previous step), the resulting CS byte length of 1byte, type nsdata, the specific code is as follows,</p></p><pre class="brush:objc;gutter:true;">-(nsdata *) getchecksum: (nsdata *) bytestr{int length = (int) bytestr.length; NSData *data = [self hextobytes:bytestr]; Byte *bytes = (unsigned char *) [bytestr bytes]; Byte sum = 0; for (int i = 0; i<length; i++) {sum + = bytes[i]; } int sumT = sum; int at = 256-sumt; printf ("checksum:%d\n", at); printf ("accumulative sum:%d\n", sumT); If (at = =) {at = 0; } nsstring *str = [nsstring stringwithformat:@ "%@", [self tohex:sumt]]; return [self hextobytes:str];} Convert decimal to hexadecimal-(nsstring *) tohex: (int) tmpid{nsstring *nlettervalue; NSString *str [email protected] ""; int ttmpig; for (int i = 0; i<9; i++) {ttmpig=tmpid%16; tmpid=tmpid/16; Switch (ttmpig) {case 10:nlettervalue [email protected] "A"; Case 11:nlettervalue [email protected] "B"; Case 12:nlettervalue [email protected] "C"; Case 13:nlettervalue [email protected] "D"; Case 14:nlettervalue [email protected] "E"; Case 15:nlettervalue [email protected] "F"; Default:nlettervalue = [nsstring stringwithformat:@ "%u", ttmpig]; } str = [nlettervalue stringbyappendingstring:str]; if (tmpid = = 0) {break; }}//nslog (@ "16 binary is:%@", str); Not enough a byte to scrape 0 if (str.length = = 1) {return [nsstring stringwithformat:@ "0%@", str]; }else{return str; }}-(nsdata *) hextobytes: (nsstring *) str{nsmutabledata* data = [nsmutabledata data]; int idx; For (idx = 0; idx+2 <= str.length; idx+=2) {nsrange range = Nsmakerange (idx, 2); nsstring* hexstr = [str substringwithrange:range]; nsscanner* scanner = [nsscanner scannerwithstring:hexstr]; unsigned int intvalue; [scanner scanhexint:&intvalue]; [data Appendbytes:&intvalue length:1]; } return data;</pre><p><p>For example, the sum of the data in the upper section is obtained:</p></p><p><p>NSData *csdata = [self getchecksum:[self Converthexstrtodata:modelstr]];csdata is the Result.</p></p><p><p>The conversion of data types also has the most basic byte[] operation, which is not said Here.</p></p><p><p>According to the BLE4.0 protocol, Bluetooth data buffer to receive the maximum 20 bytes, if the packet is too large, can be split into small packets to operate, specific can be sent by using a timer or directly through the loop (in my project I have tried, is all right, but still that sentence, or to specific see the document operation), but Note that the accuracy of the timer is not very high, (it is said that there is an error below 50ms, I did not actually test).</p></p><p><p></p></p><p><p>IOS bluetooth essay</p></p></span>
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