验证中...
Languages: ActionScript
Categories: 常用工具包
Latest update 2019-03-04 16:57
Controller.as
Raw Copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
package app.core
{
import com.distriqt.extension.bluetoothle.AuthorisationStatus;
import com.distriqt.extension.bluetoothle.BluetoothLE;
import com.distriqt.extension.bluetoothle.events.AuthorisationEvent;
import com.distriqt.extension.bluetoothle.events.BluetoothLEEvent;
import com.distriqt.extension.bluetoothle.events.CentralManagerEvent;
import com.distriqt.extension.bluetoothle.events.CharacteristicEvent;
import com.distriqt.extension.bluetoothle.events.PeripheralEvent;
import com.distriqt.extension.bluetoothle.objects.Characteristic;
import com.distriqt.extension.bluetoothle.objects.Peripheral;
import com.distriqt.extension.bluetoothle.objects.Service;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.Timer;
import app.uis.BleConnecting;
import app.utils.Translator;
import starling.core.Starling;
import starling.events.Event;
import starling.utils.SystemUtil;
public class Controller extends EventDispatcher
{
public static var APP_KEY : String = "94c120e200e7e6a057f1c7c1f30aafaa5cd8c3c3J1gpR3oVgLqGkwwP4tkYkYY4+lgyLZKCLtHa6eZAdDKXO18AW0gnu7vXlFkVThchBFs4qJZFTePsJrXj36qShNcWwBT92b4eE5BZuj6+y0259wH/A+pZlmCiuq6S0PmukyGmgQX9ixqoWM3f5UcZr+kdO5an9YKF3TfqGrx04ZrnSzz9hWo5cV0NI1Thbx1qfMSgWw8aAzR5T+xnQiqmrLyIs+LnbXMFxFWkTrq6Asby/0CpzjG/TOl/yZgLZvQRrL4MBOOrEGhZxGSnn1mSXKBo88aeJvSAeY2K/AGgQB0coFuWYHzcXQpUEos1KUIACyN/AER2tSDemTP+XIMG8w==";
public static const TAG : String = "BLEHelper";
//private var appMain : AppMain;
// max length to limit characteristic values
public static const MAX_VALUE_LENGTH : int = 1000;
public var BleData:ByteArray = new ByteArray();
//private var receiveData:String = "";
/**
* Constructor
*/
public function Controller()
{
super();
//appMain = appM;
try
{
BluetoothLE.init( APP_KEY );
trace( "BluetoothLE.isSupported : " + BluetoothLE.isSupported );
if (BluetoothLE.isSupported)
{
trace( "BluetoothLE.version : " + BluetoothLE.service.version );
BluetoothLE.service.addEventListener( AuthorisationEvent.CHANGED, authorisationChangedHandler );
checkAndRequestAuthorisation();
}
setup();
}
catch (e:Error)
{
trace(e.message);
}
}
////////////////////////////////////////////////////////
// VARIABLES
//
private var _service : Service;
private var _characteristic : Characteristic;
private var writeCharacteristic:Characteristic;
private var _readCharacteristic:Characteristic;
private var _peripheral : Peripheral;
private var _autoConnect:Boolean = false;
public function set autoConnect(boo:Boolean):void{
_autoConnect = boo;
}
public function get autoConnect():Boolean{
return _autoConnect;
}
////////////////////////////////////////////////////////
// AUTHORISATION
//
public function checkAndRequestAuthorisation():void
{
if (BluetoothLE.isSupported)
{
trace( "Authorisation Status = "+BluetoothLE.service.authorisationStatus() );
switch (BluetoothLE.service.authorisationStatus())
{
case AuthorisationStatus.AUTHORISED:
break;
case AuthorisationStatus.NOT_DETERMINED:
case AuthorisationStatus.SHOULD_EXPLAIN:
BluetoothLE.service.requestAuthorisation();
break;
case AuthorisationStatus.DENIED:
case AuthorisationStatus.RESTRICTED:
case AuthorisationStatus.UNKNOWN:
break;
}
}
}
private function authorisationChangedHandler( event:AuthorisationEvent ):void
{
trace( "authorisationChangedHandler( " + event.status + " )");
}
////////////////////////////////////////////////////////
// SETUP
//
private var _isSetup : Boolean = false;
public function get isSetup():Boolean { return _isSetup; }
public function set isSetup(value:Boolean):void { _isSetup = value; }
public function setup(e:Event=null):void
{
try
{
BluetoothLE.init( APP_KEY );
}
catch (e:Error)
{
}
if (!isSetup)
{
try
{
trace( "BluetoothLE.isSupported = " + BluetoothLE.isSupported );
if (BluetoothLE.isSupported)
{
BluetoothLE.service.addEventListener( BluetoothLEEvent.STATE_CHANGED, stateChangedHandler );
trace( "BluetoothLE.service.version = " + BluetoothLE.service.version );
trace( "BluetoothLE.service.state = " + BluetoothLE.service.state );
BluetoothLE.service.centralManager.addEventListener( CentralManagerEvent.STATE_CHANGED, central_stateChangedHandler );
BluetoothLE.service.centralManager.addEventListener( PeripheralEvent.DISCOVERED, central_peripheralDiscoveredHandler );
BluetoothLE.service.centralManager.addEventListener( PeripheralEvent.CONNECT, central_peripheralConnectHandler );
BluetoothLE.service.centralManager.addEventListener( PeripheralEvent.CONNECT_FAIL, central_peripheralConnectFailHandler );
BluetoothLE.service.centralManager.addEventListener( PeripheralEvent.DISCONNECT, central_peripheralDisconnectHandler );
BluetoothLE.service.centralManager.addEventListener( PeripheralEvent.DISCOVER_SERVICES, central_peripheralDisconnectHandler );
BluetoothLE.service.centralManager.addEventListener( PeripheralEvent.DISCOVER_CHARACTERISTICS, central_peripheralDisconnectHandler );
}
else
{
trace( "BluetoothLE not supported" );
}
isSetup = true;
}
catch (e:Error)
{
trace( e.message );
}
}
}
private function setService(bleName:String):void{
if(_service) _service = null;
_service = new Service();
_service.uuid = "ffe0";
if(bleName == "BT16" || bleName == "ELEGOO BT16"){
if(SystemUtil.isIOS){
_characteristic = new Characteristic(
"ffe2",
[ Characteristic.PROPERTY_NOTIFY, Characteristic.PROPERTY_WRITE ],
[ Characteristic.PERMISSION_WRITEABLE ] );
_readCharacteristic = new Characteristic(
"ffe1",
[ Characteristic.PROPERTY_NOTIFY, Characteristic.PROPERTY_READ ],
[ Characteristic.PERMISSION_READABLE] );
}else{
_characteristic = new Characteristic(
"0000ffe2-0000-1000-8000-00805f9b34fb",
[ Characteristic.PROPERTY_NOTIFY, Characteristic.PROPERTY_WRITE ],
[ Characteristic.PERMISSION_WRITEABLE ] );
_readCharacteristic = new Characteristic(
"0000ffe1-0000-1000-8000-00805f9b34fb",
[ Characteristic.PROPERTY_NOTIFY, Characteristic.PROPERTY_READ ],
[ Characteristic.PERMISSION_READABLE] );
}
}else{
if(SystemUtil.isIOS){
_characteristic = new Characteristic(
"ffe1",
[ Characteristic.PROPERTY_NOTIFY, Characteristic.PROPERTY_READ, Characteristic.PROPERTY_WRITE ],
[ Characteristic.PERMISSION_READABLE, Characteristic.PERMISSION_WRITEABLE ] );
_readCharacteristic = new Characteristic(
"ffe1",
[ Characteristic.PROPERTY_NOTIFY, Characteristic.PROPERTY_READ, Characteristic.PROPERTY_WRITE ],
[ Characteristic.PERMISSION_READABLE, Characteristic.PERMISSION_WRITEABLE ] );
}else{
_characteristic = new Characteristic(
"0000ffe1-0000-1000-8000-00805f9b34fb",
[ Characteristic.PROPERTY_NOTIFY, Characteristic.PROPERTY_READ, Characteristic.PROPERTY_WRITE ],
[ Characteristic.PERMISSION_READABLE, Characteristic.PERMISSION_WRITEABLE ] );
_readCharacteristic = new Characteristic(
"0000ffe1-0000-1000-8000-00805f9b34fb",
[ Characteristic.PROPERTY_NOTIFY, Characteristic.PROPERTY_READ, Characteristic.PROPERTY_WRITE ],
[ Characteristic.PERMISSION_READABLE, Characteristic.PERMISSION_WRITEABLE ] );
}
}
_service.characteristics.push( _characteristic );
_service.characteristics.push( _readCharacteristic );
}
public function dispose(e:Event=null):void
{
if (isSetup)
{
trace( "dispose" );
BluetoothLE.service.dispose();
isSetup = false;
}
}
public function getPhoneBleState():String{
var str:String = BluetoothLE.service.state;
return str;
}
public function enableWithUI():void
{
if (isSetup)
{
trace( "enableWithUI" );
BluetoothLE.service.enableWithUI();
}
}
public function disable():void
{
if (isSetup)
{
unsubscribeCharacteristic();
BluetoothLE.service.centralManager.disconnect(_peripheral);
}
}
//
// CENTRAL
//
public function scan( e:Event=null ):void
{
if (!isSetup) return;
if(BluetoothLE.service.state == "off"){
var str:String = Translator.map("Please turn on Bluetooth");
Notify.getInstance().showNotify(str,false);
return;
}
//var services:Vector.<String> = new Vector.<String>("ffe0");
//BluetoothLE.service.centralManager.scanForPeripherals(services);
BluetoothLE.service.centralManager.scanForPeripherals();
}
private var timer:Timer;
public function refreshScan():void{
if(BluetoothLE.service.state == "off"){
var str:String = Translator.map("Please turn on Bluetooth");
Notify.getInstance().showNotify(str,false);
return;
}
if (!isSetup) return;
autoConnect = true;
/*if(timer != null){
timer.stop();
timer.removeEventListener(TimerEvent.TIMER,scanForPeripherals);
timer =null;
}*/
if(timer == null){
timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER,scanForPeripherals);
}
if(!timer.running)timer.start();
}
public function stopRefreshScan():void{
autoConnect = false;
this.stopScan();
if(timer){
timer.stop();
timer.removeEventListener(TimerEvent.TIMER,scanForPeripherals);
timer = null;
}
}
public function scanForPeripherals(e:TimerEvent=null):void
{
//BluetoothLE.service.centralManager.stopScan();
//trace( "scanForPeripherals" );
//BluetoothLE.service.centralManager.scanForPeripherals( new <String>[ _service.uuid ] );
BluetoothLE.service.centralManager.scanForPeripherals( );
}
public function stopScan(e:Event=null):void
{
if (!isSetup) return;
trace( "stopScan" );
BluetoothLE.service.centralManager.stopScan();
}
public function discoverServices(e:Event=null):void
{
if (!isSetup) return;
if (_peripheral == null) return;
trace( "discoverServices" );
_peripheral.discoverServices();
}
public function discoverCharacteristics( e:Event=null ):void
{
if (!isSetup) return;
if (_peripheral == null) return;
trace( "discoverCharacteristics" );
//setService();
var success:Boolean = _peripheral.discoverCharacteristics( _service );
trace( "discoverCharacteristics: success="+success );
}
public function readCharacteristic( e:Event=null ):void
{
if (!isSetup) return;
if (_peripheral == null) return;
// if (_peripheral.services.length == 0) return;
// if (_peripheral.services[0].characteristics.length == 0) return;
trace( "readCharacteristic" );
var success:Boolean = _peripheral.readValueForCharacteristic( _characteristic );
trace( "readCharacteristic: success="+success );
}
public function writeCharacteristic( str:String):void
{
if (!isSetup) return;
if (_peripheral == null) return;
var len:int = Math.ceil(str.length / 15);
for(var i:uint = 0;i< len;i++){
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes( str.substr(i*15,15) );
Starling.juggler.delayCall(writeValue,0.06 * i,bytes);
}
}
private function writeValue(data:ByteArray):void{
trace("sendValue:",data);
var success:Boolean = _peripheral.writeValueForCharacteristic( _characteristic, data );
if(!success){
//指令传输失败
trace("发送数据失败");
}
}
public function subscribeCharacteristic( ):void
{
if (!isSetup) return;
if (_peripheral == null) return;
var success:Boolean = _peripheral.subscribeToCharacteristic( _readCharacteristic );
trace( "subscribeCharacteristic: success="+success );
}
public function unsubscribeCharacteristic( e:Event=null ):void
{
if (!isSetup) return;
if (_peripheral == null) return;
var success:Boolean = _peripheral.unsubscribeToCharacteristic( _readCharacteristic );
trace( "unsubscribeCharacteristic: success="+success );
}
////////////////////////////////////////////////////////
// INTERNALS
//
private function setActivePeripheral( peripheral:Peripheral ):void
{
if (_peripheral != null)
{
_peripheral.removeEventListener( PeripheralEvent.DISCOVER_SERVICES, peripheral_discoverServicesHandler );
_peripheral.removeEventListener( PeripheralEvent.DISCOVER_CHARACTERISTICS, peripheral_discoverCharacteristicsHandler );
_peripheral.removeEventListener( CharacteristicEvent.UPDATE, peripheral_characteristic_updatedHandler );
_peripheral.removeEventListener( CharacteristicEvent.UPDATE_ERROR, peripheral_characteristic_errorHandler );
_peripheral.removeEventListener( CharacteristicEvent.WRITE_SUCCESS, peripheral_characteristic_writeHandler );
_peripheral.removeEventListener( CharacteristicEvent.WRITE_ERROR, peripheral_characteristic_writeErrorHandler );
_peripheral.removeEventListener( CharacteristicEvent.SUBSCRIBE, peripheral_characteristic_subscribeHandler );
_peripheral.removeEventListener( CharacteristicEvent.SUBSCRIBE_ERROR, peripheral_characteristic_subscribeErrorHandler );
_peripheral.removeEventListener( CharacteristicEvent.UNSUBSCRIBE, peripheral_characteristic_unsubscribeHandler );
_peripheral = null;
}
if (peripheral != null)
{
_peripheral = peripheral;
_peripheral.addEventListener( PeripheralEvent.DISCOVER_SERVICES, peripheral_discoverServicesHandler );
_peripheral.addEventListener( PeripheralEvent.DISCOVER_CHARACTERISTICS, peripheral_discoverCharacteristicsHandler );
_peripheral.addEventListener( CharacteristicEvent.UPDATE, peripheral_characteristic_updatedHandler );
_peripheral.addEventListener( CharacteristicEvent.UPDATE_ERROR, peripheral_characteristic_errorHandler );
_peripheral.addEventListener( CharacteristicEvent.WRITE_SUCCESS, peripheral_characteristic_writeHandler );
_peripheral.addEventListener( CharacteristicEvent.WRITE_ERROR, peripheral_characteristic_writeErrorHandler );
_peripheral.addEventListener( CharacteristicEvent.SUBSCRIBE, peripheral_characteristic_subscribeHandler );
_peripheral.addEventListener( CharacteristicEvent.SUBSCRIBE_ERROR, peripheral_characteristic_subscribeErrorHandler );
_peripheral.addEventListener( CharacteristicEvent.UNSUBSCRIBE, peripheral_characteristic_unsubscribeHandler );
}
}
////////////////////////////////////////////////////////
// EVENT HANDLERS
//
private function stateChangedHandler( event:BluetoothLEEvent ):void
{
trace( "state = " + BluetoothLE.service.state );
}
//
// CENTRAL EVENTS
//
private function central_stateChangedHandler( event:CentralManagerEvent ):void
{
trace( "central state = " + BluetoothLE.service.centralManager.state );
if(BluetoothLE.service.centralManager.state == "off"){
Globals.bleIsConnect = false;
}
Globals.dispatcher.dispatchEventWith(BleConnecting.CENTRALSRATE,false,BluetoothLE.service.centralManager.state);
}
private function central_peripheralDiscoveredHandler( event:PeripheralEvent ):void
{
var iRssi:int = Math.abs(event.RSSI);
var power:Number = (iRssi-59)/(10*2.0);
var dis:Number = Math.pow(10, power);
//trace( "peripheral discovered: name: "+ event.peripheral.name + " distance:",+ dis );
//trace( "peripheral discovered: uuid: "+ event.peripheral.uuid );
if(autoConnect){
//trace("name:",event.peripheral.name,"distance:",dis);
if(dis <= 0.25){
setService(event.peripheral.name);
BluetoothLE.service.centralManager.stopScan();
timer.stop();
BluetoothLE.service.centralManager.connect( event.peripheral );
}
}else{
//trace("name:",event.peripheral.name);
if(bleList.indexOf(event.peripheral.uuid) == -1){
if(event.peripheral.name != ""){
var obj:Object = {"text":event.peripheral.name,"peripheral":event.peripheral,"uuid":event.peripheral.uuid};
bleList.push(event.peripheral.uuid);
Globals.dispatcher.dispatchEventWith("BLE_LIST_CHANGE",false,obj);
}
}
}
}
public function clearBleList():void{
bleList = [];
}
public var bleList:Array = [];
public function connect_peripheral(peripheral:Peripheral):void{
trace("connect_peripheral");
setService(peripheral.name);
BluetoothLE.service.centralManager.connect(peripheral );
}
private function central_peripheralConnectHandler( event:PeripheralEvent ):void
{
trace( "peripheral connected: "+ event.peripheral.toString() );
trace(BluetoothLE.service.centralManager.peripherals.length);
if(BluetoothLE.service.centralManager.peripherals.length > 1){
//BluetoothLE.service.centralManager.peripherals.pop();
event.peripheral.unsubscribeToCharacteristic(_readCharacteristic);
event.peripheral = null;
return;
}
trace("setActivePeripheral");
setActivePeripheral( event.peripheral );
Globals.bleIsConnect = true;
Globals.dispatcher.dispatchEventWith(Root.HIDE_CONNECTING);
Globals.dispatcher.dispatchEventWith("blueTConnected");
discoverServices();
}
private function central_peripheralConnectFailHandler( event:PeripheralEvent ):void
{
trace( "peripheral connect fail: "+ event.peripheral.name );
Notify.getInstance().showNotify("Bluetooth connection failed!",true);
setActivePeripheral( null );
}
private function central_peripheralDisconnectHandler( event:PeripheralEvent ):void
{
trace( "peripheral disconnect: "+ event.peripheral.name );
_peripheral = event.peripheral;
trace(_peripheral.identifier,"------",BluetoothLE.service.centralManager.peripherals.length);
trace(event.peripheral.unsubscribeToCharacteristic(_readCharacteristic));
setActivePeripheral( null );
Globals.bleIsConnect = false;
Globals.dispatcher.dispatchEventWith("BleDisconnect");
Notify.getInstance().showNotify(Translator.map("Bluetooth disconnected"),true);
}
//
// PERIPHERAL EVENTS
//
private function peripheral_discoverServicesHandler( event:PeripheralEvent ):void
{
trace( "peripheral discover services: " + event.peripheral.name );
for each (var service:Service in event.peripheral.services)
{
trace( "service: "+ service.uuid );
}
discoverCharacteristics();
}
private function peripheral_discoverCharacteristicsHandler( event:PeripheralEvent ):void
{
trace( "peripheral discover characteristics: " + event.peripheral.name );
for each (var service:Service in event.peripheral.services)
{
//trace( "service: "+ service.uuid );
for each (var ch:Characteristic in service.characteristics)
{
trace( "characteristic: "+ch.uuid );
}
}
subscribeCharacteristic();
}
private function peripheral_characteristic_updatedHandler( event:CharacteristicEvent ):void
{
//trace( "peripheral characteristic updated: " + event.characteristic.uuid
//+ " value="+ event.characteristic.value.readUTFBytes( event.characteristic.value.length ) );
//trace(event.characteristic.value);
BleData.writeBytes(event.characteristic.value);
if(BleData.length > 0){
var data:String = BleData.toString();
trace("data:",data);
if(data.charAt(0) == "{" && data.charAt(data.length -1)== "}"){
//trace("data:",data);
Globals.dispatcher.dispatchEventWith("ReceiveData",false,data.slice(1,data.length -1));
BleData.clear();
}
}
}
private function peripheral_characteristic_errorHandler( event:CharacteristicEvent ):void
{
trace( "peripheral characteristic error: [" + event.errorCode +"] "+event.error );
}
private function peripheral_characteristic_writeHandler( event:CharacteristicEvent ):void
{
trace( "peripheral characteristic write: " + event.peripheral.name );
}
private function peripheral_characteristic_writeErrorHandler( event:CharacteristicEvent ):void
{
trace( "peripheral characteristic error: [" + event.errorCode +"] "+event.error );
}
private function peripheral_characteristic_subscribeHandler( event:CharacteristicEvent ):void
{
trace( "peripheral characteristic subscribe: " + event.peripheral.name );
}
private function peripheral_characteristic_subscribeErrorHandler( event:CharacteristicEvent ):void
{
trace( "peripheral characteristic error: [" + event.errorCode +"] "+event.error );
}
private function peripheral_characteristic_unsubscribeHandler( event:CharacteristicEvent ):void
{
trace( "peripheral characteristic unsubscribe: " + event.peripheral.name );
}
}
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search