---
title: "使用websocket，双ibeacons判断方向"
author: "haoningabc"
date: "2014-12-16T04:08:22Z"
tags: ["iOS"]
categories: ["移动开发"]
slug: "websocket-ibeacons"
draft: false
lastmod: "2014-12-16T05:19:12Z"
id: 2166580
url: "https://haoningabc.iteye.com/blog/2166580"
---

只调用ibeacon的接口 \[code="java"] // // ViewController.m // ibb // // Created by xiao7 on 14/12/15. // Copyright (c) 2014年 killinux. All rights reserved. // #import "ViewController.h" @import CoreLocation; @interface ViewController () @property NSMutableDictionary \*beacons; @property CLLocationManager \*locationManager; @property NSMutableDictionary \*rangedRegions; @property (nonatomic, copy, readonly) NSArray \*supportedProximityUUIDs; @end @implementation ViewController - (void)viewDidLoad { \[super viewDidLoad]; NSLog(@"viewDidLoad------"); self.beacons = \[\[NSMutableDictionary alloc] init]; self.locationManager = \[\[CLLocationManager alloc] init]; self.locationManager.delegate = self; \[self.locationManager requestAlwaysAuthorization]; self.rangedRegions = \[\[NSMutableDictionary alloc] init]; \_supportedProximityUUIDs = @\[ \[\[NSUUID alloc] initWithUUIDString:@"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"], \[\[NSUUID alloc] initWithUUIDString:@"DDDDDDDD-DDDD-DDDD-AAAA-DDDDDDDDDDDD"] //,\[\[NSUUID alloc] initWithUUIDString:@"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD"] ]; for (NSUUID \*uuid in \_supportedProximityUUIDs) { CLBeaconRegion \*region = \[\[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:\[uuid UUIDString]]; self.rangedRegions\[region] = \[NSArray array]; } } - (void)viewDidAppear:(BOOL)animated { \[super viewDidAppear:animated]; for (CLBeaconRegion \*region in self.rangedRegions) { \[self.locationManager startRangingBeaconsInRegion:region]; } } - (void)locationManager:(CLLocationManager \*)manager didRangeBeacons:(NSArray \*)beacons inRegion:(CLBeaconRegion \*)region { NSLog(@"locationManager--------didRangeBeacons:%d",beacons.count); self.rangedRegions\[region] = beacons; \[self.beacons removeAllObjects]; NSLog(@"locationManager-begin"); if(beacons.count!=0){ NSArray \*allvalue=\[self.rangedRegions allValues]; if(allvalue.count==2){ NSArray \*regionResult = allvalue\[0]; CLBeacon \*thisregion = regionResult\[0]; //NSLog(@"--%.2f", thisregion.accuracy); NSArray \*regionResult2 = allvalue\[1]; if(regionResult2.count&gt;0){ CLBeacon \*thisregion2 = regionResult2\[0]; // NSLog(@"--%.2f", thisregion2.accuracy); if(thisregion.accuracy&gt;0 && thisregion2.accuracy&gt;0){ NSLog(@"%.2f", thisregion2.accuracy-thisregion.accuracy); if((thisregion2.accuracy-thisregion.accuracy)&lt;0){ NSLog(@"left"); }else{ //NSLog(@"%.2f", ABS(thisregion2.accuracy-thisregion.accuracy)); if(ABS(thisregion2.accuracy-thisregion.accuracy)&lt;0.1){ NSLog(@"w"); }else{ NSLog(@"right"); } } } } } } } - (void)didReceiveMemoryWarning { \[super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end \[/code] 加上websocket的接口 \[code="java"] // // ViewController.m // ibb // // Created by xiao7 on 14/12/15. // Copyright (c) 2014年 killinux. All rights reserved. // #import "ViewController.h" #import "SocketRocket/SRWebSocket.h" @import CoreLocation; @interface ViewController () @property NSMutableDictionary \*beacons; @property CLLocationManager \*locationManager; @property NSMutableDictionary \*rangedRegions; @property (nonatomic, copy, readonly) NSArray \*supportedProximityUUIDs; @property (nonatomic, strong) SRWebSocket \*mywebSocket; @end @implementation ViewController //NSString \*websocket\_url = @"ws://haoning.net/webs/websocket/test"; NSString \*websocket\_url = @"ws://192.168.0.112:8000/chat"; - (void)viewDidLoad { \[super viewDidLoad]; //websocket init \_mywebSocket.delegate = nil; \[\_mywebSocket close]; \_mywebSocket = \[\[SRWebSocket alloc] initWithURLRequest:\[NSURLRequest requestWithURL:\[NSURL URLWithString:websocket\_url]]]; \_mywebSocket.delegate = self; \[\_mywebSocket open]; NSLog(@"viewDidLoad------"); self.beacons = \[\[NSMutableDictionary alloc] init]; self.locationManager = \[\[CLLocationManager alloc] init]; self.locationManager.delegate = self; \[self.locationManager requestAlwaysAuthorization]; self.rangedRegions = \[\[NSMutableDictionary alloc] init]; \_supportedProximityUUIDs = @\[ \[\[NSUUID alloc] initWithUUIDString:@"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"], \[\[NSUUID alloc] initWithUUIDString:@"DDDDDDDD-DDDD-DDDD-AAAA-DDDDDDDDDDDD"] //,\[\[NSUUID alloc] initWithUUIDString:@"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD"] ]; for (NSUUID \*uuid in \_supportedProximityUUIDs) { CLBeaconRegion \*region = \[\[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:\[uuid UUIDString]]; self.rangedRegions\[region] = \[NSArray array]; } } - (void)viewDidAppear:(BOOL)animated { \[super viewDidAppear:animated]; for (CLBeaconRegion \*region in self.rangedRegions) { \[self.locationManager startRangingBeaconsInRegion:region]; } } - (void)locationManager:(CLLocationManager \*)manager didRangeBeacons:(NSArray \*)beacons inRegion:(CLBeaconRegion \*)region { NSLog(@"locationManager--------didRangeBeacons:%d",beacons.count); self.rangedRegions\[region] = beacons; \[self.beacons removeAllObjects]; NSLog(@"locationManager-begin"); if(beacons.count!=0){ NSArray \*allvalue=\[self.rangedRegions allValues]; if(allvalue.count==2){ NSArray \*regionResult = allvalue\[0]; CLBeacon \*thisregion = regionResult\[0]; //NSLog(@"--%.2f", thisregion.accuracy); NSArray \*regionResult2 = allvalue\[1]; if(regionResult2.count&gt;0){ CLBeacon \*thisregion2 = regionResult2\[0]; // NSLog(@"--%.2f", thisregion2.accuracy); if(thisregion.accuracy&gt;0 && thisregion2.accuracy&gt;0){ NSLog(@"%.2f", thisregion2.accuracy-thisregion.accuracy); if((thisregion2.accuracy-thisregion.accuracy)&lt;0){ NSLog(@"left"); \[\_mywebSocket send:@"a"]; }else{ //NSLog(@"%.2f", ABS(thisregion2.accuracy-thisregion.accuracy)); if(ABS(thisregion2.accuracy-thisregion.accuracy)&lt;0.1){ NSLog(@"w"); \[\_mywebSocket send:@"w"]; }else{ NSLog(@"right"); \[\_mywebSocket send:@"d"]; } } } } } } } - (void)didReceiveMemoryWarning { \[super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //---------------- //pragma websocket - (void)webSocketDidOpen:(SRWebSocket \*)webSocket; { NSLog(@"Websocket Connected"); self.title = @"Connected!"; } - (void)webSocket:(SRWebSocket \*)webSocket didFailWithError:(NSError \*)error; { NSLog(@":( Websocket Failed With Error %@", error); \_mywebSocket = nil; } - (void)webSocket:(SRWebSocket \*)webSocket didReceiveMessage:(id)message; { NSLog(@"websocket Received \\"%@\\"", message); NSArray \*messageArray = \[message componentsSeparatedByString:@","]; if(messageArray.count&lt;3){ NSLog(@"error parameter not right:%@",message); // NSDictionary \*dict8 = \[NSDictionary dictionaryWithObjectsAndKeys:@"haoning",@"name",message,@"content", nil]; // \[\_resultArray addObject:dict8]; }else{ NSDictionary \*dict8 = \[NSDictionary dictionaryWithObjectsAndKeys:messageArray\[0],@"name",messageArray\[2],@"content", nil]; } } - (void)webSocket:(SRWebSocket \*)webSocket didCloseWithCode:(NSInteger)code reason:(NSString \*)reason wasClean:(BOOL)wasClean; { NSLog(@"WebSocket closed"); self.title = @"Connection Closed! (see logs)"; \_mywebSocket = nil; } @end \[/code] websocket的服务端代码，使用tornado \[code="java"] #!/usr/bin/python #coding:utf-8 import os.path import tornado.httpserver import tornado.web import tornado.ioloop import tornado.options import tornado.httpclient import tornado.websocket import json import RPi.GPIO as GPIO import time #GPIO.setwarnings(False) #GPIO.setmode(GPIO.BCM) #GPIO.setup(17,GPIO.OUT) #GPIO.setup(18,GPIO.OUT) #GPIO.setup(22,GPIO.OUT) #GPIO.setup(23,GPIO.OUT) class IndexHandler(tornado.web.RequestHandler): def get(self): self.render("index.html") class SocketHandler(tornado.websocket.WebSocketHandler): """docstring for SocketHandler""" clients = set() @staticmethod def send\_to\_all(message): for c in SocketHandler.clients: c.write\_message(json.dumps(message)) def open(self): # GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(17,GPIO.OUT) GPIO.setup(18,GPIO.OUT) GPIO.setup(22,GPIO.OUT) GPIO.setup(23,GPIO.OUT) self.write\_message(json.dumps({ 'type': 'sys', 'message': 'Welcome to WebSocket', })) SocketHandler.send\_to\_all({ 'type': 'sys', 'message': str(id(self)) + ' has joined', }) SocketHandler.clients.add(self) def on\_close(self): SocketHandler.clients.remove(self) SocketHandler.send\_to\_all({ 'type': 'sys', 'message': str(id(self)) + ' has left', }) def on\_message(self, message): if(message == 'w'): GPIO.output(17,False) GPIO.output(18,True) GPIO.output(22,False) GPIO.output(23,True) elif(message == 'a'): GPIO.output(17,False) GPIO.output(18,True) GPIO.output(22,False) GPIO.output(23,False) elif(message == 'd'): GPIO.output(17,False) GPIO.output(18,False) GPIO.output(22,False) GPIO.output(23,True) elif(message == 's'): GPIO.output(17,True) GPIO.output(18,False) GPIO.output(22,True) GPIO.output(23,False) else: GPIO.output(17,False) GPIO.output(18,False) GPIO.output(22,False) GPIO.output(23,False) SocketHandler.send\_to\_all({ 'type': 'user', 'id': id(self), 'message': message, }) ##MAIN if \_\_name\__ == '\_\_main\_\_': app = tornado.web.Application( handlers=\[ (r"/", IndexHandler), (r"/chat", SocketHandler) ], debug = True, # template\_path = os.path.join(os.path.dirname(\_\_file\_\_), "templates"), # static\_path = os.path.join(os.path.dirname(\_\_file\_\_), "static") ) app.listen(8000) tornado.ioloop.IOLoop.instance().start() \[/code]