runeleaf
8/27/2012 - 6:03 AM

BluetoothController

BluetoothController

#coding: utf-8
class BluetoothController < UIViewController
  attr_accessor :session, :peer_id, :peers, :state, :text_field

  def viewDidLoad
    self.title = 'bluetooth test'
    self.view.backgroundColor = "#FFFFFF".to_color
    screen = UIScreen.mainScreen.bounds

    self.text_field = UITextField.alloc.initWithFrame [[0, 30], [200, 26]]
    self.text_field.placeholder = "aaa"
    self.text_field.returnKeyType = UIReturnKeyDone
    #self.text_field.textAlignment = UITextAlignmentCenter
    self.text_field.borderStyle = UITextBorderStyleRoundedRect
    self.text_field.autocapitalizationType = UITextAutocapitalizationTypeNone
    #self.text_field.center = CGPointMake(self.view.frame.size.width / 2, 30)
    self.text_field.delegate = self
    self.view.addSubview self.text_field

    #TODO: これをUITableとかにして出したい
    self.state = UILabel.alloc.initWithFrame [[0, 0], [300, 50]]
    self.state.font = UIFont.systemFontOfSize(30)
    self.state.text = 'abcd'
    self.state.textAlignment = UITextAlignmentCenter
    self.state.center = CGPointMake(self.view.frame.size.width / 2, 200)
    self.state.textColor = "#666666".to_color
    self.view.addSubview self.state

    @btn_connect = UIButton.buttonWithType(UIButtonTypeRoundedRect)
    @btn_connect.setTitle("Connect", forState:UIControlStateNormal)
    @btn_connect.setTitle("Wait", forState:UIControlStateDisabled)
    @btn_connect.frame = [[0, self.text_field.center.y + 26], [26, 26]]
    @btn_connect.sizeToFit
    #@btn_connect.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2)
    #@btn_connect.center = CGPointMake(self.view.frame.size.width / 2, self.state.center.y + 80)
    self.view.addSubview @btn_connect

    @btn_say = UIButton.buttonWithType(UIButtonTypeRoundedRect)
    @btn_say.setTitle("Say", forState:UIControlStateNormal)
    @btn_say.setTitle("...", forState:UIControlStateDisabled)
    @btn_say.frame = [[@btn_connect.bounds.size.width + 10, self.text_field.center.y + 26], [26, 26]]
    @btn_say.sizeToFit
    #@btn_say.center = CGPointMake(self.view.frame.size.width / 2, self.text_field.center.y + 60)
    self.view.addSubview @btn_say

    @btn_connect.when(UIControlEventTouchUpInside) do
      connect
    end

    @btn_say.when(UIControlEventTouchUpInside) do
      sendText
    end

    self.session = GKSession.alloc.initWithSessionID("connectest", displayName:nil, sessionMode:GKSessionModePeer)
    self.session.delegate = self
    self.session.setDataReceiveHandler(self, withContext:nil)
    self.session.available = true

    connect
  end

  def connect
    picker = GKPeerPickerController.alloc.init
    picker.delegate = self
    #TODO: wifi GKPeerPickerConnectionTypeOnline
    picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby
    picker.show
  end

  # コネクションタイプ
  def peerPickerController(picker, didSelectConnectionType:type)
    if type == GKPeerPickerConnectionTypeOnline
      picker.delegate = nil
      self.session = GKSession.alloc.initWithSessionID(nil, displayName:nil)
      self.session.delegate = self
      self.session.available = true
      self.session.setDataReceiveHandler(self, withContext:nil)
    end
    self.session
  end

  # picker
  def peerPickerController(picker, didConnectPeer:peer_id, toSession:session)
    self.peer_id = peer_id
    self.session = session
    session.delegate = self
    session.setDataReceiveHandler(self, withContext:nil)
    picker.delegate = nil
    picker.dismiss
  end

  # 接続キャンセル時の処理
  def peerPickerControllerDidCancel(picker)
    picker.delegate = nil
  end

  # データを送る 送信
  def sendText
    if self.session.nil?
      p 'no session'
      return nil
    end

    data = self.text_field.text.dataUsingEncoding(NSUTF8StringEncoding)
    error = nil
    self.session.sendDataToAllPeers(data, withDataMode:GKSendDataReliable, error:error)
    if error
      p 'error sendText'
      p error
    end

    self.state.text = self.text_field.text #data
    self.text_field.text = ""
  end

  # データを受ける 受信
  def receiveData(data, fromPeer:peer, inSession:session, context:context)
    str = NSString.alloc.initWithData(data, encoding:NSUTF8StringEncoding)
    self.state.text = str
  end

  # 相手を見つけたり接続状態が変わった居留守時に呼ばれるデリゲート
  def session(session, peer:peer_id, didChangeState:state)
    case state
    when GKPeerStateAvailable
      # peer_idを見つけたのでpeer_idを接続しに行く
      str = 'peer available'
      self.session.connectToPeer(peer_id, withTimeout:10.0)
    when GKPeerStateUnavailable
      # 見失った
      str = 'peer unavailable'
    when GKPeerStateConnected
      # peer_idが接続した。peer_idにメッセージを送った
      str = 'peer connected'
      self.peer_id = peer_id
    when GKPeerStateDisconnected
      # 切断された
      str = 'peer disconnected'
    when GKPeerStateConnecting
      # 接続中
      str = 'peer connecting'
    end
    self.state.text = str
  end

  # 接続要求で呼ばれるデリゲート。無条件
  def session(session, didReceiveConnectionRequestFromPeer:peer_id)
    session.acceptConnectionFromPeer(peer_id, error:nil)
  end

  def session(session, connectionWithPeerFailed:peer_id, withError:error)
    p 'error 2'
  end

  def session(session, didFailWithError:error)
    p 'error 3'
  end

  # doneでキーボード閉じる
  def textFieldShouldReturn(text_field)
    text_field.resignFirstResponder
    true
  end
end