BGAPIのメモ

# Hello

## COMMAND
|Byte|数値|名前|意味|
|:--|:--|:--|:--|
| 0 | 0x00 | hilen | Message type: command |
| 1 | 0x00 | lolen | Minimum payload length |
| 2 | 0x00 | class | Message class: System | 
| 3 | 0x01 | method | Message ID |

COMMAND送信は、normal modeとpacket modeで変わってくる。packet modeの場合は、送信バイト数を1バイト目に記載する。

normal mode
> 0x00 0x00 0x00 0x01 

packet mode
> 0x04 0x00 0x00 0x00 0x01 

## RESPONSE
|Byte|数値|名前|意味|
|:--|:--|:--|:--|
| 0 | 0x00 | hilen | Message type: response |
| 1 | 0x00 | lolen | Minimum payload length |
| 2 | 0x00 | class | Message class: System |
| 3 | 0x01 | method | Message ID |

# Set Mode
[BLUEGIGA BLUETOOTH SMART SOFTWARE V.1.3 API DOCUMENTATION Wednesday, 28 May 2014 Version 3.2 (P101) ](http://mt-system.ru/sites/default/files/documents/bluetooth_smart_software_v13_api_reference.pdf)より

## Command

|Byte|数値|名前|意味|
|:--|:--|:--|:--|
| 0 | 0x00 | hilen | command |
| 1 | 0x02 | lolen | payload  length |
| 2 | 0x06 | class | Generic Access Profile |
| 3 | 0x01 | method |Message ID |
| 4 | uint8 | discover |GAP Discoverable Mode|
| 5 | uint8 | connect |GAP Connectable Mode |

|Value|Name|Description|
|:--|:--|:--|
| 0 | gap_non_discoverable | Non-discoverable mode: the LE Limited Discoverable Mode and the LE General Discoverable Mode bits are NOT set in the Flags AD type. A Master can still connect to the advertising Slave. |
| 1 | gap_limited_discoverable | Discoverable using limited scanning mode: the advertisement packets will carry the LE Limited Discoverable Mode bit set in the Flags AD type.|
| 2 | gap_general_discoverable | Discoverable using general scanning mode: the advertisement packets will carry the LE General Discoverable Mode bit set in the Flags AD type. |
| 3 | gap_broadcast  | Same as gap_non_discoverable above. |
| 4 | gap_user_data | Send advertisement data defined by user. User is responsible to build the advertising packet so to also contain the appropriate desired Flags AD type. |
| 0x80 | gap_enhanced_broadcasting | When turning the most highest bit on, the scanning devices are reported back to the application through Scan Response event. |

|Value|Name|Description|
|:--|:--|:--|
| 0 | gap_non_connectable | Not connectable |
| 1 | gap_directed_connectable | Direct Connectable |
| 2 | gap_undirected_connectable | Undirected connectable |
| 3 | gap_scannable_connectable | Same as undirected connectable, but uses ADV_SCAN_IND packets |

例)<br>
> [0x00, 0x02, 0x06, 0x01, 0x04, 0x00]

## Response
|Byte|数値|名前|意味|
|:--|:--|:--|:--|
| 0 | 0x00 | hilen | command |
| 1 | 0x02 | lolen | payload  length |
| 2 | 0x06 | class | Generic Access Profile |
| 3 | 0x01 | method |Message ID |
| 4-5| uint16 | result |

例)<br>
> [0x00, 0x02, 0x06, 0x01, 0x00, 0x00]


# Set Adv Data
[BLUEGIGA BLUETOOTH SMART SOFTWARE V.1.3 API DOCUMENTATION Wednesday, 28 May 2014 Version 3.2 (P95) ](http://mt-system.ru/sites/default/files/documents/bluetooth_smart_software_v13_api_reference.pdf)より

## Command
|Byte|数値|名前|意味|
|:--|:--|:--|:--|
| 0 | 0x00 | hilen | command |
| 1 | 0x02 | lolen | payload  length |
| 2 | 0x06 | class | Generic Access Profile |
| 3 | 0x09 | method |Message ID |
| 4 | uint8 |set_scanrsp |0 : sets advertisement data<br>1 : sets scan response data<br>|
| 5 | adv_data | adv_data |Advertisement data to send |

例)<br>
> [0x00, 0x02, 0x06, 0x09, 0x00, 0x02, 0x01, 0x06, 0x1A, 0xFF, 0x4C, 0x00, 0x02, 0x15, 0xCB, 0x86, 0xBC, 0x31, 0x05, 0xBD, 0x40, 0xCC, 0x90, 0x3D, 0x1C, 0x9B, 0xD1, 0x3D, 0x96, 0x6B, 0x00, 0x71, 0x00, 0x71, 0xC9]

## Response
|Byte|数値|名前|意味|
|:--|:--|:--|:--|
| 0 | 0x00 | hilen | command |
| 1 | 0x02 | lolen | payload  length |
| 2 | 0x06 | class | Generic Access Profile |
| 3 | 0x09 | method |Message ID |
| 4-5| uint16 | result |

例)<br>
> [0x00, 0x02, 0x06, 0x09, 0x00, 0x00]

https://bluegiga.zendesk.com/entries/22412436--REFERENCE-What-is-the-difference-between-BGScript-BGAPI-and-BGLib-

# Sample Code

```cpp:ArduinoSample

#include <SoftwareSerial.h>

SoftwareSerial bleShield(12, 13);

bool flag = false;

void setup() {
  // BLEとの通信用
  bleShield.begin(115200);
  // ログ出力用
  Serial.begin(9600);
  Serial.write("Adv start!");
}

void loop() {

  if(flag != true){
    bleShield.write((byte)0x00);
    bleShield.write((byte)0x02);
    bleShield.write((byte)0x06);
    bleShield.write((byte)0x01);
    bleShield.write((byte)0x04);
    bleShield.write((byte)0x00);
    delay(1000);
    byte value[6];
    int i = 0;
    while (bleShield.available()) {
      if(i<6){
        value[i] = bleShield.read();
       
        if( i == 5){
          if(value[0] == 0x00 && 
             value[1] == 0x02 &&
             value[2] == 0x06 &&
             value[3] == 0x01 &&
             value[4] == 0x00 && 
             value[5] == 0x00)
            {
                Serial.println("Command OK[1]");
                break;
            }
        }

        i++;
      }
    }

    bleShield.write((byte)0x00);
    bleShield.write((byte)0x02);
    bleShield.write((byte)0x06);
    bleShield.write((byte)0x09);
    bleShield.write((byte)0x00);
    bleShield.write((byte)0x02);
    bleShield.write((byte)0x01);
    bleShield.write((byte)0x06);
    bleShield.write((byte)0x1A);
    bleShield.write((byte)0xFF);
    bleShield.write((byte)0x4C);
    bleShield.write((byte)0x00);
    bleShield.write((byte)0x02);
    bleShield.write((byte)0x15);
    bleShield.write((byte)0xCB);
    bleShield.write((byte)0x86);
    bleShield.write((byte)0xBC);
    bleShield.write((byte)0x31);
    bleShield.write((byte)0x05);
    bleShield.write((byte)0xBD);
    bleShield.write((byte)0x40);
    bleShield.write((byte)0xCC);
    bleShield.write((byte)0x90);
    bleShield.write((byte)0x3D);
    bleShield.write((byte)0x1C);
    bleShield.write((byte)0x9B);
    bleShield.write((byte)0xD1);
    bleShield.write((byte)0x3D);
    bleShield.write((byte)0x96);
    bleShield.write((byte)0x6B);
    bleShield.write((byte)0x00);
    bleShield.write((byte)0x71);
    bleShield.write((byte)0x00);
    bleShield.write((byte)0x71);
    bleShield.write((byte)0xC9);
    delay(1000);
    
    i = 0;
    while (bleShield.available()) {
      if(i<6){
        value[i] = bleShield.read();
        
        if( i == 5){
          if(value[0] == 0x00 && 
             value[1] == 0x02 &&
             value[2] == 0x06 &&
             value[3] == 0x09 &&
             value[4] == 0x00 && 
             value[5] == 0x00)
            {
                Serial.println("Command OK[2]");
                break;
            }
        }

        i++;
      }
    }
    flag = true;
  }
}
```

# Error Code

## Event
|Byte|数値|名前|意味|
|:--|:--|:--|:--|
| 0 | 0x80 | hilen | Message type: event |
| 1 | 0x02 | lolen | Minimum payload length |
| 2 | 0x00 | class | Message class: System |
| 3 | 0x06 | method | Message ID |
| 4 - 5 | uint16 | reason Reason for failure |

> [0x80, 0x02, 0x00, 0x06, 0x84, 0x01]
0x0184 のエラーが発生している。
0x0184のエラーは、"Command Not Recognized"のエラー。

## BGScript Error

| 値 | Error名 | 意味 |
|:-:|:--|:--|
| 0x0180 |  Invalid Parameter | Command contained invalid parameter |
| 0x0181 | Device in Wrong State | Device is in wrong state to receive command |
| 0x0182 | Out Of Memory | Device has run out of memory |
| 0x0183 | Feature Not Implemented | Feature is not implemented |
| 0x0184 | Command Not Recognized  | Command was not recognized |
| 0x0185 | Timeout | Command or Procedure failed due to timeout |
| 0x0186 | Not Connected | Connection handle passed is to command is not a valid handle |
| 0x0187 | flow | Command would cause either underflow or overflow error |
| 0x0188 | User Attribute |User attribute was accessed through API which is not supported |
| 0x0189 | Invalid License Key | No valid license key found |
| 0x018A |Command Too Long | Command maximum length exceeded |
| 0x018B | Out of Bonds | Bonding procedure can't be started because device has no space left for bond. |

## Bluetooth Errors

| 値 | Error名 | 意味 |
|:-:|:--|:--|
| 0x0205 |Authentication Failure|Pairing or authentication failed due to incorrect results in the pairing or authentication procedure. This could be due to an incorrect PIN or Link Key |
| 0x0206 | Pin or Key Missing | Pairing failed because of missing PIN, or authentication failed because of missing Key. |
| 0x0207 | Memory Capacity Exceeded | Controller is out of memory. |
| 0x0208 | Connection Timeout | Link supervision timeout has expired. |
| 0x0209 | Connection Limit Exceeded | Controller is at limit of connections it can support. |
| 0x020C | Command Disallowed | Command requested cannot be executed because the Controller is in a state where it cannot process this command at this time. |
| 0x0212 | Invalid Command Parameters | Command contained invalid parameters. |
| 0x0213 | Remote User Terminated Connection | User on the remote device terminated the connection. |
| 0x0216 | Connection Terminated by Local Host | Local device terminated the connection. |
| 0x0222 | LL Response Timeout | Connection terminated due to link-layer procedure timeout. |
| 0x0228 | LL Instant Passed | Received link-layer control packet where instant was in the past. |
|  0x023A | Controller Busy  | Operation was rejected because the controller is busy and unable to process the request. |
| 0x023B | Unacceptable Connection Interval | The Unacceptable Connection Interval error code indicates that the remote device terminated the connection because of an unacceptable connection interval. |
|0x023C|Directed Advertising Timeout | Directed advertising completed without a connection being created. |
|0x023D|MIC Failure | Connection was terminated because the Message Integrity Check (MIC) failed on a received packet.|
|0x023E| Connection Failed to be Established | LL initiated a connection but the connection has failed to be established. Controller did not receive any packets from remote end. |

## Security Manager Protocol Errors

| 値 | Error名 | 意味 |
|:-:|:--|:--|
| 0x0301 | Passkey Entry Failed |The user input of passkey failed, for example, the user cancelled the operation |
| 0x0302 |  OOB Data is not available | Out of Band data is not available for authentication |
| 0x0303 | Authentication Requirements | The pairing procedure cannot be performed as authentication requirements cannot be met due to IO capabilities of one or both devices |
| 0x0304 |  Confirm Value Failed | The confirm value does not match the calculated compare value |
| 0x0305 |  Pairing Not Supported | Pairing is not supported by the device |
| 0x0306 | Encryption Key Size | The resultant encryption key size is insufficient for the security requirements of this device |
| 0x0307 | Command Not Supported | The SMP command received is not supported on this device |
|0x0308 | Unspecified Reason | Pairing failed due to an unspecified reason|
|0x0309| Repeated Attempts | Pairing or authentication procedure is disallowed because too little time has elapsed since last pairing request or security request |
| 0x030A | Invalid Parameters | The Invalid Parameters error code indicates: the command length is invalid or a parameter is outside of the specified range. |

## Attribute Protocol Errors

| 値 | Error名 | 意味 |
|:-:|:--|:--|
|0x0401|Invalid Handle|The attribute handle given was not valid on this server|
|0x0402|Read Not Permitted |The attribute cannot be read|
|0x0403|Write Not Permitted|The attribute cannot be written|
|0x0404|Invalid PDU |The attribute PDU was invalid|
|0x0405|Insufficient Authentication |The attribute requires authentication before it can be read or written.|
|0x0406|Request Not Supported |Attribute Server does not support the request received from the client.|
|0x0407 |Invalid Offset |Offset specified was past the end of the attribute|
|0x0408 |Insufficient Authorization |The attribute requires authorization before it can be read or written.|
|0x0409|Prepare Queue Full |Too many prepare writes have been queueud|
|0x040A|Attribute Not Found |No attribute found within the given attribute handle range.|
|0x040B|Attribute Not Long |The attribute cannot be read or written using the Read Blob Request|
|0x040C|Insufficient Encryption Key Size |The Encryption Key Size used for encrypting this link is insufficient.|
|0x040D|Invalid Attribute Value Length |The attribute value length is invalid for the operation|
|0x040E|Unlikely Error |The attribute request that was requested has encountered an error that was unlikely, and therefore could not be completed as requested.|
|0x040F|Insufficient Encryption |The attribute requires encryption before it can be read or written.|
|0x0410|Unsupported Group Type |The attribute type is not a supported grouping attribute as defined by a higher layer specification.|
|0x0411|Insufficient Resources |Insufficient Resources to complete the request |
|0x0480|Application Error Codes |Application error code defined by a higher layer specification.|