index.uts 14.9 KB
Newer Older
打打卡夫卡's avatar
打打卡夫卡 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
import Context from "android.content.Context";
import {UTSAndroid } from "io.dcloud.uts";
import WifiManager from "android.net.wifi.WifiManager";
import WifiInfo from "android.net.wifi.WifiInfo";
import Manifest from "android.Manifest";
import PackageManager from "android.content.pm.PackageManager";
import ScanResult from "android.net.wifi.ScanResult";
import BroadcastReceiver from "android.content.BroadcastReceiver";
import ActivityCompat from "androidx.core.app.ActivityCompat";
import IntentFilter from "android.content.IntentFilter";
import Gson from "com.google.gson.Gson";
import JSONObject from "com.alibaba.fastjson.JSONObject";
import Intent from "android.content.Intent";
import Thread from "java.lang.Thread";
import WifiConfiguration from 'android.net.wifi.WifiConfiguration';
import AuthAlgorithm from 'android.net.wifi.WifiConfiguration.AuthAlgorithm';
import KeyMgmt from 'android.net.wifi.WifiConfiguration.KeyMgmt';
import TextUtils from 'android.text.TextUtils';

/**
 * Wifi 函数通用入参封装
 */
type WifiOption = {
	success?: (res: object) => void;
	fail?: (res: object) => void;
	complete?: (res: object) => void;
};

/**
 * Wifi 链接参数封装
 */
type WifiConnectOption = {
	SSID:string;
	BSSID:string;
	password:string;
	maunal:boolean;
	partialInfo:boolean;
	success?: (res: object) => void;
	fail?: (res: object) => void;
	complete?: (res: object) => void;
}


function isHex(key:string):boolean {
	for (var i = key.length - 1; i >= 0; i--) {
		let c = key.charAt(i);
		if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
				&& c <= 'f')) {
			return false;
		}
	}

	return true;
}


/**
 * 判断是否是wep格式的key
 */
function isHexWepKey(wepKey:string):boolean {
	let len = wepKey.length;

	// WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
	if (len != 10 && len != 26 && len != 58) {
		return false;
	}

	return isHex(wepKey);
}

function wrapWifiConfiguration(SSID:string ,password:string,passwordType:string):WifiConfiguration {
		
	let config = new WifiConfiguration();
	
	config.allowedAuthAlgorithms.clear();
	config.allowedGroupCiphers.clear();
	config.allowedKeyManagement.clear();
	config.allowedPairwiseCiphers.clear();
	config.allowedProtocols.clear();
	config.SSID = "\"" + SSID + "\"";
	
	
	// nopass
	if ("NONE".equals(passwordType)) {
		config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
	}
	// // wep
	if ("WEP".equals(passwordType)) {
		if (!TextUtils.isEmpty(password)) {
			if (isHexWepKey(password)) {
				config.wepKeys[0] = password;
			} else {
				config.wepKeys[0] = "\"" + password + "\"";
			}
		}
		config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
		config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
		config.allowedKeyManagement.set(KeyMgmt.NONE);
		config.wepTxKeyIndex = 0;
	}
	// wpa
	if ("WPA".equals(passwordType)) {
		config.preSharedKey = "\"" + password + "\"";
		config.hiddenSSID = true;
		config.allowedAuthAlgorithms
				.set(WifiConfiguration.AuthAlgorithm.OPEN);
		config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
		config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
		config.allowedPairwiseCiphers
				.set(WifiConfiguration.PairwiseCipher.TKIP);
		// 此处需要修改否则不能自动重联
		config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
		config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
		config.allowedPairwiseCiphers
				.set(WifiConfiguration.PairwiseCipher.CCMP);
		config.status = WifiConfiguration.Status.ENABLED;
	}
	
	return config;
}
/**
 * Wifi信息统一数据结构
 */
class UniWifiInfo {

	SSID: String = "";
	BSSID: String = "";
	secure: boolean = false;
	signalStrength: Number = 0;
	frequency: Number = 0;
	
	/*下面的字段属于扩展字段*/
	securityType:string = ""

	constructor(scanResult?: ScanResult) {
		if (scanResult != null) {
			// 如果是通过扫描列表得到的数据,进行封装
			this.BSSID = scanResult.BSSID;
			this.SSID = scanResult.SSID;

			this.signalStrength = scanResult.level;
			this.frequency = scanResult.frequency;

			// 是否安全,微信的标准是是否需要密码。 来源:https://developers.weixin.qq.com/community/develop/doc/00064cf1790458db19cddf9925ac00?highLine=WifiInfo
			this.secure = false;
			let capabilities = scanResult.capabilities.trim();
			if ((capabilities.equals(Global.WIFI_AUTH_OPEN) || capabilities.equals(Global.WIFI_AUTH_ROAM))) {
				this.secure = false;
			} else {
				this.secure = true;
			}
			
			/*扩展字段*/
			this.securityType = getSecurityType(scanResult);
		}
	}

	/**
	 * 根据connectInfo 链接信息对wifi数据结构进行初始化
	 */
	wrapConnectInfo(connectInfo: WifiInfo): void {
		console.log(connectInfo.getSSID());
		console.log(connectInfo.getBSSID());
		if (connectInfo.getBSSID() == null) {
			return
		}
		if (connectInfo.getSSID() != null) {
			let s = connectInfo.getSSID();
			// 微信不带,这里需要去掉引号
			if (s.length > 2 && s.charAt(0) == '"' && s.charAt(s.length - 1) == '"') {
				s = s.substring(1, s.length - 1);
			}
			this.SSID = s;
		}

		this.BSSID = connectInfo.getBSSID();
		//Android返回的值是-100~0,而微信API规范是0~100,值越大信号越好,需要+100拉齐
		this.signalStrength = connectInfo.getRssi() + 100; 
		this.frequency = connectInfo.getFrequency();

	}


}

/**
 * 获取当前链接的wifi信息
 */
type GetConnectedWifiOptions = {
	partialInfo?: boolean
	success?: (res: UTSJSONObject) => void
	fail?: (res: UTSJSONObject) => void
	complete?: (res: UTSJSONObject) => void
}



/**
 * 全局数据储存
 */
class Global {
	static mReceiver?: CustomBroadcastReceiver = null;
	static scanList: UniWifiInfo[] = []
	static WIFI_AUTH_OPEN: String = "";
	static WIFI_AUTH_ROAM: String = "[ESS]";
	static getWifiListCallbackList: UTSCallback[] = []
	static onWifiConnectCallbackList: UTSCallback[] = []
}


function getSecurityType(result:ScanResult):string {
    if (result.capabilities.contains("WEP")) {
        return "WEP";
    } else if (result.capabilities.contains("PSK")) {
        return "WPA";
    } else if (result.capabilities.contains("EAP")) {
        return "EAP";
    }
    return "NONE";
}


/**
 * 自定义wifi变化广播监听器
 */
class CustomBroadcastReceiver extends BroadcastReceiver {

	mWifiManager?: WifiManager = null;

	constructor(wifiManager: WifiManager) {
		super();
		this.mWifiManager = wifiManager;
	}

	override onReceive(_context: Context, intent: Intent): void {


		if (intent.action == WifiManager.WIFI_STATE_CHANGED_ACTION) {
			let state =
				intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)
			if (state == WifiManager.WIFI_STATE_ENABLED) {
				// 获取当前的connectInfo 并且进行数据封装
				let uniWifiInfo = new UniWifiInfo(null)
				//做一些异步操作
				setTimeout(function() {
					// BroadcastReceiver 中不能执行耗时任务,需要使用setTimeout
					console.log(Thread.currentThread().getName())
					// @ts-ignore
					let winfo = this.mWifiManager!.getConnectionInfo();
					while (winfo.bssid == null) {
						Thread.sleep(1000)
						winfo = this.mWifiManager!.getConnectionInfo();
					}

					// 封装成数据对象
					uniWifiInfo.wrapConnectInfo(winfo)
					let res = {
						errMsg: 'onWifiConnected:ok',
						errCode: 0,
						wifi: uniWifiInfo
					}
					// wifi状态可用了,分发当前的链接状态给已注册的监听集合
					for (let perCallback in Global.onWifiConnectCallbackList) {
						perCallback(res);
					}

				}, 100);
			}

		}


		if (intent.action == WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) {
			// wifi 扫描结果回调
			let results = this.mWifiManager!.scanResults;

			if (results != null) {
				Global.scanList = []
				for (let scanResult in results) {
					if (scanResult.SSID == null) {
						continue;
					}
					Global.scanList.push(new UniWifiInfo(scanResult));
				}

				// 挨个通知,所有的监听器
				for (let perCallback in Global.getWifiListCallbackList) {

					const data = new JSONObject();
					let mainJsonStr = Gson().toJson(Global.scanList);
					data["wifiList"] = mainJsonStr
					perCallback(data);
				}

			}

		}
	}

}



/************************* 下面是对外提供的函数 *************************/

/**
 * 获取wifi列表
 */

export function getWifiList(option: WifiOption) {
	
	if (Global.mReceiver == null) {
		// 还没调用startWifi 提示报错
		var result = {
			errCode: 12000,
			errMsg: "getWifiList:fail:not invoke startWifi",
			errSubject:"uni-getWifiList"
		}
		option.fail?.(result)
		option.complete?.(result)
		return
	}
	
	let wifiManager: WifiManager =
		UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
	wifiManager.startScan()

	let ret = {
		errCode: 0,
		errMsg: "getWifiList:ok"
	}
	option.success?.(ret)
	option.complete?.(ret)

}



/**
 * wifi 链接成功的回调注册
 */
export function onWifiConnected(callback: UTSCallback) {
	Global.onWifiConnectCallbackList.push(callback)
}

/**
 * wifi 链接成功的回调取消注册
 */
export function offWifiConnected(callback: UTSCallback) {
	let callbackIndex = Global.onWifiConnectCallbackList.indexOf(callback)
	if (callbackIndex > 0) {
		Global.onWifiConnectCallbackList.splice(callbackIndex, 1);
	}
}

/**
 * 注册Wifi列表的监听事件
 */
export function onGetWifiList(callback: UTSCallback) {
	Global.getWifiListCallbackList.push(callback)
}
/**
 * 取消注册Wifi列表的监听事件
 */
export function offGetWifiList(callback: UTSCallback) {
	let callbackIndex = Global.getWifiListCallbackList.indexOf(callback)
	if (callbackIndex > 0) {
		Global.getWifiListCallbackList.splice(callbackIndex, 1);
	}
}


/**
 * 链接指定wifi
 */
export function connectWifi(option: WifiConnectOption) {
	

	var result = {
		errCode: 12000,
		errMsg: "connectWifi:fail:not invoke startWifi",
		errSubject:"uni-connectWifi"
	}
	
	if (Global.mReceiver == null || Global.scanList.length < 1) {
		// 还没调用startWifi 提示报错
		option.fail?.(result)
		option.complete?.(result)
	
		return
	}
	
	if(option.maunal == true){
		// 指定了手动模式
		let manunalIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
		UTSAndroid.getUniActivity()!!.startActivity(manunalIntent);
		
		result.errCode = 0
		result.errMsg = "connectWifi:ok"
		
		option.success?.(result)
		option.complete?.(result)
		return 
	}
	
	// 执行后续的逻辑
	let scanWifiInfo:UniWifiInfo|null = null
	for (let scanResult in Global.scanList) {
		
		if (scanResult.SSID.equals(option.SSID)) {
			scanWifiInfo = scanResult
		}
	}
	
	if(scanWifiInfo == null){
		// 不在扫描列表中返回错误
		option.fail?.(result)
		option.complete?.(result)
		
		return
	}
	
	console.log(JSON.stringify(scanWifiInfo.securityType));
	
	let wifiConfigration = wrapWifiConfiguration(option.SSID,option.password,scanWifiInfo.securityType);
	
	let wifiManager: WifiManager =
		UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
	
	// 如果已经存在了指定wifi 配置,移除之
	let targetExistConfig:WifiConfiguration|null = null
	let existingConfigs = wifiManager.getConfiguredNetworks();
	for (let existingConfig in existingConfigs) {
		if (existingConfig.SSID.equals("\"" + option.SSID + "\"")) {
			targetExistConfig = existingConfig
		}
	}
	
	if (targetExistConfig != null) {
		wifiManager.removeNetwork(targetExistConfig.networkId);
	}
	
	try {
		let netID = wifiManager.addNetwork(wifiConfigration);
		let enabled = wifiManager.enableNetwork(netID, true);
		let connected = wifiManager.reconnect();
		console.log(connected);
	} catch (e) {
		// TODO: handle exception
		console.log(e);
		// e.printStackTrace();
		
	}
	
	result.errCode = 0
	result.errMsg = "connectWifi:ok"
	
	option.success?.(result)
	option.complete?.(result)
	
	
}

/**
 * 开启wifi
 */
export function startWifi(option: WifiOption) {
	
	
	
	// 需要先开启wifi,才能使用后续的功能
	let requestCode = 1001;
	let permissionWifi = arrayOf("android.permission.ACCESS_FINE_LOCATION");
	var result = {
		errCode: 12001,
		errMsg: "startWifi:premission loss",
		errSubject:"uni-startWifi",
	}
	// 检查权限
	if (ActivityCompat.checkSelfPermission(UTSAndroid.getUniActivity()!, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

		ActivityCompat.requestPermissions(UTSAndroid.getUniActivity()!, permissionWifi, requestCode)
		// 尚不具备权限,返回错误
		option.fail?.(result)
		option.complete?.(result)

		return;
	}

	// 具备了权限,继续前进
	let wifiManager: WifiManager =
		UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager

	if (Global.mReceiver == null) {
		Global.mReceiver = new CustomBroadcastReceiver(wifiManager)
	}

	let filter = new IntentFilter()
	filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
	// @ts-ignore
	filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
	// @ts-ignore
	filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);

	UTSAndroid.getUniActivity()!.registerReceiver(Global.mReceiver, filter)
	wifiManager.startScan()
	result.errCode = 0
	result.errMsg = "startWifi:ok"
	
	option.success?.(result)
	option.complete?.(result)

}


/**
 * 关闭wifi
 */
export function stopWifi(option: WifiOption) {
	// 需要先开启wifi,才能使用后续的功能
	if (Global.mReceiver == null) {
		var result = {
			errNo: 12000,
			errCode: 12000,
			errSubject:"uni-stopWifi",
			errMsg: "stopWifi:not init"
		}
		option.fail?.(result)
		option.complete?.(result)

		return
	}

	UTSAndroid.getUniActivity()!.unregisterReceiver(Global.mReceiver)
	var result = {
		errNo: 0,
		errCode: 0,
		errMsg: "stopWifi:ok"
	}
	option.success?.(result)
	option.complete?.(result)

}

/**
 * 获取当前连接中的wifi信息
 */
export function getConnectedWifi(option: GetConnectedWifiOptions) {

	let wifiInfo = new UniWifiInfo(null)

	var res = {
		errCode: 12000,
		errMsg: "getConnectedWifi:fail:not invoke startWifi",
		errSubject:"uni-getConnectedWifi",
		wifi:wifiInfo
	}

	if (Global.mReceiver == null) {
		// 还没调用startWifi 提示报错
		option.fail?.(res)
		option.complete?.(res)
	
		return
	}
	
	if (ActivityCompat.checkSelfPermission(UTSAndroid.getUniActivity()!, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
		// 尚不具备权限,返回错误
		res.errCode = 12001
		res.errMsg = "getConnectedWifi:permission loss"
		
		option.fail?.(res)
		option.complete?.(res)
		return;
	}

	// TODO 应该try catch一下,把系统的错误码给返回来,然后和微信的错误码拉齐
	// 需要先校验权限,没有位置权限无法获取wifi
	const context = UTSAndroid.getAppContext();
	if (context != null) {
		const wm = context.getSystemService(
			Context.WIFI_SERVICE
		) as WifiManager;
		// 测试android 12上可以使用
		//@ts-ignore
		const winfo = wm.getConnectionInfo();
		// 封装成数据对象
		wifiInfo.wrapConnectInfo(winfo);

		res.errCode = 0
		res.errMsg = "getConnectedWifi:ok"
		res.wifi = wifiInfo;
		option.success?.(res)
		option.complete?.(res)
		return
	}
	option.fail?.(res)
	option.complete?.(res)
}