<commit_before>/*
Copyright © 2015 NoTalentHack, LLC

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.
*/

#include "common.h"
#include "cJSON/cJSON.h"

uint8_t channel = 22;

#ifdef _DEBUG
#define DEBUG 1
#else
#define DEBUG 0
#endif

#define DEBUG 1

// commands between Client and Server. Server is on Edison side and
// client is on the phone side
#define SERIAL_CMD_START       1
#define SERIAL_CMD_STATUS      2
#define SERIAL_CMD_ERROR       3
#define SERIAL_CMD_KILL        4 
#define SERIAL_CMD_STOP        5
#define SERIAL_CMD_CPU_INFO    6
#define SERIAL_CMD_CLOSE       0xFF 

const char *KEY_COMMAND_TYPE   = "command_type";
const char *KEY_COMMAND        = "command";
const char *KEY_CAPTURE_OUTPUT = "capture_output";
const char *KEY_IDENTIFIER     = "identifier";
const char *KEY_PERCENT        = "percent";
const char *KEY_TOAST          = "toast";
const char *KEY_FREQUENCY      = "frequency";
const char *KEY_CPU_CORES      = "cpu_cores";
const char *KEY_CPU_FAMILY     = "cpu_family";
const char *KEY_STEPPING       = "stepping";
const char *KEY_MODEL          = "model";
const char *KEY_CACHE_SIZE     = "cache_size";
const char *KEY_MODEL_NAME     = "model_name";
const char *KEY_VENDOR_ID      = "vendor_id";

/* Protocol between client and server
 *     byte 1 = command 
 *     byte 2-n = command line except for close which is empy
 */

// strip out all arguments                                        
void strip_argv(char *buffer) {                                   
    char *ptr;                                                    
    int slen;                                                     
                                                                  
    ptr = strchr(buffer, ' ');  // space is where arguments starts
    if (ptr != '\0') {                                            
        slen = (int)(ptr - buffer);                                   
        if (slen > 0) {                                               
            buffer[slen] = '\0';                                      
        }                                                             
        printf("buf = %s\n", buffer);                                 
    }                                                             
} 

void returnCpuInfo(int client) {
    struct cpuInfo cpuinfo;
    getCpuInfo(&cpuinfo); 

    // build cpu info data
    cJSON *json = cJSON_CreateObject();
    cJSON_AddNumberToObject(json, KEY_COMMAND_TYPE, SERIAL_CMD_CPU_INFO);
    cJSON_AddNumberToObject(json, KEY_FREQUENCY, cpuinfo.frequency);
    cJSON_AddNumberToObject(json, KEY_CPU_CORES, cpuinfo.cpu_cores);
    cJSON_AddNumberToObject(json, KEY_CPU_FAMILY, cpuinfo.cpu_family);
    cJSON_AddNumberToObject(json, KEY_STEPPING, cpuinfo.stepping);
    cJSON_AddNumberToObject(json, KEY_MODEL, cpuinfo.model);
    cJSON_AddStringToObject(json, KEY_CACHE_SIZE, cpuinfo.cache_size);
    cJSON_AddStringToObject(json, KEY_MODEL_NAME, cpuinfo.model_name);
    cJSON_AddStringToObject(json, KEY_VENDOR_ID, cpuinfo.vendor_id);
        
    char *out = cJSON_Print(json, 0);
    int slen = strlen(out);
    int bytes_wrote = write(client, out, slen);              
    if (bytes_wrote <= 0 || bytes_wrote != slen) {       
        // Use system log?                                 
        fprintf(stderr, "Can't write to client\n");        
    }                                                      
    free(out);
    cJSON_Delete(json);
}

// return unknown command error message
void returnMessage(int client, int msgType,  char *format, char *str) {
    char error[256] = { 0 };
    sprintf(error, format, str);

    // build status data
    cJSON *json = cJSON_CreateObject();
    cJSON_AddNumberToObject(json, KEY_COMMAND_TYPE, msgType);
    cJSON_AddStringToObject(json, KEY_TOAST, error);
        
    char *out = cJSON_Print(json, 0);
    int slen = strlen(out);
    int bytes_wrote = write(client, out, slen);              
    if (bytes_wrote <= 0 || bytes_wrote != slen) {       
        // Use system log?                                 
        fprintf(stderr, "Can't write to client\n");        
    }                                                      
    free(out);
    cJSON_Delete(json);
} 

// return last known error message
void returnError(int client) {
    char error[BUFSIZE] = { 0 };
    get_lasterror(error);                         
    returnMessage(client, SERIAL_CMD_ERROR, "%s", error);
}

void returnUnknown(int client, char *format, char *str) {
    returnMessage(client, SERIAL_CMD_ERROR, format, str);
}

// argv that is needed to pass into returnCpuUsage function as part of
// pthread_create function
struct argvCpuInfo {
    int client;
    int identifier;
    pid_t pid;
}; 

// Function to return cpu usage and other info about process
void* returnCpuUsage(void *arg)                                                                                                
{                                                                                                                        
    struct pstat prev, curr;                                                                                             
    double pct;                                                                                                          
    struct argvCpuInfo *argv = (struct argvCpuInfo *)arg; 
    
    while( 1 )                                                                                                           
    {                                                                                                                    
        if( get_usage(argv->pid, &prev) == -1 ) {                                                                              
            printf( "error\n" );                                                                                         
        }                                                                                                                
                                                                                                                         
        sleep( 2 );                                                                                                      
                                                                                                                         
        if( get_usage(argv->pid, &curr) == -1 ) {                                                                              
            printf( "error\n" );                                                                                         
        }                                                                                                                
                                                                                                                         
        calc_cpu_usage_pct(&curr, &prev, &pct);                                                                          
       
        // build status data
        cJSON *json = cJSON_CreateObject();
        cJSON_AddNumberToObject(json, KEY_COMMAND_TYPE, SERIAL_CMD_STATUS);
        cJSON_AddNumberToObject(json, KEY_IDENTIFIER, argv->identifier);
        cJSON_AddNumberToObject(json, KEY_PERCENT, pct);
        
        int slen = strlen(json->string);
        int bytes_wrote = write(argv->client, json->string, slen);              
        if (bytes_wrote <= 0 || bytes_wrote != slen) {       
           // Use system log?                                 
           fprintf(stderr, "Can't write to client\n");        
        }                                                      
        cJSON_Delete(json);
        printf("%%cpu: %.02f\n", pct);                                                                                   
    }                                                                                                                    

    free(argv);
}                                                                                                                        

int main(int argc, char **argv)
{
    struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
    char buf[1024] = { 0 };
    char client_addr[64];
    int sock, client, bytes_read, status;
    socklen_t opt = sizeof(rem_addr);
    pid_t pid;
    cJSON *json;

    // allocate socket
    sock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    if (sock < 0) {<commit_msg>Added count to loop, so later on we can loop getting status<commit_after>/*
Copyright © 2015 NoTalentHack, LLC

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.
*/

#include "common.h"
#include "cJSON/cJSON.h"

uint8_t channel = 22;

#ifdef _DEBUG
#define DEBUG 1
#else
#define DEBUG 0
#endif

#define DEBUG 1

// commands between Client and Server. Server is on Edison side and
// client is on the phone side
#define SERIAL_CMD_START       1
#define SERIAL_CMD_STATUS      2
#define SERIAL_CMD_ERROR       3
#define SERIAL_CMD_KILL        4 
#define SERIAL_CMD_STOP        5
#define SERIAL_CMD_CPU_INFO    6
#define SERIAL_CMD_CLOSE       0xFF 

const char *KEY_COMMAND_TYPE   = "command_type";
const char *KEY_COMMAND        = "command";
const char *KEY_CAPTURE_OUTPUT = "capture_output";
const char *KEY_IDENTIFIER     = "identifier";
const char *KEY_PERCENT        = "percent";
const char *KEY_TOAST          = "toast";
const char *KEY_FREQUENCY      = "frequency";
const char *KEY_CPU_CORES      = "cpu_cores";
const char *KEY_CPU_FAMILY     = "cpu_family";
const char *KEY_STEPPING       = "stepping";
const char *KEY_MODEL          = "model";
const char *KEY_CACHE_SIZE     = "cache_size";
const char *KEY_MODEL_NAME     = "model_name";
const char *KEY_VENDOR_ID      = "vendor_id";

/* Protocol between client and server
 *     byte 1 = command 
 *     byte 2-n = command line except for close which is empy
 */

// strip out all arguments                                        
void strip_argv(char *buffer) {                                   
    char *ptr;                                                    
    int slen;                                                     
                                                                  
    ptr = strchr(buffer, ' ');  // space is where arguments starts
    if (ptr != '\0') {                                            
        slen = (int)(ptr - buffer);                                   
        if (slen > 0) {                                               
            buffer[slen] = '\0';                                      
        }                                                             
        printf("buf = %s\n", buffer);                                 
    }                                                             
} 

void returnCpuInfo(int client) {
    struct cpuInfo cpuinfo;
    getCpuInfo(&cpuinfo); 

    // build cpu info data
    cJSON *json = cJSON_CreateObject();
    cJSON_AddNumberToObject(json, KEY_COMMAND_TYPE, SERIAL_CMD_CPU_INFO);
    cJSON_AddNumberToObject(json, KEY_FREQUENCY, cpuinfo.frequency);
    cJSON_AddNumberToObject(json, KEY_CPU_CORES, cpuinfo.cpu_cores);
    cJSON_AddNumberToObject(json, KEY_CPU_FAMILY, cpuinfo.cpu_family);
    cJSON_AddNumberToObject(json, KEY_STEPPING, cpuinfo.stepping);
    cJSON_AddNumberToObject(json, KEY_MODEL, cpuinfo.model);
    cJSON_AddStringToObject(json, KEY_CACHE_SIZE, cpuinfo.cache_size);
    cJSON_AddStringToObject(json, KEY_MODEL_NAME, cpuinfo.model_name);
    cJSON_AddStringToObject(json, KEY_VENDOR_ID, cpuinfo.vendor_id);
        
    char *out = cJSON_Print(json, 0);
    int slen = strlen(out);
    int bytes_wrote = write(client, out, slen);              
    if (bytes_wrote <= 0 || bytes_wrote != slen) {       
        // Use system log?                                 
        fprintf(stderr, "Can't write to client\n");        
    }                                                      
    free(out);
    cJSON_Delete(json);
}

// return unknown command error message
void returnMessage(int client, int msgType,  char *format, char *str) {
    char error[256] = { 0 };
    sprintf(error, format, str);

    // build status data
    cJSON *json = cJSON_CreateObject();
    cJSON_AddNumberToObject(json, KEY_COMMAND_TYPE, msgType);
    cJSON_AddStringToObject(json, KEY_TOAST, error);
        
    char *out = cJSON_Print(json, 0);
    int slen = strlen(out);
    int bytes_wrote = write(client, out, slen);              
    if (bytes_wrote <= 0 || bytes_wrote != slen) {       
        // Use system log?                                 
        fprintf(stderr, "Can't write to client\n");        
    }                                                      
    free(out);
    cJSON_Delete(json);
} 

// return last known error message
void returnError(int client) {
    char error[BUFSIZE] = { 0 };
    get_lasterror(error);                         
    returnMessage(client, SERIAL_CMD_ERROR, "%s", error);
}

void returnUnknown(int client, char *format, char *str) {
    returnMessage(client, SERIAL_CMD_ERROR, format, str);
}

// argv that is needed to pass into returnCpuUsage function as part of
// pthread_create function
struct argvCpuInfo {
    int client;
    int identifier;
    pid_t pid;
}; 

// Function to return cpu usage and other info about process
void* returnCpuUsage(void *arg)                                                                                                
{                                                                                                                        
    struct pstat prev, curr;                                                                                             
    double pct;                                                                                                          
    struct argvCpuInfo *argv = (struct argvCpuInfo *)arg; 
    int cnt = 0;
    
    // could loop if needed by change cnt < n
    while( cnt < 1 )
    {                                                                                                                    
        if( get_usage(argv->pid, &prev) == -1 ) {                                                                              
            printf( "error\n" );                                                                                         
        }                                                                                                                
                                                                                                                         
        sleep( 2 );                                                                                                      
                                                                                                                         
        if( get_usage(argv->pid, &curr) == -1 ) {                                                                              
            printf( "error\n" );                                                                                         
        }                                                                                                                
                                                                                                                         
        calc_cpu_usage_pct(&curr, &prev, &pct);                                                                          
       
        // build status data
        cJSON *json = cJSON_CreateObject();
        cJSON_AddNumberToObject(json, KEY_COMMAND_TYPE, SERIAL_CMD_STATUS);
        cJSON_AddNumberToObject(json, KEY_IDENTIFIER, argv->identifier);
        cJSON_AddNumberToObject(json, KEY_PERCENT, pct);
        
        int slen = strlen(json->string);
        int bytes_wrote = write(argv->client, json->string, slen);              
        if (bytes_wrote <= 0 || bytes_wrote != slen) {       
           // Use system log?                                 
           fprintf(stderr, "Can't write to client\n");        
        }                                                      
        cJSON_Delete(json);

        cnt++;
        printf("%%cpu: %.02f\n", pct);                                                                                   
    }                                                                                                                    

    free(argv);
}                                                                                                                        

int main(int argc, char **argv)
{
    struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
    char buf[1024] = { 0 };
    char client_addr[64];
    int sock, client, bytes_read, status;
    socklen_t opt = sizeof(rem_addr);
    pid_t pid;
    cJSON *json;

    // allocate socket
    sock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    if (sock < 0) {
{'fraction_non_alphanumeric': 0.06899488926746167, 'fraction_numerical': 0.00516396933560477, 'mean_word_length': 1.0902414598865027, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 213, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5372104', 'n_tokens_mistral': 4369, 'n_tokens_neox': 4170, 'n_words': 1284}