InfraredLibに対応したMSC

Dependencies:   BLE_API RemoteIR mbed nRF51822

Fork of nRF51822_SimpleChat by RedBearLab

main.cpp

Committer:
ke_ix1
Date:
2017-02-12
Revision:
7:66243b10532c
Parent:
6:976503121a46

File content as of revision 7:66243b10532c:

/*

Copyright (c) 2012-2014 RedBearLab

Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
and associated documentation files (the "Software"), to deal in the Software without restriction, 
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

/*
 *    The application works with the BLEController iOS/Android App.
 *    Type something from the Terminal to send
 *    to the BLEController App or vice verse.
 *    Characteristics received from App will print on Terminal.
 */
 
#include "mbed.h"
#include "ble/BLE.h"
#include <string.h>
#include "ReceiverIR.h"
#include "TransmitterIR.h"

//#include <stdio.h>


#define BLE_UUID_TXRX_SERVICE            0x0000 /**< The UUID of the Nordic UART Service. */
#define BLE_UUID_TX_CHARACTERISTIC       0x0002 /**< The UUID of the TX Characteristic. */
#define BLE_UUIDS_RX_CHARACTERISTIC      0x0003 /**< The UUID of the RX Characteristic. */

#define TXRX_BUF_LEN                     20

BLE  ble;

Serial pc(USBTX, USBRX);
Ticker steper;
DigitalOut led1(P0_17);
DigitalOut ledori1(LED1);
//DigitalOut ledori2(LED2);

//ReceiverIR ir_rx(P0_25); //nRF51
//ReceiverIR ir_rx(P0_4); //Nano できんかった
ReceiverIR ir_rx(P0_2); //51822 nrf51

TransmitterIR ir_tx(P0_18);

//ReceiverIR ir_rx(P0_25);


// TX POWER用
#include "ble_gap.h"
#define TX_POWER                         0
//機器設定
//#define TX_ZERO                         
//#define TX_POWER_CALI                    -10
//const static char     DEVICE_NAME[]        = "nRF51DK"; // change this

//#define TX_POWER_CALI                      -7
//const static char     DEVICE_NAME[]        = "51822"; // change this

//#define TX_POWER_CALI                    -15
//const static char     DEVICE_NAME[]        = "Nano"; // change this

#define TX_POWER_CALI                      -7
const static char     DEVICE_NAME[]        = "MN6"; // change this

// The Nordic UART Service
static const uint8_t uart_base_uuid[] = {0x71, 0x3D, 0, 0, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
static const uint8_t uart_tx_uuid[]   = {0x71, 0x3D, 0, 3, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
static const uint8_t uart_rx_uuid[]   = {0x71, 0x3D, 0, 2, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
static const uint8_t uart_base_uuid_rev[] = {0x1E, 0x94, 0x8D, 0xF1, 0x48, 0x31, 0x94, 0xBA, 0x75, 0x4C, 0x3E, 0x50, 0, 0, 0x3D, 0x71};



// MSC UUID
static const uint8_t msc_uuid[]   = {0x71, 0x3D, 0, 6, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E}; //central_TxPower受信用
uint8_t mscPayload[TXRX_BUF_LEN] = {0,};
static uint8_t msc_buf[TXRX_BUF_LEN];
static uint8_t msc_len=0;
GattCharacteristic  mscCharacteristic (msc_uuid, mscPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ); //tx power characteristic

// TX POWER用
static const uint8_t power_level_uuid[]   = {0x71, 0x3D, 0, 4, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E}; //central_TxPower受信用
uint8_t powerPayload[TXRX_BUF_LEN] = {0,};
static uint8_t power_buf[TXRX_BUF_LEN];
static uint8_t power_len=0;
GattCharacteristic  txPowerCharacteristic (power_level_uuid, powerPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ); //tx power characteristic
Ticker txSteper;

//Feature UUID
static const uint8_t feature_uuid[]   = {0x71, 0x3D, 0, 5, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E}; //central_TxPower受信用
uint8_t featurePayload[TXRX_BUF_LEN] = {0,};
static uint8_t feature_buf[TXRX_BUF_LEN];
static uint8_t feature_len=0;
GattCharacteristic  featureCharacteristic (feature_uuid, featurePayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ); //tx power characteristic






uint8_t txPayload[TXRX_BUF_LEN] = {0,};
uint8_t rxPayload[TXRX_BUF_LEN] = {0,};

static uint8_t rx_buf[TXRX_BUF_LEN];
static uint8_t rx_len=0;
static uint8_t rx_buf_st[20];

int8_t buf_before[40];

static int st = 0;

int flagMargine = -1;
int receivedFlag = 0;

GattCharacteristic  txCharacteristic (uart_tx_uuid, txPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);
                                      
GattCharacteristic  rxCharacteristic (uart_rx_uuid, rxPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ);

GattCharacteristic *uartChars[] = {&txCharacteristic, &rxCharacteristic, &txPowerCharacteristic, &mscCharacteristic, &featureCharacteristic};

GattService         uartService(uart_base_uuid, uartChars, sizeof(uartChars) / sizeof(GattCharacteristic *));





// TX POWER用
void txPowerUpdate(int newTxPower) {
    sd_ble_gap_tx_power_set(newTxPower);
    //ここから-------------
    char bufbuf_c[20];
    uint8_t bufbuf[40];
    sprintf(bufbuf_c, "%d", newTxPower + TX_POWER_CALI);
    int a;
    for(a=0; bufbuf_c[a] != '\0'; a++) {
        bufbuf[a] = bufbuf_c[a];
    }
    ble.updateCharacteristicValue(txPowerCharacteristic.getValueAttribute().getHandle(), bufbuf, a);
    //ここまで-------------
    //をこぴればデータを送信可能
}


// MSC UUID
void initMsc() {
    //ここから-------------
    char bufbuf_c[20];
    uint8_t bufbuf[40];
    sprintf(bufbuf_c, "%s", "00000003");
    //sprintf(bufbuf_c, "%d", "02f3f538-8d11-4802-b6fc-fb6616d4cd70");
    int a;
    for(a=0; bufbuf_c[a] != '\0'; a++) {
        bufbuf[a] = bufbuf_c[a];
    }
    ble.updateCharacteristicValue(mscCharacteristic.getValueAttribute().getHandle(), bufbuf, a);
    //ここまで-------------
    //をこぴればデータを送信可能
}


// Feature
void initFeature() {
    //ここから-------------
    char bufbuf_c[20];
    uint8_t bufbuf[40];
    sprintf(bufbuf_c, "%s", "In.Sensor.Infrared");
    int a;
    for(a=0; bufbuf_c[a] != '\0'; a++) {
        bufbuf[a] = bufbuf_c[a];
    }
    ble.updateCharacteristicValue(featureCharacteristic.getValueAttribute().getHandle(), bufbuf, a);
    //ここまで-------------
    //をこぴればデータを送信可能
}


void txStep() {
    //ここから-------------
    //sd_ble_gap_tx_power_set(TX_POWER);
    char bufbuf_c[20];
    uint8_t bufbuf[40];
    sprintf(bufbuf_c, "%d", TX_POWER + TX_POWER_CALI);
    int a;
    for(a=0; bufbuf_c[a] != '\0'; a++) {
        bufbuf[a] = bufbuf_c[a];
    }
    ble.updateCharacteristicValue(txPowerCharacteristic.getValueAttribute().getHandle(), bufbuf, a);
}


void initChara() {
    initMsc();
    initFeature();
    txStep();
}

//-------------------




void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason)
{
    pc.printf("Disconnected \r\n");
    pc.printf("Restart advertising \r\n");
    ble.startAdvertising();
}


void onScanCallback(const Gap::AdvertisementCallbackParams_t *params)
{
    //printf("onScanNau\n");
  
//    printf("adv peerAddr[%d %d %d %d %d %d] rssi %d, isScanResponse %u, AdvertisementType %u\r\n",

//だいじ
/* 
    printf("adv peerAddr[%02x %02x %02x %02x %02x %02x] rssi %d, isScanResponse %u, AdvertisementType %u\r\n",
           params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],
           params->rssi, params->isScanResponse, params->type);
    printf("\n");
    printf("Len:%d\n",params->advertisingDataLen);
    printf("Data:");
  for (int i=0; i< params->advertisingDataLen; i++){
    printf("%02x,",params->advertisingData[i]);
  }
  */
  
 // for (int i=0; i<params->advertisingDataLen; i++){
 //   printf("%02x,",params->advertisingData[i]);
 // }
  
    printf("\n");
    
//   DEBUG(" \n\r");
//#endif
    
    
}


void WrittenHandler(const GattWriteCallbackParams *Handler)
{   
    uint8_t buf[TXRX_BUF_LEN];
    uint16_t bytesRead, index;
    
    if (Handler->handle == txCharacteristic.getValueAttribute().getHandle()) 
    {
        ble.readCharacteristicValue(txCharacteristic.getValueAttribute().getHandle(), buf, &bytesRead);
        memset(txPayload, 0, TXRX_BUF_LEN);
        memcpy(txPayload, buf, TXRX_BUF_LEN);
        pc.printf("WriteHandler \r\n");
        pc.printf("Length: ");
        pc.putc(bytesRead);
        pc.printf("\r\n");
        pc.printf("Data: ");
        for(index=0; index<bytesRead; index++)
        {
            pc.putc(txPayload[index]);        
        }
        pc.printf("\r\n");
    }
}

void uartCB(void)
{   
    while(pc.readable())    
    {
        rx_buf[rx_len++] = pc.getc();
        if(rx_len>=20 || rx_buf[rx_len-1]=='\0' || rx_buf[rx_len-1]=='\n')
        {
            ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), rx_buf, rx_len); 
            pc.printf("RecHandler \r\n");
            pc.printf("Length: ");
            pc.putc(rx_len);
            pc.printf("\r\n");
            rx_len = 0;
            break;
        }
    }
}


// 1++していく
void step() {
    ++st;
    //ここから-------------
    char bufbuf_c[20];
    uint8_t bufbuf[40];
    sprintf(bufbuf_c, "%d", st);
    
    int a;
    for(a=0; bufbuf_c[a] != '\0'; a++) {
        bufbuf[a] = bufbuf_c[a];
    }
    
//    ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), rx_buf, rx_len); 
    ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), bufbuf, a); 
    //ここまで-------------
    //をこぴればデータを送信可能
    
    //pc.printf("%d", st);
    //pc.printf("step! \r\n");
}

void flagSet() {
        //ここから-------------
    char bufbuf_c[20];
    uint8_t bufbuf[40];
    sprintf(bufbuf_c, "%d", receivedFlag);
    led1 = receivedFlag;
    //ledori2 = led1;
    int a;
    for(a=0; bufbuf_c[a] != '\0'; a++) {
        bufbuf[a] = bufbuf_c[a];
    }
    
//    ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), rx_buf, rx_len); 
    ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), bufbuf, a); 
    //ここまで-------------
    //をこぴればデータを送信可能
}



/**
 * Receive.
 *
 * @param format Pointer to a format.
 * @param buf Pointer to a buffer.
 * @param bufsiz Size of the buffer.
 *
 * @return Bit length of the received data.
 */
int receive(RemoteIR::Format *format, uint8_t *buf, int bufsiz, int timeout = 100) {
    int cnt = 0;
//    while (ir_rx.getState() != ReceiverIR::Received) {
    if (ir_rx.getState() != ReceiverIR::Received) {
        //pc.printf("no receive \r\n");
            return -1;
    }
    return ir_rx.getData(format, buf, bufsiz * 8);
}

/**
 * Transmit.
 *
 * @param format Format.
 * @param buf Pointer to a buffer.
 * @param bitlength Bit length of the data.
 *
 * @return Bit length of the received data.
 */
int transmit(RemoteIR::Format format, uint8_t *buf, int bitlength, int timeout = 100) {
    int cnt = 0;
    while (ir_tx.getState() != TransmitterIR::Idle) {
        cnt++;
        if (timeout < cnt) {
            return -1;
        }
    }
    return ir_tx.setData(format, buf, bitlength);
}

/**
 * Display a data.
 *
 * @param buf Pointer to a buffer.
 * @param bitlength Bit length of a data.
 */
void display_data(uint8_t *buf, int bitlength) {
    //lcd.locate(0, 1);
    const int n = bitlength / 8 + (((bitlength % 8) != 0) ? 1 : 0);
    for (int i = 0; i < n; i++) {
      
      pc.printf("%02X", buf[i]);
    }
    for (int i = 0; i < 8 - n; i++) {
      pc.printf("--");
    }
}

/**
 * Display a current status.
 */
void display_status(char *status, int bitlength) {
    //lcd.locate(8, 0);
    pc.printf("%-5.5s:%02d", status, bitlength);
}

/**
 * Display a format of a data.
 */
void display_format(RemoteIR::Format format) {
    //lcd.locate(0, 0);
    switch (format) {
        case RemoteIR::UNKNOWN:
            pc.printf("????????");
            break;
        case RemoteIR::NEC:
            pc.printf("NEC     ");
            break;
        case RemoteIR::NEC_REPEAT:
            pc.printf("NEC  (R)");
            break;
        case RemoteIR::AEHA:
            pc.printf("AEHA    ");
            break;
        case RemoteIR::AEHA_REPEAT:
            pc.printf("AEHA (R)");
            break;
        case RemoteIR::SONY:
            pc.printf("SONY    ");
            break;
    }
}



int main(void)
{
    ledori1 = 0;
    //ledori2 = 0;
    led1 = 0;
    ble.init();
    ble.onDisconnection(disconnectionCallback);
    ble.onDataWritten(WrittenHandler);  
   
    pc.baud(9600);
    pc.printf("SimpleChat Init \r\n");
    
    pc.attach( uartCB , pc.RxIrq);
   // setup advertising 
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
                                    (const uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME) - 1);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
                                    (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid));
    // 100ms; in multiples of 0.625ms. 
    ble.setAdvertisingInterval(160);

    ble.addService(uartService);
    
    ble.setScanParams(GapScanningParams::SCAN_INTERVAL_MIN,
                      GapScanningParams::SCAN_WINDOW_MIN,
                      0);

    ble.startScan(&onScanCallback);
    
    ble.startAdvertising(); 
    pc.printf("Advertising Start \r\n");
    
    steper.attach(&flagSet, 0.5);
    
        //TX POWER用
    //txSteper.attach(&initChara, 3.0);
    txPowerUpdate(TX_POWER);
   
   initChara();
    while(1)
    {
        //pc.printf("-------- \r\n");
        ble.waitForEvent();
        
        uint8_t buf1[32];
        int bitlength1;
        RemoteIR::Format format;

        //memset(buf1, 0x00, sizeof(buf1));

        {
            bitlength1 = receive(&format, buf1, sizeof(buf1));
            if (bitlength1 < 0) {
                if(flagMargine <= 0) {
                    receivedFlag = 0;
                } else {
                    flagMargine--;
                }
                
                if(flagMargine < -1000) {
                    flagMargine = -1;
                }
                continue;
            }
            /*
            pc.printf("receive ok! \r\n");
            display_status("RECV", bitlength1);
            display_data(buf1, bitlength1);
            display_format(format);
            */
            receivedFlag = 1;
            flagMargine = 30000;
        }
    }
}