vue操作蓝牙教程

项目背景

想在VUE中使用蓝牙功能,百度了好久也尝试了好多都没法实现。

概念讲价

如果要在浏览器中使用蓝牙,去搜索关键字【navigator.bluetooth】,搜索后发现这根本不是想要的结果。

解决方法

去搜索关键字【uniapp+bluetooth+vue】,这里的vue只是在uniapp中开发的语法,并不是传统的前端开发VUE。因为uniapp有好几种开发的语法。所以结果就是只能用uniapp开发一个网页的软件,然后打包成android的APP和IOS的APP。

uniapp开发的工具是【HBuilder】,现在最新的是【HBuilder X】。

操作教程

1、下载HBuilder X

// 官网下载地址

https://www.dcloud.io/hbuilderx.html

2、新建蓝牙项目

3、选择蓝牙模版项目

4、项目结构

它这个模版的项目是html5的,所以直接使用真机运行就行。然后就能看到效果了。真实的开发中我们是使用uniapp打包的apk,也就是uni-app+vue架构的项目。

 5、common.js

(function(w){
// 空函数
function shield(){
	return false;
}
document.addEventListener('touchstart', shield, false);//取消浏览器的所有事件,使得active的样式在手机上正常生效
document.oncontextmenu=shield;//屏蔽选择函数
// H5 plus事件处理
var ws=null,as='pop-in';
function plusReady(){
	ws=plus.webview.currentWebview();
	plus.key.addEventListener('backbutton', function(){
		back();
	},false);
}
if(w.plus){
	plusReady();
}else{
	document.addEventListener('plusready', plusReady, false);
}
// DOMContentLoaded事件处理
document.addEventListener('DOMContentLoaded', function(){
	gInit();
	document.body.onselectstart=shield;
},false);
// 返回
w.back=function(hide){
	if(w.plus){
		ws||(ws=plus.webview.currentWebview());
		(hide||ws.preate)?ws.hide('auto'):ws.close('auto');
	}else if(history.length>1){
		history.back();
	}else{
		w.close();
	}
};
// 处理点击事件
var openw=null;
/**
 * 打开新窗口
 * @param {URIString} id : 要打开页面url
 * @param {String} t : 页面标题名称
 * @param {JSON} ws : Webview窗口属性
 */
w.clicked=function(id, t, ws){
	if(openw){//避免多次打开同一个页面
		return null;
	}
	if(w.plus){
		ws=ws||{};
		ws.scrollIndicator||(ws.scrollIndicator='none');
		ws.scalable||(ws.scalable=false);
		ws.backButtonAutoControl||(ws.backButtonAutoControl='close');
		ws.titleNView=ws.titleNView||{autoBackButton:true};
		ws.titleNView.backgroundColor = '#D74B28';
		ws.titleNView.titleColor = '#CCCCCC';
		ws.doc&&(ws.titleNView.buttons=ws.titleNView.buttons||[],ws.titleNView.buttons.push({fontSrc:'_www/helloh5.ttf',text:'\ue301',fontSize:'20px',onclick:'javascript:openDoc()'}));
		t&&(ws.titleNView.titleText=t);
		openw = plus.webview.create(id, id, ws);
		openw.addEventListener('loaded', function(){
			openw.show(as);
		}, false);
		openw.addEventListener('close', function(){
			openw=null;
		}, false);
		return openw;
	}else{
		w.open(id);
	}
	return null;
};
/**
 * 创建新窗口(无原始标题栏),
 * @param {URIString} id : 要打开页面url
 * @param {JSON} ws : Webview窗口属性
 */
w.createWithoutTitle=function(id, ws){
	if(openw){//避免多次打开同一个页面
		return null;
	}
	if(w.plus){
		ws=ws||{};
		ws.scrollIndicator||(ws.scrollIndicator='none');
		ws.scalable||(ws.scalable=false);
		ws.backButtonAutoControl||(ws.backButtonAutoControl='close');
		openw = plus.webview.create(id, id, ws);
		openw.addEventListener('close', function(){
			openw=null;
		}, false);
		return openw;
	}else{
		w.open(id);
	}
	return null;
};
/**
 * 打开文档页面
 * @param {URIString} c : 要打开页面url
 */
w.openDoc=function(c){
	plus.webview.create(c, 'document', {
		titleNView:{
			autoBackButton:true,
			backgroundColor:'#D74B28',
			titleColor:'#CCCCCC'
		},
		backButtonAutoControl:'close',
		scalable:false
	}).show('pop-in');
};
/**
 * 兼容提示
 */
w.compatibleConfirm=function(){
	plus.nativeUI.confirm('本OS原生层面不提供该控件,需使用mui框架实现类似效果。请点击“确定”下载Hello mui示例',function(e){
		if(0==e.index){
			plus.runtime.openURL("http://www.dcloud.io/hellomui/");
		}
	},"",["确定","取消"]);
}
// 通用元素对象
var _dout_=null;
w.gInit=function(){
	_dout_=document.getElementById("output");
};
// 清空输出内容
w.outClean=function(){
	_dout_.innerText="";
	_dout_.scrollTop=0;//在iOS8存在不滚动的现象
};
// 输出内容
w.outSet=function(s){
	console.log(s);
	_dout_.innerText=s+"\n";
	(0==_dout_.scrollTop)&&(_dout_.scrollTop=1);//在iOS8存在不滚动的现象
};
// 输出行内容
w.outLine=function(s){
	console.log(s);
	_dout_.innerText+=s+"\n";
	(0==_dout_.scrollTop)&&(_dout_.scrollTop=1);//在iOS8存在不滚动的现象
};
// 格式化时长字符串,格式为"HH:MM:SS"
w.timeToStr=function(ts){
	if(isNaN(ts)){
		return "--:--:--";
	}
	var h=parseInt(ts/3600);
	var m=parseInt((ts%3600)/60);
	var s=parseInt(ts%60);
	return (ultZeroize(h)+":"+ultZeroize(m)+":"+ultZeroize(s));
};
// 格式化日期时间字符串,格式为"YYYY-MM-DD HH:MM:SS"
w.dateToStr=function(d){
	return (d.getFullYear()+"-"+ultZeroize(d.getMonth()+1)+"-"+ultZeroize(d.getDate())+" "+ultZeroize(d.getHours())+":"+ultZeroize(d.getMinutes())+":"+ultZeroize(d.getSeconds()));
};
/**
 * zeroize value with length(default is 2).
 * @param {Object} v
 * @param {Number} l
 * @return {String} 
 */
w.ultZeroize=function(v,l){
	var z="";
	l=l||2;
	v=String(v);
	for(var i=0;i<l-v.length;i++){
		z+="0";
	}
	return z+v;
};
})(window);

// fast click 
;(function () {
	'use strict';

	/**
	 * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
	 *
	 * @codingstandard ftlabs-jsv2
	 * @copyright The Financial Times Limited [All Rights Reserved]
	 * @license MIT License (see LICENSE.txt)
	 */

	/*jslint browser:true, node:true*/
	/*global define, Event, Node*/


	/**
	 * Instantiate fast-clicking listeners on the specified layer.
	 *
	 * @constructor
	 * @param {Element} layer The layer to listen on
	 * @param {Object} [options={}] The options to override the defaults
	 */
	function FastClick(layer, options) {
		var oldOnClick;

		options = options || {};

		/**
		 * Whether a click is currently being tracked.
		 *
		 * @type boolean
		 */
		this.trackingClick = false;


		/**
		 * Timestamp for when click tracking started.
		 *
		 * @type number
		 */
		this.trackingClickStart = 0;


		/**
		 * The element being tracked for a click.
		 *
		 * @type EventTarget
		 */
		this.targetElement = null;


		/**
		 * X-coordinate of touch start event.
		 *
		 * @type number
		 */
		this.touchStartX = 0;


		/**
		 * Y-coordinate of touch start event.
		 *
		 * @type number
		 */
		this.touchStartY = 0;


		/**
		 * ID of the last touch, retrieved from Touch.identifier.
		 *
		 * @type number
		 */
		this.lastTouchIdentifier = 0;


		/**
		 * Touchmove boundary, beyond which a click will be cancelled.
		 *
		 * @type number
		 */
		this.touchBoundary = options.touchBoundary || 10;


		/**
		 * The FastClick layer.
		 *
		 * @type Element
		 */
		this.layer = layer;

		/**
		 * The minimum time between tap(touchstart and touchend) events
		 *
		 * @type number
		 */
		this.tapDelay = options.tapDelay || 200;

		/**
		 * The maximum time for a tap
		 *
		 * @type number
		 */
		this.tapTimeout = options.tapTimeout || 700;

		if (FastClick.notNeeded(layer)) {
			return;
		}

		// Some old versions of Android don't have Function.prototype.bind
		function bind(method, context) {
			return function() { return method.apply(context, arguments); };
		}


		var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
		var context = this;
		for (var i = 0, l = methods.length; i < l; i++) {
			context[methods[i]] = bind(context[methods[i]], context);
		}

		// Set up event handlers as required
		if (deviceIsAndroid) {
			layer.addEventListener('mouseover', this.onMouse, true);
			layer.addEventListener('mousedown', this.onMouse, true);
			layer.addEventListener('mouseup', this.onMouse, true);
		}

		layer.addEventListener('click', this.onClick, true);
		layer.addEventListener('touchstart', this.onTouchStart, false);
		layer.addEventListener('touchmove', this.onTouchMove, false);
		layer.addEventListener('touchend', this.onTouchEnd, false);
		layer.addEventListener('touchcancel', this.onTouchCancel, false);

		// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
		// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
		// layer when they are cancelled.
		if (!Event.prototype.stopImmediatePropagation) {
			layer.removeEventListener = function(type, callback, capture) {
				var rmv = Node.prototype.removeEventListener;
				if (type === 'click') {
					rmv.call(layer, type, callback.hijacked || callback, capture);
				} else {
					rmv.call(layer, type, callback, capture);
				}
			};

			layer.addEventListener = function(type, callback, capture) {
				var adv = Node.prototype.addEventListener;
				if (type === 'click') {
					adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
						if (!event.propagationStopped) {
							callback(event);
						}
					}), capture);
				} else {
					adv.call(layer, type, callback, capture);
				}
			};
		}

		// If a handler is already declared in the element's onclick attribute, it will be fired before
		// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
		// adding it as listener.
		if (typeof layer.onclick === 'function') {

			// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
			// - the old one won't work if passed to addEventListener directly.
			oldOnClick = layer.onclick;
			layer.addEventListener('click', function(event) {
				oldOnClick(event);
			}, false);
			layer.onclick = null;
		}
	}

	/**
	* Windows Phone 8.1 fakes user agent string to look like Android and iPhone.
	*
	* @type boolean
	*/
	var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;

	/**
	 * Android requires exceptions.
	 *
	 * @type boolean
	 */
	var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;


	/**
	 * iOS requires exceptions.
	 *
	 * @type boolean
	 */
	var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;


	/**
	 * iOS 4 requires an exception for select elements.
	 *
	 * @type boolean
	 */
	var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);


	/**
	 * iOS 6.0-7.* requires the target element to be manually derived
	 *
	 * @type boolean
	 */
	var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent);

	/**
	 * BlackBerry requires exceptions.
	 *
	 * @type boolean
	 */
	var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;

	/**
	 * Determine whether a given element requires a native click.
	 *
	 * @param {EventTarget|Element} target Target DOM element
	 * @returns {boolean} Returns true if the element needs a native click
	 */
	FastClick.prototype.needsClick = function(target) {
		switch (target.nodeName.toLowerCase()) {

		// Don't send a synthetic click to disabled inputs (issue #62)
		case 'button':
		case 'select':
		case 'textarea':
			if (target.disabled) {
				return true;
			}

			break;
		case 'input':

			// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
			if ((deviceIsIOS && target.type === 'file') || target.disabled) {
				return true;
			}

			break;
		case 'label':
		case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
		case 'video':
			return true;
		}

		return (/\bneedsclick\b/).test(target.className);
	};


	/**
	 * Determine whether a given element requires a call to focus to simulate click into element.
	 *
	 * @param {EventTarget|Element} target Target DOM element
	 * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
	 */
	FastClick.prototype.needsFocus = function(target) {
		switch (target.nodeName.toLowerCase()) {
		case 'textarea':
			return true;
		case 'select':
			return !deviceIsAndroid;
		case 'input':
			switch (target.type) {
			case 'button':
			case 'checkbox':
			case 'file':
			case 'image':
			case 'radio':
			case 'submit':
				return false;
			}

			// No point in attempting to focus disabled inputs
			return !target.disabled && !target.readOnly;
		default:
			return (/\bneedsfocus\b/).test(target.className);
		}
	};


	/**
	 * Send a click event to the specified element.
	 *
	 * @param {EventTarget|Element} targetElement
	 * @param {Event} event
	 */
	FastClick.prototype.sendClick = function(targetElement, event) {
		var clickEvent, touch;

		// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
		if (document.activeElement && document.activeElement !== targetElement) {
			document.activeElement.blur();
		}

		touch = event.changedTouches[0];

		// Synthesise a click event, with an extra attribute so it can be tracked
		clickEvent = document.createEvent('MouseEvents');
		clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
		clickEvent.forwardedTouchEvent = true;
		targetElement.dispatchEvent(clickEvent);
	};

	FastClick.prototype.determineEventType = function(targetElement) {

		//Issue #159: Android Chrome Select Box does not open with a synthetic click event
		if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
			return 'mousedown';
		}

		return 'click';
	};


	/**
	 * @param {EventTarget|Element} targetElement
	 */
	FastClick.prototype.focus = function(targetElement) {
		var length;

		// Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
		if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
			length = targetElement.value.length;
			targetElement.setSelectionRange(length, length);
		} else {
			targetElement.focus();
		}
	};


	/**
	 * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
	 *
	 * @param {EventTarget|Element} targetElement
	 */
	FastClick.prototype.updateScrollParent = function(targetElement) {
		var scrollParent, parentElement;

		scrollParent = targetElement.fastClickScrollParent;

		// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
		// target element was moved to another parent.
		if (!scrollParent || !scrollParent.contains(targetElement)) {
			parentElement = targetElement;
			do {
				if (parentElement.scrollHeight > parentElement.offsetHeight) {
					scrollParent = parentElement;
					targetElement.fastClickScrollParent = parentElement;
					break;
				}

				parentElement = parentElement.parentElement;
			} while (parentElement);
		}

		// Always update the scroll top tracker if possible.
		if (scrollParent) {
			scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
		}
	};


	/**
	 * @param {EventTarget} targetElement
	 * @returns {Element|EventTarget}
	 */
	FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {

		// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
		if (eventTarget.nodeType === Node.TEXT_NODE) {
			return eventTarget.parentNode;
		}

		return eventTarget;
	};


	/**
	 * On touch start, record the position and scroll offset.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchStart = function(event) {
		var targetElement, touch, selection;

		// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
		if (event.targetTouches.length > 1) {
			return true;
		}

		targetElement = this.getTargetElementFromEventTarget(event.target);
		touch = event.targetTouches[0];

		if (deviceIsIOS) {

			// Only trusted events will deselect text on iOS (issue #49)
			selection = window.getSelection();
			if (selection.rangeCount && !selection.isCollapsed) {
				return true;
			}

			if (!deviceIsIOS4) {

				// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
				// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
				// with the same identifier as the touch event that previously triggered the click that triggered the alert.
				// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
				// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
				// Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
				// which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
				// random integers, it's safe to to continue if the identifier is 0 here.
				if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
					event.preventDefault();
					return false;
				}

				this.lastTouchIdentifier = touch.identifier;

				// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
				// 1) the user does a fling scroll on the scrollable layer
				// 2) the user stops the fling scroll with another tap
				// then the event.target of the last 'touchend' event will be the element that was under the user's finger
				// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
				// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
				this.updateScrollParent(targetElement);
			}
		}

		this.trackingClick = true;
		this.trackingClickStart = event.timeStamp;
		this.targetElement = targetElement;

		this.touchStartX = touch.pageX;
		this.touchStartY = touch.pageY;

		// Prevent phantom clicks on fast double-tap (issue #36)
		if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
			event.preventDefault();
		}

		return true;
	};


	/**
	 * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.touchHasMoved = function(event) {
		var touch = event.changedTouches[0], boundary = this.touchBoundary;

		if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
			return true;
		}

		return false;
	};


	/**
	 * Update the last position.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchMove = function(event) {
		if (!this.trackingClick) {
			return true;
		}

		// If the touch has moved, cancel the click tracking
		if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
			this.trackingClick = false;
			this.targetElement = null;
		}

		return true;
	};


	/**
	 * Attempt to find the labelled control for the given label element.
	 *
	 * @param {EventTarget|HTMLLabelElement} labelElement
	 * @returns {Element|null}
	 */
	FastClick.prototype.findControl = function(labelElement) {

		// Fast path for newer browsers supporting the HTML5 control attribute
		if (labelElement.control !== undefined) {
			return labelElement.control;
		}

		// All browsers under test that support touch events also support the HTML5 htmlFor attribute
		if (labelElement.htmlFor) {
			return document.getElementById(labelElement.htmlFor);
		}

		// If no for attribute exists, attempt to retrieve the first labellable descendant element
		// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
		return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
	};


	/**
	 * On touch end, determine whether to send a click event at once.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchEnd = function(event) {
		var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;

		if (!this.trackingClick) {
			return true;
		}

		// Prevent phantom clicks on fast double-tap (issue #36)
		if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
			this.cancelNextClick = true;
			return true;
		}

		if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
			return true;
		}

		// Reset to prevent wrong click cancel on input (issue #156).
		this.cancelNextClick = false;

		this.lastClickTime = event.timeStamp;

		trackingClickStart = this.trackingClickStart;
		this.trackingClick = false;
		this.trackingClickStart = 0;

		// On some iOS devices, the targetElement supplied with the event is invalid if the layer
		// is performing a transition or scroll, and has to be re-detected manually. Note that
		// for this to function correctly, it must be called *after* the event target is checked!
		// See issue #57; also filed as rdar://13048589 .
		if (deviceIsIOSWithBadTarget) {
			touch = event.changedTouches[0];

			// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
			targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
			targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
		}

		targetTagName = targetElement.tagName.toLowerCase();
		if (targetTagName === 'label') {
			forElement = this.findControl(targetElement);
			if (forElement) {
				this.focus(targetElement);
				if (deviceIsAndroid) {
					return false;
				}

				targetElement = forElement;
			}
		} else if (this.needsFocus(targetElement)) {

			// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
			// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
			if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
				this.targetElement = null;
				return false;
			}

			this.focus(targetElement);
			this.sendClick(targetElement, event);

			// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
			// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
			if (!deviceIsIOS || targetTagName !== 'select') {
				this.targetElement = null;
				event.preventDefault();
			}

			return false;
		}

		if (deviceIsIOS && !deviceIsIOS4) {

			// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
			// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
			scrollParent = targetElement.fastClickScrollParent;
			if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
				return true;
			}
		}

		// Prevent the actual click from going though - unless the target node is marked as requiring
		// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
		if (!this.needsClick(targetElement)) {
			event.preventDefault();
			this.sendClick(targetElement, event);
		}

		return false;
	};


	/**
	 * On touch cancel, stop tracking the click.
	 *
	 * @returns {void}
	 */
	FastClick.prototype.onTouchCancel = function() {
		this.trackingClick = false;
		this.targetElement = null;
	};


	/**
	 * Determine mouse events which should be permitted.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onMouse = function(event) {

		// If a target element was never set (because a touch event was never fired) allow the event
		if (!this.targetElement) {
			return true;
		}

		if (event.forwardedTouchEvent) {
			return true;
		}

		// Programmatically generated events targeting a specific element should be permitted
		if (!event.cancelable) {
			return true;
		}

		// Derive and check the target element to see whether the mouse event needs to be permitted;
		// unless explicitly enabled, prevent non-touch click events from triggering actions,
		// to prevent ghost/doubleclicks.
		if (!this.needsClick(this.targetElement) || this.cancelNextClick) {

			// Prevent any user-added listeners declared on FastClick element from being fired.
			if (event.stopImmediatePropagation) {
				event.stopImmediatePropagation();
			} else {

				// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
				event.propagationStopped = true;
			}

			// Cancel the event
			event.stopPropagation();
			event.preventDefault();

			return false;
		}

		// If the mouse event is permitted, return true for the action to go through.
		return true;
	};


	/**
	 * On actual clicks, determine whether this is a touch-generated click, a click action occurring
	 * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
	 * an actual click which should be permitted.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onClick = function(event) {
		var permitted;

		// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
		if (this.trackingClick) {
			this.targetElement = null;
			this.trackingClick = false;
			return true;
		}

		// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
		if (event.target.type === 'submit' && event.detail === 0) {
			return true;
		}

		permitted = this.onMouse(event);

		// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
		if (!permitted) {
			this.targetElement = null;
		}

		// If clicks are permitted, return true for the action to go through.
		return permitted;
	};


	/**
	 * Remove all FastClick's event listeners.
	 *
	 * @returns {void}
	 */
	FastClick.prototype.destroy = function() {
		var layer = this.layer;

		if (deviceIsAndroid) {
			layer.removeEventListener('mouseover', this.onMouse, true);
			layer.removeEventListener('mousedown', this.onMouse, true);
			layer.removeEventListener('mouseup', this.onMouse, true);
		}

		layer.removeEventListener('click', this.onClick, true);
		layer.removeEventListener('touchstart', this.onTouchStart, false);
		layer.removeEventListener('touchmove', this.onTouchMove, false);
		layer.removeEventListener('touchend', this.onTouchEnd, false);
		layer.removeEventListener('touchcancel', this.onTouchCancel, false);
	};


	/**
	 * Check whether FastClick is needed.
	 *
	 * @param {Element} layer The layer to listen on
	 */
	FastClick.notNeeded = function(layer) {
		var metaViewport;
		var chromeVersion;
		var blackberryVersion;
		var firefoxVersion;

		// Devices that don't support touch don't need FastClick
		if (typeof window.ontouchstart === 'undefined') {
			return true;
		}

		// Chrome version - zero for other browsers
		chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];

		if (chromeVersion) {

			if (deviceIsAndroid) {
				metaViewport = document.querySelector('meta[name=viewport]');

				if (metaViewport) {
					// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
					if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
						return true;
					}
					// Chrome 32 and above with width=device-width or less don't need FastClick
					if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
						return true;
					}
				}

			// Chrome desktop doesn't need FastClick (issue #15)
			} else {
				return true;
			}
		}

		if (deviceIsBlackBerry10) {
			blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);

			// BlackBerry 10.3+ does not require Fastclick library.
			// https://github.com/ftlabs/fastclick/issues/251
			if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
				metaViewport = document.querySelector('meta[name=viewport]');

				if (metaViewport) {
					// user-scalable=no eliminates click delay.
					if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
						return true;
					}
					// width=device-width (or less than device-width) eliminates click delay.
					if (document.documentElement.scrollWidth <= window.outerWidth) {
						return true;
					}
				}
			}
		}

		// IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
		if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {
			return true;
		}

		// Firefox version - zero for other browsers
		firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];

		if (firefoxVersion >= 27) {
			// Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896

			metaViewport = document.querySelector('meta[name=viewport]');
			if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
				return true;
			}
		}

		// IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version
		// http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
		if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {
			return true;
		}

		return false;
	};


	/**
	 * Factory method for creating a FastClick object
	 *
	 * @param {Element} layer The layer to listen on
	 * @param {Object} [options={}] The options to override the defaults
	 */
	FastClick.attach = function(layer, options) {
		return new FastClick(layer, options);
	};


	if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {

		// AMD. Register as an anonymous module.
		define(function() {
			return FastClick;
		});
	} else if (typeof module !== 'undefined' && module.exports) {
		module.exports = FastClick.attach;
		module.exports.FastClick = FastClick;
	} else {
		window.FastClick = FastClick;
	}

document.addEventListener('DOMContentLoaded', function() {
    FastClick.attach(document.body);
}, false);

}());

6、index.html

把这个js复制到自己的项目中,然后在自己的index.html文件中引用,如下所示。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
	<script>
	  var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
	    CSS.supports('top: constant(a)'))
	  document.write(
	    '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
	    (coverSupport ? ', viewport-fit=cover' : '') + '" />')
	</script>
	<script type="text/javascript" src="static/assets/js/common.js"></script>
    <title></title>
    <!--preload-links-->
    <!--app-context-->
  </head>
  <body>
    <div id="app"><!--app-html--></div>
    <script type="module" src="/main.js"></script>
  </body>
</html>

 7、bluetooth.html

所有实现的方法都在这里,自己参考着写一写。

<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8"/>
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
		<meta name="HandheldFriendly" content="true"/>
		<meta name="MobileOptimized" content="320"/>
		<title>Hello H5+</title>
		<script type="text/javascript" src="../js/common.js"></script>
		<script type="text/javascript">
var bds = []; // 可连接设备列表
var deviceId = null, bconnect = false;
var bss = [];	// 连接设备服务列表
var serviceId = null;
var bscs = [];	// 连接设备服务对应的特征值列表
var characteristicId = null;
var bscws = [];  // 可写特征值列表
var wcharacteristicId = null;
// 重设数据 
function resetDevices(d,s){
	d||(bds=[],deviceId=null,document.getElementById('deivce').value='');
	s||(bss=[],serviceId=null,document.getElementById('service').value='');
	bscs=[],bscws=[],characteristicId=null,wcharacteristicId=null,document.getElementById('characteristic').value='',document.getElementById('wcharacteristic').value='';
}

// 页面初始化操作 
document.addEventListener('plusready', function(e){
	// 监听蓝牙适配器状态变化
	plus.bluetooth.onBluetoothAdapterStateChange(function(e){
		outLine('onBluetoothAdapterStateChange: '+JSON.stringify(e));
	});
	//  监听搜索到新设备 
	plus.bluetooth.onBluetoothDeviceFound(function(e){
		var devices = e.devices;
		outLine('onBluetoothDeviceFound: '+devices.length);
		for(var i in devices){
			outLine(JSON.stringify(devices[i]));
			var device = devices[i];
			if(device.deviceId/*&&device.name&&device.name.length>0&&device.name!='null'*/){
				bds.push(device);
			}
		}
		if(!bconnect && bds.length>0){	// 默认选择最后一个
			var n = bds[bds.length-1].name;
			if(!n || n.length<=0){
				n = bds[bds.length-1].deviceId;
			}
			document.getElementById('deivce').value = n;
			deviceId = bds[bds.length-1].deviceId;
		}
	});
	//  监听低功耗蓝牙设备连接状态变化 
	plus.bluetooth.onBLEConnectionStateChange(function(e){
		outLine('onBLEConnectionStateChange: '+JSON.stringify(e));
		if(deviceId == e.deviceId){	// 更新连接状态
			bconnect = e.connected;
		}
	});
	// 监听低功耗蓝牙设备的特征值变化 
	plus.bluetooth.onBLECharacteristicValueChange(function(e){
		outLine('onBLECharacteristicValueChange: '+JSON.stringify(e));
		var value = buffer2hex(e.value);
		outLine('value(hex) = '+value);
		if(characteristicId == e.characteristicId){
			// 更新到页面显示
			document.getElementById('readvalue').value = value;
		}else if(wcharacteristicId == e.characteristicId){
			plus.nativeUI.toast(value);
		}
	});
}, false);

function buffer2hex(value){
	var t='';
	if(value){
		var v=new Uint8Array(value);
		for(var i in v){
			t += '0x'+v[i].toString(16)+' ';
		}
	}else{
		t='无效值';
	}
	return t;
}

// 打开蓝牙 
function openBluetooth(){
	outSet('打开蓝牙适配器:');
	plus.bluetooth.openBluetoothAdapter({
		success: function(e){
			outLine('打开成功!');
		},
		fail: function(e){
			outLine('打开失败! '+JSON.stringify(e));
		}
	});
}

// 开始搜索蓝牙设备 
function startDiscovery(){
	outSet('开始搜索蓝牙设备:');
	resetDevices();
	plus.bluetooth.startBluetoothDevicesDiscovery({
		success: function(e){
			outLine('开始搜索成功!');
		},
		fail: function(e){
			outLine('开始搜索失败! '+JSON.stringify(e));
		}
	});
}

// 停止搜索蓝牙设备 
function stopDiscovery(){
	outSet('停止搜索蓝牙设备:');
	plus.bluetooth.stopBluetoothDevicesDiscovery({
		success: function(e){
			outLine('停止搜索成功!');
		},
		fail: function(e){
			outLine('停止搜索失败! '+JSON.stringify(e));
		}
	});
}

// 选择蓝牙设备 
function selectDevice(){
	if(bds.length <= 0){
		plus.nativeUI.toast('未搜索到有效蓝牙设备!');
		return;
	}
	var bts=[];
	for(var i in bds){
		var t = bds[i].name;
		if(!t || t.length<=0){
			t = bds[i].deviceId;
		}		
		bts.push({title:t});
	}
	plus.nativeUI.actionSheet({title:"选择蓝牙设备",cancel:"取消",buttons:bts}, function(e){
		if(e.index>0){
			document.getElementById('deivce').value = bds[e.index-1].name;
			deviceId = bds[e.index-1].deviceId;
			outLine('选择了"'+bds[e.index-1].name+'"');
		}
	});
}

// 连接蓝牙设备 
function connectDevice(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	outSet('连接设备: '+deviceId);
	plus.bluetooth.createBLEConnection({
		deviceId: deviceId,
		success: function(e){
			outLine('连接成功!');
		},
		fail: function(e){
			outLine('连接失败! '+JSON.stringify(e));
		}
	});
}

// 获取设备服务 
function getServices(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if(!bconnect){
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	resetDevices(true);
	outSet('获取蓝牙设备服务:');
	plus.bluetooth.getBLEDeviceServices({
		deviceId: deviceId,
		success: function(e){
			var services = e.services;
			outLine('获取服务成功! '+services.length);
			if(services.length>0){
				for(var i in services){
					bss.push(services[i]);
					outLine(JSON.stringify(services[i]));
				}
				if(bss.length>0){	// 默认选择最后一个服务
					document.getElementById('service').value = serviceId = bss[bss.length-1].uuid;
				}
			}else{
				outLine('获取服务列表为空?');
			}
		},
		fail: function(e){
			outLine('获取服务失败! '+JSON.stringify(e));
		}
	});
}

// 选择服务 
function selectService(){
	if(bss.length <= 0){
		plus.nativeUI.toast('未获取到有效蓝牙服务!');
		return;
	}
	var bts=[];
	for(var i in bss){
		bts.push({title:bss[i].uuid});
	}
	plus.nativeUI.actionSheet({title:"选择服务",cancel:"取消",buttons:bts}, function(e){
		if(e.index>0){
			document.getElementById('service').value = serviceId = bss[e.index-1].uuid;
			outLine('选择了服务: "'+serviceId+'"');
		}
	});
}

// 获取服务的特征值 
function getCharacteristics(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if(!bconnect){
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	if(!serviceId){
		plus.nativeUI.toast('未选择服务!');
		return;
	}
	resetDevices(true, true);
	outSet('获取蓝牙设备指定服务的特征值:');
	plus.bluetooth.getBLEDeviceCharacteristics({
		deviceId: deviceId,
		serviceId: serviceId,
		success: function(e){
			var characteristics = e.characteristics;
			outLine('获取特征值成功! '+characteristics.length);
			if(characteristics.length>0){
				for(var i in characteristics){
					var characteristic = characteristics[i];
					outLine(JSON.stringify(characteristic));
					if(characteristic.properties){
						if(characteristic.properties.read){
							bscs.push(characteristics[i]);
						}
						if(characteristic.properties.write){
							bscws.push(characteristics[i]);
							if(characteristic.properties.notify||characteristic.properties.indicate){
								plus.bluetooth.notifyBLECharacteristicValueChange({	//监听数据变化
									deviceId: deviceId,
									serviceId: serviceId,
									characteristicId: characteristic.uuid,
									success: function(e){
										outLine('notifyBLECharacteristicValueChange '+characteristic.uuid+' success.');
									},
									fail: function(e){
										outLine('notifyBLECharacteristicValueChange '+characteristic.uuid+' failed! '+JSON.stringify(e));
									}
								});
							}
						}
					}
				}
				if(bscs.length>0){	// 默认选择最后特征值
					document.getElementById('characteristic').value = characteristicId = bscs[bscs.length-1].uuid;
				}
				if(bscws.length>0){	// 默认选择最后一个可写特征值
					document.getElementById('wcharacteristic').value = wcharacteristicId = bscws[bscws.length-1].uuid;
				}
			}else{
				outLine('获取特征值列表为空?');
			}
		},
		fail: function(e){
			outLine('获取特征值失败! '+JSON.stringify(e));
		}
	});
}

// 选择特征值(读取) 
function selectCharacteristic(){
	if(bscs.length <= 0){
		plus.nativeUI.toast('未获取到有效可读特征值!');
		return;
	}
	var bts=[];
	for(var i in bscs){
		bts.push({title:bscs[i].uuid});
	}
	plus.nativeUI.actionSheet({title:'选择特征值',cancel:'取消',buttons:bts}, function(e){
		if(e.index>0){
			document.getElementById('characteristic').value = characteristicId = bscs[e.index-1].uuid;
			outLine('选择了特征值: "'+characteristicId+'"');
		}
	});
}

// 读取特征值数据 
function readValue(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if(!bconnect){
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	if(!serviceId){
		plus.nativeUI.toast('未选择服务!');
		return;
	}
	if(!characteristicId){
		plus.nativeUI.toast('未选择读取的特征值!');
		return;
	}
	outSet('读取蓝牙设备的特征值数据: ');
	plus.bluetooth.readBLECharacteristicValue({
		deviceId: deviceId,
		serviceId: serviceId,
		characteristicId: characteristicId,
		success: function(e){
			outLine('读取数据成功!');
		},
		fail: function(e){
			outLine('读取数据失败! '+JSON.stringify(e));
		}
	});
}

// 选择特征值(写入) 
function selectwCharacteristic(){
	if(bscws.length <= 0){
		plus.nativeUI.toast('未获取到有效可写特征值!');
		return;
	}
	var bts=[];
	for(var i in bscws){
		bts.push({title:bscws[i].uuid});
	}
	plus.nativeUI.actionSheet({title:'选择特征值',cancel:'取消',buttons:bts}, function(e){
		if(e.index>0){
			document.getElementById('wcharacteristic').value = wcharacteristicId = bscws[e.index-1].uuid;
			outLine('选择了特征值: "'+wcharacteristicId+'"');
		}
	});
}

// 写入特征值数据 
function writeValue(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if(!bconnect){
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	if(!serviceId){
		plus.nativeUI.toast('未选择服务!');
		return;
	}
	if(!wcharacteristicId){
		plus.nativeUI.toast('未选择写入的特征值!');
		return;
	}
	var value = document.getElementById('writevalue').value;
	if(!value || value==''){
		plus.nativeUI.toast('请输入需要写入的数据');
		document.getElementById('writevalue').focus();
		return;
	}
	// 转换为ArrayBuffer写入蓝牙
	str2ArrayBuffer(value, function(buffer){
		outSet('写入蓝牙设备的特征值数据: ');
		plus.bluetooth.writeBLECharacteristicValue({
			deviceId: deviceId,
			serviceId: serviceId,
			characteristicId: wcharacteristicId,
			value: buffer,
			success: function(e){
				outLine('写入数据成功!');
			},
			fail: function(e){
				outLine('写入数据失败! '+JSON.stringify(e));
			}
		});
	});
}

function str2ArrayBuffer(s,f) {
    var b = new Blob([s],{type:'text/plain'});
    var r = new FileReader();
    r.readAsArrayBuffer(b);
    r.onload = function(){if(f)f.call(null,r.result)}
}


// 断开蓝牙设备
function disconnectDevice(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	resetDevices(true);
	outSet('断开蓝牙设备连接:');
	plus.bluetooth.closeBLEConnection({
		deviceId: deviceId,
		success: function(e){
			outLine('断开连接成功!');
		},
		fail: function(e){
			outLine('断开连接失败! '+JSON.stringify(e));
		}
	});
}

// 关闭蓝牙
function closeBluetooth(){
	outSet('关闭蓝牙适配器:');
	resetDevices();
	plus.bluetooth.closeBluetoothAdapter({
		success: function(e){
			outLine('关闭成功!');
			bconnect = false;
		},
		fail: function(e){
			outLine('关闭失败! '+JSON.stringify(e));
		}
	});
}
		</script>
		<link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8"/>
	</head>
	<body>
		<br/>
		<div class="button" onclick="openBluetooth()">初始化蓝牙模块</div>
		<div class="button" onclick="startDiscovery()">开始搜索蓝牙设备</div>
		<div class="button" onclick="stopDiscovery()">停止搜索蓝牙设备</div>
		设备:<input id="deivce" type="text" disabled="disabled"></input>
		<a href="#" onclick="selectDevice()">选择设备</a>
		<div class="button" onclick="connectDevice()">连接蓝牙设备</div>
		<div class="button" onclick="getServices()">获取设备服务</div>
		服务:<input id="service" type="text" disabled="disabled"></input>
		<a href="#" onclick="selectService()">选择服务</a>
		<div class="button" onclick="getCharacteristics()">获取服务的特征值</div>
		读取特征值:<input id="characteristic" type="text" disabled="disabled"></input>
		<a href="#" onclick="selectCharacteristic()">选择</a>
		<div class="button" onclick="readValue()">读取特征值数据</div>
		读取数据:<input id="readvalue" type="text" disabled="disabled" style="width:60%"></input>
		<hr/>
		<br/>
		写入特征值:<input id="wcharacteristic" type="text" disabled="disabled"></input>
		<a href="#" onclick="selectwCharacteristic()">选择</a>
		<div class="button" onclick="writeValue()">写入特征值数据</div>
		写入数据:<input id="writevalue" type="text" style="width:60%;-webkit-user-select:text" value="test"></input>
		<div class="button" onclick="disconnectDevice()">断开蓝牙设备</div>
		<div class="button" onclick="closeBluetooth()">关闭蓝牙模块</div>
		<div id="outpos"/>
		<div id="output">
Bluetooth用于管理蓝牙设备,搜索附近蓝牙设备、连接实现数据通信等。
		</div>
	</body>
</html>

8、权限勾选

上面说过了,它的html5的模版是可以直接运行的,不存在打包。然后我们开发APP,需要本地离线打包,然后注意在manifest.json勾选蓝牙。

9、离线打包

// 打包教程

https://blog.csdn.net/renkai721/article/details/139068540

打包的时候记得把HBuilder-HelloUniApp\app\libs\Bluetooth-release.aar的这个文件复制到HBuilder-Integrate-AS\simpleDemo\libs文件夹下面。

10、结束

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/699495.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Web前端三大主流框架简介与优缺点对比分析

随着互联网的快速发展&#xff0c;Web前端开发技术不断进步&#xff0c;各种前端框架应运而生&#xff0c;极大地提高了开发效率和用户体验。在众多框架中&#xff0c;React、Vue.js 和 Angular 是目前最受欢迎的三大主流框架。本文将对它们进行详细介绍&#xff0c;并对它们的…

110.网络游戏逆向分析与漏洞攻防-装备系统数据分析-装备与技能描述信息的处理

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 如果看不懂、不知道现在做的什么&#xff0c;那就跟着做完看效果&#xff0c;代码看不懂是正常的&#xff0c;只要会抄就行&#xff0c;抄着抄着就能懂了 内容…

网络数据库后端相关面试题(其三)

18&#xff0c; 传输控制协议tcp和用户数据报协议udp有哪些区别 第一&#xff0c;tcp是面向字节流的&#xff0c;基本的传输单位是tcp报文段&#xff1b;而udp是面向报文的&#xff0c;基本传输单位是用户数据报。 第二&#xff0c; tcp注重安全可靠性&#xff0c;连接双方在…

Linux网络 - HTTP协议

文章目录 前言一、HTTP协议1.urlurl特殊字符 requestrespond 总结 前言 上一章内容我们讲了在应用层制定了我们自己自定义的协议、序列化和反序列化。 协议的制定相对来讲还是比较麻烦的&#xff0c;不过既然应用层的协议制定是必要的&#xff0c;那么肯定已经有许多计算机大佬…

内存分配器性能优化

背景 在之前我们提到采用自定义的内存分配器来解决防止频繁 make 导致的 gc 问题。gc 问题本质上是 CPU 消耗&#xff0c;而内存分配器本身如果产生了大量的 CPU 消耗那就得不偿失。经过测试初代内存分配器实现过于简单&#xff0c;产生了很多 CPU 消耗&#xff0c;因此必须优…

果汁机锂电池充电,5V升压12.7V 升压恒压芯片SL1571B

在现代化的日常生活中&#xff0c;果汁机已经逐渐成为了许多家庭厨房的必备电器。随着科技的不断进步&#xff0c;果汁机的性能也在不断提升&#xff0c;其中锂电池的应用更是为果汁机带来了前所未有的便利。而5V升压12.7V升压恒压芯片SL1571B&#xff0c;作为果汁机锂电池充电…

skywalking9.4 链路追踪

下载&#xff0c;很慢很慢很慢&#xff01;&#xff01;&#xff01;&#xff01; jdk 使用jdk17 skywalking-apm 9.4 java-agent 9.0 idea 本地开发配置 第1行配置按实际来&#xff1b; 第2行自定义&#xff0c;一般和微服务名称相同&#xff1b; 第3行ip写安装的机器ip,端…

QQ音乐绿钻API接口:解锁更多音乐可能性

在我们日常生活中&#xff0c;音乐是不可或缺的一部分。无论是在上班途中&#xff0c;还是在健身房锻炼时&#xff0c;我们都可以通过听音乐来放松自己。然而&#xff0c;在现如今的音乐市场中&#xff0c;有时候我们会觉得收听的歌曲有限&#xff0c;想要尝试更多不同的音乐类…

量产导入 | DFT和ATE概述

什么是DFT DFT(Design for Test),即可测性设计。 一切为了芯片流片后测试所加入的逻辑设计,都叫DFT。 DFT只是为了测试芯片制造过程中有没有缺陷,而不是用来验证芯片功能的,芯片功能的完善应该应该是在芯片开发过程用先进验证方法学去做的。 芯片制造过程相当复杂,工艺缺陷…

降价潮背后:大模型落地门槛真的降了吗?

“比起价格门槛&#xff0c;AI大模型的应用门槛&#xff0c;更难跨越。” 大模型争相降价下&#xff0c;AI应用的门槛真的降低了吗&#xff1f; 答案还真不一定。因为除了价格门槛&#xff0c;AI大模型还有应用门槛。甚至&#xff0c;后者比前者更具挑战性。 B端业务场景向来…

3D感知视觉表示与模型分析:深入探究视觉基础模型的三维意识

在深度学习与大规模预训练的推动下&#xff0c;视觉基础模型展现出了令人印象深刻的泛化能力。这些模型不仅能够对任意图像进行分类、分割和生成&#xff0c;而且它们的中间表示对于其他视觉任务&#xff0c;如检测和分割&#xff0c;同样具有强大的零样本能力。然而&#xff0…

Java集合的组内平均值怎么计算

哈喽&#xff0c;大家好&#xff0c;我是木头左&#xff01; 在Java中&#xff0c;经常需要对集合进行各种操作&#xff0c;其中之一就是计算集合的组内平均值。本文将介绍如何使用Java集合来计算组内平均值&#xff0c;并提供一些示例代码和实用技巧。 1. 使用Java 8 Stream A…

MMdeploy在cuda+tensorrt下的配置和编译

MMdeploy在cudatensorrt下的配置和编译 Python安装配置MMdeploy配置openmmlab系列从工程安装mmdeploy MMdeploy_runtime以及demo编译安装量化编译runtime和demo Python安装配置MMdeploy 配置openmmlab系列 pip install -U openmim如果mim命令遭遇故障&#xff0c;或者安装失败…

龙迅LT9211D MIPIDSI/CSI桥接到2 PORT LVDS,支持 3840x2160 30Hz分辨率

龙迅LT9211D描述&#xff1a; LT9211D是一款高性能的MIPI DSI/CSI-2到双端口LVDS转换器。LT9211D反序列化输入的MIPI视频数据&#xff0c;解码数据包&#xff0c;并将格式化的视频数据流转换为AP和移动显示面板或摄像机之间的LVDS发射机输出。LT9211D支持最大12.5 dB输入均衡和…

boost asio异步服务器(3)增加发送队列实现全双工通信

增加发送节点 构造发送节点&#xff0c;管理发送数据。发送节点的类如下。 这个发送节点用于保证发送和接收数据的有效性。 增加发送队列 前边实现的是一个简单的echo服务器&#xff0c;也就是服务器将收到的内容发送给对应的客户端。但是在实际的服务器设计中&#xff0c;服务…

《精通ChatGPT:从入门到大师的Prompt指南》第7章:创意写作

第7章&#xff1a;创意写作 7.1 角色设定 角色设定是创意写作中最关键的环节之一。成功的角色设定能够让读者对故事产生共鸣&#xff0c;使故事更加生动有趣。角色不仅仅是情节发展的载体&#xff0c;更是读者情感的投射对象。因此&#xff0c;深入了解如何设定一个生动而有深…

讯方技术与华为终端签署鸿蒙合作协议,将为企业助培百万鸿蒙人才

1月18日&#xff0c;鸿蒙生态千帆启航仪式在深圳举行&#xff0c;华为宣布HarmonyOS NEXT鸿蒙星河版开发者预览面向开发者开放申请&#xff0c;这意味着鸿蒙生态进入第二阶段&#xff0c;将加速千行百业的应用鸿蒙化。讯方技术总裁刘国锋、副总经理刘铭皓应邀出席启航仪式&…

Tessy学习系列(四):组件测试——官方例程interior_light

一、新建工程 &#xff08;1&#xff09;新建工程 注意&#xff1a;路径不能包含空格与中文 &#xff08;2&#xff09;新建测试集 &#xff08;3&#xff09;新建组件测试模块 &#xff08;4&#xff09;设置测试模块为组件测试模块 二、导入源码 &#xff08;1&#xff09…

【ARM Cache 及 MMU 系列文章 6.4 -- Cache miss 统计详细介绍】

请阅读【ARM Cache 及 MMU/MPU 系列文章专栏导读】 及【嵌入式开发学习必备专栏】 文章目录 ARM Cache Miss 统计Cache 多层架构简介Cache 未命中的类型Cache 未命中统计Cache miss 统计代码实现Cache Miss 统计意义ARM Cache Miss 统计 在ARMv8/v9架构中,缓存未命中(Cache …

【wiki知识库】06.文档管理接口的实现--SpringBoot后端部分

目录 一、&#x1f525;今日目标 二、&#x1f388;SpringBoot部分类的添加 1.调用MybatisGenerator 2.添加DocSaveParam 3.添加DocQueryVo 三、&#x1f686;后端新增接口 3.1添加DocController 3.1.1 /all/{ebokId} 3.1.2 /doc/save 3.1.3 /doc/delete/{idStr} …