我有一个 SWIFT 应用程序,它必须使用蓝牙低功耗模块向我的 Arduino 发送一个值!
我已正确完成搜索和连接部分,但我无法发送和接收任何数据。
这是我的代码,用于获取可用的 BLE 设备列表并将所有这些放在表格 View 中,然后在单击一个单元格后,应用程序提供将设备与它们连接!
所有这一切都很完美,但我不知道从应用程序发送一个“a”字符到 BLE,然后从 arduino 向应用程序取回答案!
import UIKit
import CoreBluetooth
class BluetoothList: UITableViewController,CBCentralManagerDelegate, CBPeripheralDelegate {
var listValue = [Lista]()
var Blue: CBCentralManager!
var conn: CBPeripheral!
var a: String!
var char: CBCharacteristic!
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
if (peripheral.name == a){
self.conn = peripheral
self.conn.delegate = self
Blue.stopScan()
Blue.connectPeripheral(self.conn, options: nil)
self.performSegueWithIdentifier("ConnectionSegue", sender: nil)
}
else{
listValue = [
Lista(Name: peripheral.name!, RSS: RSSI.stringValue)
]
self.tableView.reloadData()
}
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices(nil)
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
if let servicePeripheral = peripheral.services! as [CBService]!{
for service in servicePeripheral{
peripheral.discoverCharacteristics(nil, forService: service)
}
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
if let characterArray = service.characteristics! as [CBCharacteristic]!{
for cc in characterArray {
if(cc.UUID.UUIDString == "FF05"){
print("OKOK")
peripheral.readValueForCharacteristic(cc)
}
}
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if (characteristic.UUID.UUIDString == "FF05"){
let value = UnsafePointer<Int>((characteristic.value?.bytes.memory)!)
print("\(value)")
}
}
func centralManagerDidUpdateState(central: CBCentralManager){
switch(central.state){
case .PoweredOn:
Blue.scanForPeripheralsWithServices(nil, options:nil)
print("Bluetooth is powered ON")
case .PoweredOff:
print("Bluetooth is powered OFF")
case .Resetting:
print("Bluetooth is resetting")
case .Unauthorized:
print("Bluetooth is unauthorized")
case .Unknown:
print("Bluetooth is unknown")
case .Unsupported:
print("Bluetooth is not supported")
}
}
override func viewDidLoad() {
super.viewDidLoad()
Blue = CBCentralManager(delegate: self, queue: nil)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currentCell = tableView.cellForRowAtIndexPath(tableView.indexPathForSelectedRow!)! as UITableViewCell
a = currentCell.textLabel?.text
Blue = CBCentralManager(delegate: self, queue: nil)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
@IBAction func Reload_BTN(sender: AnyObject) {
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.listValue.count
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cella = self.tableView.dequeueReusableCellWithIdentifier("Cella", forIndexPath: indexPath)
let Lista = self.listValue[indexPath.row]
cella.textLabel?.text = Lista.Name
cella.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cella
}
最佳答案
以下代码适用于 Swift 3 (XCode 8 Beta 6)。这是一个将标准 UUID 用于串行端口的示例,例如某些商业模块上的串行端口。所以服务和特性的声明应该是这样的:
private let UuidSerialService = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
private let UuidTx = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
private let UuidRx = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
然后您的委托(delegate)的 didDiscoverCharacteristic 方法可以是这样的:
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?)
{
if let characteristics = service.characteristics {
for characteristic in characteristics {
// Tx:
if characteristic.uuid == CBUUID(string: UuidTx) {
print("Tx char found: \(characteristic.uuid)")
txCharacteristic = characteristic
}
// Rx:
if characteristic.uuid == CBUUID(string: UuidRx) {
rxCharacteristic = characteristic
if let rxCharacteristic = rxCharacteristic {
print("Rx char found: \(characteristic.uuid)")
serialPortPeripheral?.setNotifyValue(true, for: rxCharacteristic)
}
}
}
}
}
对于写入 Tx,类似下面的工作,其中值是 [UInt8]:
let data = NSData(bytes: value, length: value.count)
serialPortPeripheral?.writeValue(data as Data, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse)
阅读?
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let rxData = characteristic.value
if let rxData = rxData {
let numberOfBytes = rxData.count
var rxByteArray = [UInt8](repeating: 0, count: numberOfBytes)
(rxData as NSData).getBytes(&rxByteArray, length: numberOfBytes)
print(rxByteArray)
}
}
最后,如果您不知道或不确定您的 BLE 设备的服务和特性,您可以寻找一款名为“LightBlue”的免费 iOS 应用程序。它会发现一个设备,如果您连接到它,它会列出所有服务和特征。请注意,当 LightBlue 连接到您的设备时,您的应用显然无法访问 BLE 硬件。
关于ios - SWIFT - BLE 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35794107/
我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
MIMO技术的优缺点优点通过下面三个增益来总体概括:阵列增益。阵列增益是指由于接收机通过对接收信号的相干合并而活得的平均SNR的提高。在发射机不知道信道信息的情况下,MIMO系统可以获得的阵列增益与接收天线数成正比复用增益。在采用空间复用方案的MIMO系统中,可以获得复用增益,即信道容量成倍增加。信道容量的增加与min(Nt,Nr)成正比分集增益。在采用空间分集方案的MIMO系统中,可以获得分集增益,即可靠性性能的改善。分集增益用独立衰落支路数来描述,即分集指数。在使用了空时编码的MIMO系统中,由于接收天线或发射天线之间的间距较远,可认为它们各自的大尺度衰落是相互独立的,因此分布式MIMO
print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上
当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#
当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab
我需要将目录中的一堆文件上传到S3。由于上传所需的90%以上的时间都花在了等待http请求完成上,所以我想以某种方式同时执行其中的几个。Fibers能帮我解决这个问题吗?它们被描述为解决此类问题的一种方法,但我想不出在http调用阻塞时我可以做任何工作的任何方法。有什么方法可以在没有线程的情况下解决这个问题? 最佳答案 我没有使用1.9中的纤程,但是1.8.6中的常规线程可以解决这个问题。尝试使用队列http://ruby-doc.org/stdlib/libdoc/thread/rdoc/classes/Queue.html查看文
在ruby中...我有一个由外部进程创建的IO对象,我需要从中获取文件名。然而我似乎只能得到文件描述符(3),这对我来说不是很有用。有没有办法从此对象获取文件名甚至获取文件对象?我正在从通知程序中获取IO对象。所以这也可能是获取文件路径的一种方式? 最佳答案 关于howtogetathefilenameinC也有类似的问题,我将在这里以ruby的方式给出这个问题的答案。在Linux中获取文件名假设io是您的IO对象。以下代码为您提供了文件名。File.readlink("/proc/self/fd/#{io.fileno}")例