repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
Bern2539/PSoC-AMT21-Driver
src/amt21_driver.c
/******************************************************************************* * * CUI AMT21XX-V Encoder driver for PSoC * Copyright (C) 2020, <NAME> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *******************************************************************************/ #include "amt21_driver.h" // Delays #define AMT21_START_UP_TIME_MS (200u) #define AMT21_TURNAROUND_TIME_US (30u) // Commands #define AMT21_RESPONSE_LENGTH ((uint8)2u) #define AMT21_CMD_LENGTH ((uint8)1u) #define AMT21_EXT_CMD_LENGTH ((uint8)2u) #define AMT21_READ_POS ((uint8)(AMT21_NODE_ADDR + 0x00u)) #define AMT21_READ_TURNS ((uint8)(AMT21_NODE_ADDR + 0x01u)) #define AMT21_EXT_CMD ((uint8)(AMT21_NODE_ADDR + 0x02u)) #define AMT21_RESET_ENC ((uint8)(0x75u)) #ifdef AMT21_SINGLE_TURN #define AMT21_SET_ZERO_POS ((uint8)(0x5Eu)) // Single turn encoders only #endif /******************************************************************************* * PRIVATE PROTOTYPES *******************************************************************************/ void _uart_read(uint8 *data, uint8 length); void _uart_write(uint8 *data, uint8 length); bool _check_parity(uint16 *response); /******************************************************************************* * PUBLIC FUNCTIONS *******************************************************************************/ /******************************************************************************* * Function Name: amt21_driver_init ******************************************************************************** * Summary: * Start UART component and wait until the encoder as started. * Should be called once before the infinite loop in your main. * * Parameters: * None. * * Return: * None. * *******************************************************************************/ void amt21_init() { UART_AMT21_Start(); CyDelay(AMT21_START_UP_TIME_MS); UART_AMT21_ClearRxBuffer(); UART_AMT21_ClearTxBuffer(); } /******************************************************************************* * Function Name: amt21_get_pos ******************************************************************************** * Summary: * Read the absolute position from the encoder. * * Parameters: * None. * * Return: * uint16: Absolute position of the encoder. * *******************************************************************************/ uint16 amt21_get_pos() { // Send READ_POS command uint8 cmd = AMT21_READ_POS; _uart_write(&cmd, AMT21_CMD_LENGTH); // Wait for encoder to reply CyDelayUs(AMT21_TURNAROUND_TIME_US); // Read response uint8 response_raw[AMT21_RESPONSE_LENGTH]; _uart_read(response_raw, AMT21_RESPONSE_LENGTH); uint16 pos = (response_raw[1] << 8u) | response_raw[0]; // Check parity and extract value if(!_check_parity(&pos)) return 0; // Remove the parity check bits pos = (pos & 0x3FFFu); // Convert value to match encoder's resolution (see AMT21_RESOLUTION) if(AMT21_RESOLUTION == 12u) pos = pos >> 2u; // Return the position return pos; } /******************************************************************************* * Function Name: amt21_get_turns ******************************************************************************** * Summary: * Read the turn counter's value from the encoder. * * Parameters: * None. * * Return: * int16: Turn counter value of the encoder. * *******************************************************************************/ int16 amt21_get_turns() { // Send READ_TURNS command uint8 cmd = AMT21_READ_TURNS; _uart_write(&cmd, AMT21_CMD_LENGTH); // Wait for encoder to reply CyDelayUs(AMT21_TURNAROUND_TIME_US); // Read response uint8 response_raw[AMT21_RESPONSE_LENGTH]; _uart_read(response_raw, AMT21_RESPONSE_LENGTH); uint16 turns_unsigned = (response_raw[1] << 8u) | response_raw[0]; // Check parity and extract value if(!_check_parity(&turns_unsigned)) return 0; // Remove the parity check bits (k0 and k1) turns_unsigned = (turns_unsigned & 0x3FFFu); // Replace k0 and k1 with the MSB of the 14-bit int) bool negative = (turns_unsigned >> 13) & 0x01u; if(negative) turns_unsigned = turns_unsigned | 0xC000; // Return the number of turns return (int16)turns_unsigned; } /******************************************************************************* * Function Name: amt21_reset_enc ******************************************************************************** * Summary: * Reset the encoder. * * Parameters: * None. * * Return: * None. * *******************************************************************************/ void amt21_reset_enc() { // Send RESET_ENC command uint8 cmd[AMT21_EXT_CMD_LENGTH] = {AMT21_EXT_CMD, AMT21_RESET_ENC}; _uart_write(cmd, AMT21_EXT_CMD_LENGTH); // Wait for encoder to reset CyDelay(AMT21_START_UP_TIME_MS); } #ifdef AMT21_SINGLE_TURN /******************************************************************************* * Function Name: amt21_set_zero_pos ******************************************************************************** * Summary: * Set zero to the actual position. * * Parameters: * None. * * Return: * None. * *******************************************************************************/ void amt21_set_zero_pos() { // Send AMT21_SET_ZERO_POS command uint8 cmd[AMT21_EXT_CMD_LENGTH] = {AMT21_EXT_CMD, AMT21_SET_ZERO_POS}; _uart_write(cmd, AMT21_EXT_CMD_LENGTH); } #endif /******************************************************************************* * PRIVATE FUNCTIONS *******************************************************************************/ /******************************************************************************* * Function Name: _uart_read ******************************************************************************** * Summary: * Read all available bytes from UART. * * Parameters: * [out] data: Array containing the read bytes. * [in] length: Number of bytes to read. * * Return: * uint8: Number of bytes read. * *******************************************************************************/ void _uart_read(uint8 *data, uint8 length) { // Verify parameters if(!data || length <= 0) return; // Read bytes for(int i=0; i<length; i++) { data[i] = UART_AMT21_GetChar(); } } /******************************************************************************* * Function Name: _uart_write ******************************************************************************** * Summary: * Write bytes to UART. * * Parameters: * data: Array containing the bytes to write. * length: Number of bytes to write. * * Return: * None. * *******************************************************************************/ void _uart_write(uint8 *data, uint8 length) { // Verify parameters if(!data || length <= 0) return; // Write bytes UART_AMT21_PutArray(data, length); } /******************************************************************************* * Function Name: _check_parity ******************************************************************************** * Summary: * Check parity and return the value embedded in the response. * * Details: * Checksum * The AMT21 encoder uses a checksum calculation for detecting transmission * errors. The upper two bits of every response from the encoder are check bits. * Those values are shown in the examples below as K1 and K0. The check bits are * odd parity; K1 for the odd bits in the response, and K0 for the even bits in * the response. These check bits are not part of the position, but are used to * verify its validity. The remaining lower 14 bits are the useful data. Here is * an example of how to calculate the checkbits for a 16-bit response, from a * 14-bit encoder. * * Full response: 0x61AB * 14-bit position: 0x21AB (8619 decimal) * * Checkbit Formula * Odd: K1 = !(H5^H3^H1^L7^L5^L3^L1) * Even: K0 = !(H4^H2^H0^L6^L4^L2^L0) * * From the above response 0x61AB: * Odd: 0 = !(1^0^0^1^1^1^1) = correct * Even: 1 = !(0^0^1^0^0^0^1) = correct * * Parameters: * response: Message received from the encoder. * * Return: * bool: True if checksum is valid. * *******************************************************************************/ bool _check_parity(uint16 *response) { // Verify parameters if(!response) return false; // Check odd bits parity (odd parity) bool k1 = (*response >> 15u) & 0x01u; bool odd_checkbit = !(((*response >> 1u) & 0x01u) ^ ((*response >> 3u) & 0x01u) ^ ((*response >> 5u) & 0x01u) ^ ((*response >> 7u) & 0x01u) ^ ((*response >> 9u) & 0x01u) ^ ((*response >> 11u) & 0x01u) ^ ((*response >> 13u) & 0x01u)); if(odd_checkbit != k1) return false; // Check even bits parity (odd parity) bool k0 = (*response >> 14u) & 0x01u; uint8 even_checkbit = !(((*response >> 0u) & 0x01u) ^ ((*response >> 2u) & 0x01u) ^ ((*response >> 4u) & 0x01u) ^ ((*response >> 6u) & 0x01u) ^ ((*response >> 8u) & 0x01u) ^ ((*response >> 10u) & 0x01u) ^ ((*response >> 12u) & 0x01u)); if(even_checkbit != k0) return false; return true; } /* [] END OF FILE */
Bern2539/PSoC-AMT21-Driver
src/amt21_driver.h
<reponame>Bern2539/PSoC-AMT21-Driver /******************************************************************************* * * CUI AMT21XX-V Encoder driver for PSoC * Copyright (C) 2020, <NAME> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************** * * Summary: * Handles communication with the CUI AMT21 series encoder. * You are required to convert the RS-485 (encoder) to UART (PSoC). * * Required components in TopDesign: * 1 x UART (named 'UART_AMT21') * 1 x Digital Input Pin connected to UART_AMT21/rx * 1 x Digital Output Pin connected to UART_AMT21/tx * 1 x Digital Output Pin connected to UART_AMT21/tx_en * 1 x Logic Low '0' connected to UART/reset * * If Data Rate = 2Mbps (see datasheet, page 5) * 1 x Clock (set at 32MHz) connected to UART_AMT21/clock * * Configuration of component UART_enc (TopDesign): * Configure tab * Mode = "Full UART (TX + RX)" * Bits per second = Data rate of your encoder (see datasheet, page 5) * Data bits = "8" * Parity type = "None" * Stops bits = "1" * Flow control = "None" * * Advanced tab * RS-485 Configuration options = "Harware TX-Enable" ticked * Oversampling rate = "16x" * * If Data Rate = 2Mbps (see datasheet, page 5) * Clock selection = "External clock" * Otherwise * Clock selection = "Internal clock" * * Clocks configurations (.cydwr): * If Data Rate = 2Mbps (see datasheet, page 5) * PLL = 64MHz (or a multiple of 32MHz) * * Macros (see below): * AMT21_RESOLUTION = Resolution of your encoder as per its part number * (see datasheet, page 5) * AMT21_NODE_ADDR = RS485 node address of your encoder * (see datasheet, page 3) * AMT21_SINGLE_TURN = Uncomment if your encoder is single-turn * (see datasheet, page 5) * * References: * https://www.cuidevices.com/product/motion/rotary-encoders/absolute/modular/amt21-series * ******************************************************************************** * * Revisions: * 1.0: First. * *******************************************************************************/ #ifndef _AMT21_DRIVER_H #define _AMT21_DRIVER_H #include <project.h> #include <sys/param.h> #include <stdbool.h> /******************************************************************************* * MACROS *******************************************************************************/ // Characteristics #define AMT21_RESOLUTION (12u) // 12-bit or 14-bit (see datasheet, page 5) #define AMT21_NODE_ADDR (0x54u) // Default is 0x54 //#define AMT21_SINGLE_TURN // Uncomment if single-turn (see datasheet, page 5) /******************************************************************************* * PUBLIC PROTOTYPES *******************************************************************************/ // Init void amt21_init(); // Read commands uint16 amt21_get_pos(); int16 amt21_get_turns(); // Write commands void amt21_reset_enc(); #ifdef AMT21_SINGLE_TURN void amt21_set_zero_pos(); #endif #endif // _AMT21_DRIVER_H /* [] END OF FILE */
oligval/Darkest-Light
Mystic-Light-API-Wrapper/mlapi_wrapper.h
#pragma once #include <tuple> #include <vector> #include <string> namespace starl1ght { namespace mystic_light { enum class result { ok, generic_error, timeout, not_implemented, not_initialized, invalid_argument, device_not_found, not_supported, admin_rights_are_needed, not_in_enum }; result initialize(const wchar_t* path_to_dll); std::tuple<result, std::vector<std::wstring>, std::vector<uint32_t>> get_device_info(); std::tuple<result, uint8_t, uint8_t, uint8_t> get_led_color(const wchar_t* device, uint32_t led_id); std::tuple<result, std::wstring> get_led_style(const wchar_t* device, uint32_t led_id); std::tuple<result, uint32_t> get_led_bright(const wchar_t* device, uint32_t led_id); std::tuple<result, uint32_t> get_led_max_bright(const wchar_t* device, uint32_t led_id); std::tuple<result, uint32_t> get_led_speed(const wchar_t* device, uint32_t led_id); std::tuple<result, uint32_t> get_led_max_speed(const wchar_t* device, uint32_t led_id); std::tuple<result> get_led_info(const wchar_t* device, uint32_t led_id); result set_led_style(const wchar_t* device, uint32_t led_id, const wchar_t* style); result set_led_color(const wchar_t* device, uint32_t led_id, uint8_t r, uint8_t g, uint8_t b); result set_led_speed(const wchar_t* device, uint32_t led_id, uint32_t speed); result set_led_brightness(const wchar_t* device, uint32_t led_id, uint32_t brightness); } }
dan-seol/C
strInv.c
<reponame>dan-seol/C #include <stdio.h> int main(int argc, char *argv[]){ char s[100] = "Hello World"; int c = 0; int e = 0; char t[100]; fgets(t, 99, stdin); while(s[c]!= '\0'){ c++; } while(t[e]!= '\0'){ e++; } for(int d = c-1; d >= 0; d--){ printf("%c", s[d]); } printf("\n"); for(int f = e-1; f >= 0; f--){ printf("%c", t[f]); } printf("\n"); return 0; }
dan-seol/C
garb.c
#include <stdio.h> int main(int argc, char *argv[]){ int i =5; float f = 3.9; int k = i+f; printf("The result of adding 5 and 3.9 is %d\n", k); }
dan-seol/C
midtermEx1.c
#include <stdio.h> void muddle(char string[]){ string[0] = 'M' + 1; string[1] = string[1]; string[2] = string[1]; char temp = string[4]; string[4] = string[5]; string[5] = temp; } int main(void){ char string[10] = "goedel"; muddle(string); printf("%s\n", string); return 0; }
dan-seol/C
countWords.c
#include <stdio.h> #include <string.h> int words(const char sentence[]) { int counted = 0; // result // state: const char* it = sentence; int inword = 0; do switch(*it) { case '\0': case ' ': case '\t': case '\n': case '\r': // TODO others? if (inword){inword = 0; counted++;} break; default: inword =1; } while(*it++); return counted; } int main(int argc, const char *argv[]) { char t[2000]; fgets(t, 2000, stdin); printf("%d\n", words(t)); printf("%d\n", words("")); printf("%d\n", words("\t")); printf("%d\n", words(" a castle")); printf("%d\n", words("my world is a castle")); }
dan-seol/C
fnvar.c
#include <stdio.h> int increment(int fnvar){ fnvar++; return fnvar; } int main(){ int a=5; increment(a); printf("The value of a is now %d\n", a); int b=5; b = increment(b); printf("The value of b is now %d\n", b); }
dan-seol/C
Ex1617.c
#include <stdio.h> /* copy I to O; 1st version */ int main(void) { printf("We will see the value of boolean values : %d\n", getchar() != EOF); printf("This is the value of EOF, %d\n", EOF); }
dan-seol/C
strCatTest.c
#include <stdio.h> #include <string.h> //Concatenates two strings int main(int argc, char* argv[]){ if(argc != 3){ printf("ERROR: please type in a string and a positive integer\n"); return 0; } char s1[256]; char s2[256]; strcpy(s1, argv[1]); strcpy(s2, argv[2]); strcat(s1, " "); strcat(s1, s2); puts(s1); }
dan-seol/C
StrCountPtr.c
<filename>StrCountPtr.c #include <stdio.h> int main(void){ char str_var[100] = "world"; int length = 0; char *ptr = str_var; while(*ptr){ ptr++; length++; } printf("The string %s has length %d.\n", str_var, length); return 0; }
dan-seol/C
A3_solution.c
/* FILE: A3_solutions.c is where you will code your answers for Assignment 3. * * Each of the functions below can be considered a start for you. They have * the correct specification and are set up correctly with the header file to * be run by the tester programs. * * You should leave all of the code as is, especially making sure not to change * any return types, function name, or argument lists, as this will break * the automated testing. * * Your code should only go within the sections surrounded by * comments like "REPLACE EVERTHING FROM HERE... TO HERE. * * The assignment document and the header A3_solutions.h should help * to find out how to complete and test the functions. Good luck! * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "A3_provided_functions.h" unsigned char* bmp_open( char* bmp_filename, unsigned int *width, unsigned int *height, unsigned int *bits_per_pixel, unsigned int *padding, unsigned int *data_size, unsigned int *data_offset ) { unsigned char *img_data=NULL; // REPLACE EVERYTHING FROM HERE FILE *bmpfile = fopen(bmp_filename, "rb"); // we are using "rb" since we are opening non-text //check if file is null if( bmpfile == NULL ){ //clause in bmp info that prints a message return img_data; } char b, m; fread (&b,1,1,bmpfile); fread (&m,1,1,bmpfile); //find the size of the file fread( data_size, 1, sizeof(unsigned int), bmpfile ); rewind(bmpfile); //allocate the amount of heap memory img_data=(unsigned char*)malloc(*data_size*sizeof(unsigned char)); fread( img_data, 1, *data_size, bmpfile ); //assign the variables *width = *((unsigned int*)(img_data+18)); unsigned int* hp=(unsigned int*)(img_data+22); *height = *hp; *bits_per_pixel = *((short int*)(img_data+28)); *data_offset = *((unsigned int*)(img_data+10)); *padding = (4 - (*width*(*bits_per_pixel/8)) % 4) % 4; // TO HERE! return img_data; } void bmp_close( unsigned char **img_data ) { // REPLACE EVERYTHING FROM HERE if( *img_data != NULL ){ free( *img_data ); *img_data = NULL; } // TO HERE! } unsigned char*** bmp_scale( unsigned char*** pixel_array, unsigned char* header_data, unsigned int header_size, unsigned int* width, unsigned int* height, unsigned int num_colors, float scale ) { unsigned char*** new_pixel_array = NULL; // REPLACE EVERYTHING FROM HERE //make variables for new_height and new_width to make enough space unsigned int scaled_height = (unsigned int) ((*height) * (scale)); unsigned int* new_height = &scaled_height; unsigned int scaled_width = (unsigned int) ((*width) * (scale)); unsigned int* new_width = &scaled_width; //reasign the values *width=*new_width; *height=*new_height; //use malloc to create space for new_pixel_array new_pixel_array = (unsigned char***)malloc( sizeof(unsigned char**) * (*new_height)); if( new_pixel_array == NULL ){ printf( "Error: bmp_scale failed to allocate memory for image of height %d.\n", (*height) ); return NULL; } //initialize enough space in the rows for new data for( int row=0; row<*new_height; row++ ){ new_pixel_array[row] = (unsigned char**)malloc( sizeof(unsigned char*) * (*new_width) ); for( int col=0; col<*new_width; col++ ){ new_pixel_array[row][col] = (unsigned char*)malloc( sizeof(unsigned char) * (num_colors) ); } } //populate new pixel array for( int row=0; row<*new_height; row++ ) for( int col=0; col<*new_width; col++ ) for( int color=0; color<num_colors; color++ ){ new_pixel_array[row][col][color] = pixel_array[(int)(row/scale)][(int)(col/scale)][color]; } //change the header data int padding = ( 4 - ((*new_width) * num_colors) % 4) % 4; int row_size = (*new_width)*num_colors+padding; int image_size = header_size + (*height)*row_size; *(unsigned int*)(header_data+2) = (image_size); *(unsigned int*)(header_data+18) = *new_width; *(unsigned int*)(header_data+22) = *new_height; // TO HERE! return new_pixel_array; } int bmp_collage( char* background_image_filename, char* foreground_image_filename, char* output_collage_image_filename, int row_offset, int col_offset, float scale ) { // REPLACE EVERYTHING FROM HERE //1. open each file //background unsigned int back_width; unsigned int back_height; unsigned int back_bpp; unsigned int back_pad; unsigned int back_data_size; unsigned int back_data_offset; unsigned char* back_img_data = NULL; back_img_data= bmp_open( background_image_filename, &back_width, &back_height, &back_bpp, &back_pad, &back_data_size, &back_data_offset); //foreground unsigned int fore_width; unsigned int fore_height; unsigned int fore_bpp; unsigned int fore_pad; unsigned int fore_data_size; unsigned int fore_data_offset; unsigned char* fore_img_data = NULL; fore_img_data= bmp_open( foreground_image_filename, &fore_width, &fore_height, &fore_bpp, &fore_pad, &fore_data_size, &fore_data_offset); //1b. Check to make sure bpp =32 if(fore_bpp != 32 || back_bpp != 32){ printf( "Error: bpp is not 32 for one of the files" ); return -1; } //close the images because we are going to open them again bmp_close(&fore_img_data); bmp_close(&back_img_data); //2. scale the foreground and turn both into pixel array unsigned char* fore_header_data; unsigned int fore_header_size, fore_num_colors; unsigned char*** fore_pixel_array = NULL; unsigned char*** back_pixel_array = NULL; unsigned char* back_header_data; unsigned int back_header_size, back_num_colors; //3D array opens the file to extract data fore_pixel_array = bmp_to_3D_array( foreground_image_filename, &fore_header_data, &fore_header_size, &fore_width, &fore_height, &fore_num_colors); back_pixel_array = bmp_to_3D_array( background_image_filename, &back_header_data, &back_header_size, &back_width, &back_height, &back_num_colors); if( fore_pixel_array == NULL || back_pixel_array == NULL){ printf( "Error: bmp_to_3D_array failed for file %s.\n", foreground_image_filename ); return -1; } unsigned char*** scaled_pixel_array = bmp_scale( fore_pixel_array, fore_header_data, fore_header_size, &fore_width, &fore_height, fore_num_colors, scale ); if( scaled_pixel_array == NULL ){ printf( "Error: Call to bmp_scale failed!\n" ); return -1; } //3. get the size of background and allocate memory for new file //get the size of the image in the foreground int fore_padding = ( 4 - (fore_width * fore_num_colors) % 4) % 4; int row_size = fore_width*fore_num_colors+fore_padding; int fore_image_size = fore_header_size + fore_height*row_size; //find the size the foreground image can take up //NEED TO MAKE SURE CORRECT unsigned int max_width = back_width - col_offset; unsigned int max_height = back_height - row_offset; int off_padding = (4 - (max_width * 4) %4)%4; int max_row_size = max_width*4+off_padding; int max_pixel_size = back_header_size + max_height*max_row_size; //check to make sure forground will fit if(max_pixel_size<fore_image_size){ printf( "Error: foreground image too large\n" ); return -1; } //4. overlay the files unsigned char*** new_pixel_array = NULL; new_pixel_array = (unsigned char***)malloc( sizeof(unsigned char**) * (back_height)); if( new_pixel_array == NULL ){ printf( "Error: failed to allocate memory for image of height %d.\n", (back_height) ); return -1; } //initialize enough space in the rows for new data for( int row=0; row<back_height; row++ ){ new_pixel_array[row] = (unsigned char**)malloc( sizeof(unsigned char*) * (back_width) ); for( int col=0; col<back_width; col++ ){ new_pixel_array[row][col] = (unsigned char*)malloc( sizeof(unsigned char) * (back_num_colors) ); } } //set the new array equal to the background new_pixel_array = back_pixel_array; //find the value of color at the offset spot int color_offset = 0; for(int row = 0; row<back_height; row++){ for(int col = 0; col<back_width; col++){ for(int color = 0; color<back_num_colors; color++){ if(row == row_offset && col == col_offset){ color_offset = color; break; } } } } //overlay foreground where foreground has color for(int row = row_offset; row<fore_height + row_offset; row++){ for(int col = col_offset; col<fore_width+col_offset; col++){ for(int color = color_offset; color<fore_num_colors+color_offset; color++){ if(scaled_pixel_array[row-row_offset][col-col_offset][color-color_offset] > 0 ){ new_pixel_array[row][col][color] = scaled_pixel_array[row-row_offset][col-col_offset][color-color_offset]; } } } } //transfer new_pixel_array to a file bmp_from_3D_array( output_collage_image_filename, back_header_data, back_header_size, new_pixel_array, back_width, back_height, back_num_colors ); // TO HERE! return 0; }
dan-seol/C
access_arg.c
<reponame>dan-seol/C #include <stdio.h> int main(int argc, char *argv[]){ printf("I have %d arguments\n", argc); printf("The zeroth arg is %s\n", argv[0]); for(int i = 1; i <3 ; i++){ //printf("The 1st arg is %s", argv[1]); printf("The %d -th arg is %s\n",i, argv[i]); } }
dan-seol/C
countWord206.c
<reponame>dan-seol/C #include <stdio.h> int main() { char string[99999] = "The quick brown fox jumped over the pile of ice."; char *pos = string; unsigned int words = 0; while(*pos) { if(*pos == ' ' || *pos == '.') { words++; } printf("Procesing character %c with words %d.\n", *pos, words); pos++; } printf("There were %d words. \n", words); return 0; }
dan-seol/C
ctChar.c
<reponame>dan-seol/C #include <stdio.h> int main(void) { long nc= 0; while(getchar() != '\0'){ nc++; printf("%ld\n", nc); } return 0; }
dan-seol/C
arraysol1.c
<gh_stars>0 #include <stdio.h> #include <math.h> int main(int argc, char *argv[]){ const int array_length = 11; float account_balances[array_length]; for(int pos=0; pos<array_length; pos++){ account_balances[pos] = expf(pos); printf("The value of e to the power %d is %f \n", (pos), account_balances[pos]); } }
dan-seol/C
arrayex.c
<gh_stars>0 #include <stdio.h> int main(int argc, char *argv[]){ int hourly_prices[2] = {2,4}; for(int) printf("%d\n", *hourly_prices); }
dan-seol/C
filesortingdave.c
<reponame>dan-seol/C<filename>filesortingdave.c<gh_stars>0 /* FILE: sorting_excersize_starter_dave.c * * Please fill this in with some code to sort. You can use the * linear sort algorithm suggested on the Lecture 6 slides * or something you learned in a previous course. * Good luck! * * Author: <NAME> * Date: Sept 19, 2018 */ #include <stdio.h> int main(){ int array[4] = {3,1,4,2}; // Write your code here, try to sort the array for(int pos=0; pos<3; pos++){ int val_here = array[pos]; int min_over_rest = 9999999; int min_pos = -1; for(int next_pos = pos+1; next_pos <4; next_pos++){ if(array[next_pos] < min_over_rest){ min_over_rest = array[next_pos]; min_pos = next_pos; } } if(min_over_rest < val_here){ array[min_pos] = val_here; array[pos] = min_over_rest; } } printf( "The array holds: " ); for( int i=0; i<4; i++ ) printf( "%d ", array[i] ); printf("\n"); printf( "If you coded it correctly, you should see 1 2 3 4\n"); return 0; }
dan-seol/C
sortVocab.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <string.h> void sort_words(char *words[], int count) { char *x; for(int i=0; i<count; i++) { for(int j= i+1; j<count; j++) { if(strcmp(words[i], words[j]) > 0) { x = words[j]; words[j] = words[i]; words[i] = x; } } } } #ifndef RunTests int main(int argc, char *argv[]) { char *words[] = {"cherry", "orange", "apple"}; sort_words(words, 3); for(int i=0; i<3; i++) { printf("%s", words[i]); } } #endif
dan-seol/C
LARA/matrix.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #define ROWS 5 #define COLS 5 //1. fillMatrix void fillMatrix(int matrix[ROWS][COLS]) { srand(time(0)); for(int i = 0; i < ROWS; i++) { for(int j = 0; j < COLS; j++) { matrix[i][j] = (rand() % 100) + 1; } } } //2. printMatrix void printMatrix(int matrix[ROWS][COLS]) { for(int i = 0; i < ROWS; i++ ) { for(int j = 0; j < COLS; j++ ) { printf("%d ", matrix[i][j]); } printf("\n"); } } //3. transposeMatrix void transposeMatrix(int matrix[ROWS][COLS]) { int *pm = *matrix; for(int i = 0; i < ROWS; i++) { for(int j = 0; j < i; j++) { int ij = *(pm + (i * COLS) + j); int ji = *(pm + (j * COLS) + i); *(pm + (i * COLS) + j) = ji; *(pm + (j * COLS) + i) = ij; } } } //4. multiplyMatrix void multiplyMatrix(int m1[2][COLS], int m2[ROWS][COLS], int resultMatrix[ROWS][COLS]) { for(int i = 0; i < ROWS; i++) { for(int j = 0; j < COLS; j++) { int sum = 0; if(i < 2) { for(int k = 0; k < COLS; k++) { sum += (m1[i][k] * m2[k][j]); } } resultMatrix[i][j] = sum; } } } //main int main() { int matrix[ROWS][COLS]; fillMatrix(matrix); printMatrix(matrix); transposeMatrix(matrix); printMatrix(matrix); int matrix2[2][COLS] = {{0,1,2,3,4},{5,6,7,8,9}}; int matrixResult[ROWS][COLS]; multiplyMatrix(matrix2, matrix, matrixResult); printMatrix(matrixResult); return 0; }
dan-seol/C
simplecalc.c
<filename>simplecalc.c<gh_stars>0 #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]){ int l; l = atoi(argv[1]); for(int i=2; i<argc; i= i + 2){ if(strcmp(argv[i], "+")==0){ l = l + atoi(argv[i+1]); } else if (strcmp(argv[i], "-")==0){ l = l-atoi(argv[i+1]); } else if(strcmp(argv[i], "x")==0){ l = l*atoi(argv[i+1]); }else if(strcmp(argv[i], "/")==0){ l = l/atoi(argv[i+1]); } else{ printf("ERROR: I did not understand"); return -1; } } printf("%d", l); return 0; }
dan-seol/C
LARA/database.c
<filename>LARA/database.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #define SIZE 1024 typedef struct Record { int ID; char NAME[SIZE]; int AGE; double GPA; } Record; typedef struct node { Record val; struct node *next; } node_r; void trimSpace(const char *input, char *result) { int i, j = 0; for (i=0; input[i] != '\0'; i++) { if(!isspace((unsigned char)input[i])) { result[j] = input[i]; j++; } } result[j] = '\0'; } void showRecords() { FILE *fp = fopen("database.csv", "r"); char db1[SIZE]; printf("#################### DATABASE DISPLAY:START ####################\n"); int row = 1; while(fgets(db1, 2*SIZE, fp) != NULL) { char lineTrimmed[SIZE]; trimSpace(db1, lineTrimmed); //printf("%s\n", lineTrimmed); Record *record = malloc(sizeof(Record)); char * tok; tok = strtok(lineTrimmed,","); record->ID = (int) strtol(tok, NULL, 10); tok = strtok(0, ","); strcpy(record->NAME, tok); tok=strtok(0,","); record->AGE = (int) strtol(tok, NULL, 10); tok=strtok(0,","); record->GPA = strtod(tok, NULL); printf("Record %d : [ ID = %d, NAME = %s, AGE = %2d, GPA = %.1f ]\n", row, record->ID, record->NAME, record->AGE, record->GPA); row++; free(record); } fflush(fp); fclose(fp); printf("##################### DATABASE DISPLAY:END #####################\n"); } void addRecords(int newId, char* newName, int newAge, double newGpa) { FILE *fp = fopen("database.csv", "a+"); fprintf(fp, "%d, %s, %d, %.1f\n", newId, newName, newAge, newGpa); fflush(fp); fclose(fp); } int delRecords(char* nameToDel){ int isDetected = 0; FILE *fp = fopen("database.csv", "r"); FILE *result = fopen("database.tmp", "w"); char db1[SIZE]; while(fgets(db1, 2*SIZE, fp) != NULL) { char lineTrimmed[SIZE]; trimSpace(db1, lineTrimmed); Record *record = malloc(sizeof(Record)); char * tok; tok = strtok(lineTrimmed,","); record->ID = (int) strtol(tok, NULL, 10); tok = strtok(0, ","); strcpy(record->NAME, tok); tok=strtok(0,","); record->AGE = (int) strtol(tok, NULL, 10); tok=strtok(0,","); record->GPA = strtod(tok, NULL); if(strcmp(record->NAME, nameToDel) !=0) { fprintf(result, "%d, %s, %2d, %.1f\n", record->ID, record->NAME, record->AGE, record->GPA); } else { isDetected = 1; } free(record); } fflush(fp); fclose(fp); fflush(result); fclose(result); system("rm database.csv"); system("mv database.tmp database.csv"); return isDetected; } char* strUpp(char * lower){ char* name = malloc(1024); strcpy(name, lower); char *s = name; while(*s) { *s = toupper((unsigned char)*s); s++; } return name; } int main(int argc, char* argv[]){ //Opening the file for reading /* delRecords("dan"); showRecords(); addRecords(25, "dan", 22, 3.8); showRecords(); */ if(argc < 2){ printf("You did not provide any arguments.\nPlease enter: ./database CMP OPT1 OPT2 OPT3 OPT4\n"); return 1; } char * CMD = strUpp(argv[1]); int isSHOW = (strcmp(CMD, "SHOW") == 0); int isADD = (strcmp(CMD, "ADD") == 0) ; int isDELETE = (strcmp(CMD, "DELETE") == 0); if(!isSHOW && !isADD && !isDELETE ) { printf("The command you requested is invalid.\n Please select from one of these: SHOW, DELETE, ADD\n"); printf("The command you typed is (capitalized) : %s\n",CMD); return 1; }else if(isSHOW){ if(argc != 2){ printf("You typed unnecessary argument with SHOW\n"); return 1; } printf("Showing records:\n"); showRecords(); }else if(isDELETE){ if(argc == 2){ printf("The name of the record to delete is missing\n"); return 1; } int isDetected = delRecords(argv[2]); if(isDetected == 0){ printf("Sorry, that user was not found. Nothing was deleted\n"); return 1; } printf("The record of the user %s was deleted \n", argv[2]); } else { if(argc < 5){ printf("Missing ID, Name, AGE, and GPA arguments"); return 1; } int ID = (int) strtol(argv[2], NULL, 10); int AGE = (int) strtol(argv[4], NULL, 10); double GPA = strtod(argv[5], NULL); addRecords(ID, argv[3], AGE, GPA); printf("A new record with ID=%d, NAME=%s, AGE=%d, GPA=%.1f has been added\n",ID, argv[3], AGE, GPA); } return 0; }
dan-seol/C
strstrTest.c
<gh_stars>0 #include <stdio.h> #include <string.h> int main (int argc, char* argv[]) { char haystack[256]; char needle[256]; if(argc != 3){ printf("ERROR: Please type in two strings"); return 1; } strcpy(haystack, argv[1]); strcpy(needle, argv[2]); if(strlen(haystack) < strlen(needle)){ printf("ERROR: Your \" substring \" is longer than the original string to be compared"); } char *ret; ret = strstr(haystack, needle); printf("The substring is: %s\n", ret); return(0); }
dan-seol/C
strTOK.c
#include <string.h> #include <stdio.h> int main () { char str[80] = "This is - www.tutorialspoint.com - website"; const char s[2] = "-"; const char t[2] = " "; char *token; /* get the first token */ /* walk through other tokens */ while( token != NULL ) { printf( " %c\n", *token ); token = strtok(NULL, s, t); } return(0); }
dan-seol/C
q1b_sierpinski_diamond.c
<filename>q1b_sierpinski_diamond.c #include <stdio.h> #include <stdlib.h> // Used for atoi() function #include <string.h> // Used for strlen() function #include <math.h> int power2(int m){ if(m==0){ return 1; } else if (m < 0) { // positive integer assumes printf("This function is defined for nonnegative integers only"); return -1; } else { return 2*power2(m-1); } } double t_h(int height){ return ceil(height/2.0); } //method attempted but failed //*void line(int n, int m){ // for(int i=0; i<n; i++){ // if((n/2)-(m) < i && i <= n/2){ // printf("*"); // } else if(n/2< i && i < (n/2 +m) ){ // printf("*"); // } else { // printf(" "); // } // } //} //Watched the hint video & Changed the approach: Print Sierpinski's triangle first, and then build upon it. void whiteSp(int m, int h, int l){ double th = t_h(h); for(int i=0; i< th/2; i++){ printf(" "); } } void Tr(int m, int h, int l){ double th = t_h(h); if(l == 1){ for(int i =0; i<=h-1; i++){ int b1 = i > th-m-2; int b2 = i < th+m; if(b1 && b2){ printf("*"); } else { printf(" "); } } } else if(m < th/2){ //On top of the triangle whiteSp(m, h, l); Tr(m, h/2, l-1); whiteSp(m, h, l); } else { //At the bottom of the triangle! Tr(m-th/2, h/2, l-1); printf(" "); Tr(m-th/2, h/2, l-1); } } void TrFlipped(int h, int l){ double th = t_h(h); for(int j = th-2; j >= 0; j--){ Tr(j, h, l); printf("\n"); } } void sierpinski(int h, int l){ double th = t_h(h); int powerof2 = log2(th) - (int)log2(th) == 0; int heightref = power2(l-1); if(!powerof2 || th < heightref){ printf("ERROR: Height does not allow evenly dividing requested number of levels."); } else { for(int i = 0; i < th; i++){ Tr(i, h, l); printf("\n"); } TrFlipped(h, l); } } int main(int argc, char *argv[]) { //case separated when there are zero arguments if( argc > 3 ) { printf("ERROR: Wrong number of arguments. One required\n"); return 1; } else if (argc < 3){ printf("ERROR: Wrong number of arguments. One required\n"); return 1; } else { int n = (int) atoi(argv[1]); int m = (int) atoi(argv[2]); if(n % 2 == 0 ){ printf("ERROR: Bad argument. Height must be positive odd integer \n"); return 1; } printf("%d\n", n); sierpinski(n, m); return 0; } }
dan-seol/C
ts.c
#include <stdio.h> int main(int argc, char *argv[]){ int array[4] = {1,2,3,4}; for(int i=0; i<100; i++){ printf("%d, %d", i, array[i]); } }
dan-seol/C
LARA/ssv.h
#include <stdio.h> #include <string.h> #include <stdlib.h> void parse(char record[], int *acct, float *amnt) { sscanf(record, "%d %f", acct, amnt); }
dan-seol/C
q2_extract_wiki_links.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <math.h> // It can take multiple downloaded pages at once. //EXAMPLE OUTPUT from // $ ./a.out <NAME> // int main(int argc, char* argv[]){ for(int i =1; i<argc; i++){ printf("Here is your %d-th article.", i); char* fname = argv[i]; FILE *fpointer; fpointer = fopen(fname, "r+"); if(fpointer == NULL){ printf("ERROR MESSAGE: The file does not exist"); return -1; } size_t l; fseek(fpointer, 0 , SEEK_END); l = ftell(fpointer); rewind(fpointer); char s[l+1]; fread(s, 1, l+1, fpointer); s[l] = '\0'; char *begin = s; char *timeStamp = begin; char *end; char *nestedBegin; char *nestedEnd; //We iterate through the whole file while(1) { begin = strstr(timeStamp, "<a href=\"/wiki/"); if(begin == NULL) { break; } end= strstr(begin,"</a>"); if(end == NULL) { break; } size_t sizelabRat = end - begin; char labRat[sizelabRat]; strncpy(labRat, begin, sizelabRat); labRat[sizelabRat] = '\0'; char *d; if((d = strstr(labRat + 18, "<a href=\"/wiki/" )) != NULL) {timeStamp = begin + 18; continue; } nestedBegin = strstr(begin, "title=\""); nestedEnd = strstr(nestedBegin, "\">"); if(nestedBegin != NULL && nestedEnd != NULL) {size_t nestedSize= nestedEnd - (nestedBegin + 7); char pageTitle[nestedSize]; strncpy(pageTitle, nestedBegin + 7, nestedEnd - (nestedBegin + 7)); pageTitle[nestedSize] = '\0'; printf("%s \n", pageTitle); } timeStamp = begin + 18; printf("\n"); } fclose(fpointer); } return 0; }
dan-seol/C
ptrr.c
#include <stdio.h> void swap(int* i, int* j){ int k; k = *i; *i = *j; *j = k; } int main(int argc, char* argv[]) { int x = 3; int y = 4; int* a = &x; int* b = &y; swap(a, b); printf("%d, %d\n", *a, *b); return 0; }
dan-seol/C
Quiz3Q4.c
<reponame>dan-seol/C #include <stdio.h> int main(void){ unsigned char c = 'c'; unsigned char d = ( c >> 3 ) << 3; printf("%c\n", c); printf("%c\n", d); unsigned char e = c * 8; printf("%c\n", c >> 2); printf("%c\n", c << 2); return 0; }
dan-seol/C
progsol.c
#include <stdio.h> #include <math.h> #include <limits.h> #include <stdlib.h> int main(int argc, char* argv[]){ int array[argc-1]; for(int pos=1; pos<argc; pos++) array[pos-1] = atoi(argv[pos]); for(int pos=0; pos<argc-1; pos++){ int curr = array[pos]; int min_pos = -1; int min_val = INT_MAX; for(int other_pos=pos; other_pos<argc-1; other_pos++){ if(array[other_pos] < min_val){ min_pos = other_pos; min_val = array[other_pos]; } } array[min_pos] = curr; array[pos] = min_val; } for(int pos=0; pos<argc; pos++) printf("Array element %d is %d. \n", pos, array[pos]); return 0; }
dan-seol/C
q2_extract_wiki_links_attempt.c
<gh_stars>0 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> //char article[20] = "<a href= \"/wiki/"; //char title[7] = "title="; //char quote[2] = "\""; //const char* filename = arg; //char *ref; //char *token1; //char *token2; int main(int argc, char *argv[]){ for(int i =1; i<argc; i++){ const char* fname= argv[i]; //create a file pointer FILE *fp; //open the file and have the file pointer point to it fp = fopen(fname, "r+"); //print an error message if fp is null if(fp == NULL){ printf("ERROR: There is an error with the file."); return -1; } //copy the file contents to the file char s[INT_MAX/2]; fread(s, 1, INT_MAX/2-2, fp); s[INT_MAX/2-1] = '\0'; //set the start of the open pointer to the beginning of the haystack char *open = s; //this keeps track of the open pointer char *timeStamp = open; //pointers to be used in the while loop char *close; char *innerOpen; char *innerClose; //use a while loop to iterate through the whole file while(1){ //set open to the next occurance of "<a href ..." open = strstr(timeStamp, "<a href=\"/wiki/" ); //break the loop if open is null if(open == NULL){ break; } //set close to the next occurance of "</a>" close= strstr(open,"</a>"); //break the loop if close is null if(close == NULL){ break; } //create a char array labRat that is the size of the difference of the pointers size_t sizelabRat = close - open; char labRat[sizelabRat]; //copy the characters between the pointers open and close into labRat strncpy(labRat, open, close - open); labRat[sizelabRat] = '\0'; char *c; //test to see if there is another occurance between "<a href... " in the labRat if((c = strstr(labRat + 16, "<a href=\"/wiki/" )) != NULL){ timeStamp = open + 16; continue; } //look for "title=\" and "\>" in the string array innerOpen = strstr(open, "title=\""); innerClose = strstr(innerOpen, "\">"); //if "title=\" is in labRat, get the name and print it if(innerOpen != NULL && innerClose != NULL){ size_t sizeInner = innerClose - (innerOpen + 7); char pageName[sizeInner]; strncpy(pageName, innerOpen + 7, innerClose - (innerOpen + 7)); pageName[sizeInner] = '\0'; printf("%s \n", pageName); } //increase the position of the timeStamp by 15 (the length of "<a href ...") timeStamp = open + 16; } } } //FILE *fp = fopen(argv[1],"r"); //while(fgets(s, 9000, fp)){ // ref = strstr(s, article); // token1 = strstr(ref, title); // token2 = strtok(token1, quote); // printf("%s\n", token2);
dan-seol/C
Q3Q4.c
<filename>Q3Q4.c //COMP 206 Quiz 3 Question 4 #include <stdio.h> int* f( int size, int *ptr ){ int array[size]; array[0] = 1; return &size; } int main(){ int i = 5; int *p = f( i, &i ); i = p[0]; printf( "The value of i is %d.\n", i ); return 0; }
dan-seol/C
jk.c
<reponame>dan-seol/C<filename>jk.c #include <stdio.h> int main(void){ short int i=0; while(1){ printf("i is %d.\n", i); i++; } }
dan-seol/C
template.c
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]){ }
dan-seol/C
q1b_Alison.c
#include <stdio.h> #include <stdlib.h> #include <math.h> //This method prints out the space at the beginning and end of the triangle int printSpace(int y, int height, int level){ //get the height of the triangle double tri_height = ceil(height/2.0); //use a for loop to print out spaces for(int x = 0; x < tri_height/2; x++){ printf(" "); } return 1; } //this method draws out the triangles int printTriangle(int y, int height, int level){ //get the height of the triangle double tri_height = ceil(height/2.0); //draw the triangle out if the level is 1 if(level == 1){ for(int x = 0; x < height; x++){ if(x >= tri_height-y-1 && x <= tri_height+y-1){ printf("*"); } else{ printf(" "); } } return 1; } //if we are in the top half of the triangle, one triangle and space on either side of it else if(y < tri_height/2){ printSpace(y, height, level); printTriangle(y, height/2, level-1); printSpace(y, height, level); } //otherwise, print 2 triangles with a space between them else{ printTriangle(y-tri_height/2, height/2, level- 1); printf(" "); printTriangle(y-tri_height/2, height/2, level - 1); } return 1; } int main(int argc, char* argv[]){ //print out an error statement if there is more than one argument. if(argc != 3){ printf("ERROR: Wrong number of arguments. 2 required.\n"); return -1; } //Convert the first argument from a string into an integer. //This is the height of the diamond. int height = atoi(argv[1]); //Convert the second argument from a string into an integer. //This is the fractal level of the diamond int level = atoi(argv[2]); //Get the height of the triangle. Put 2.0 to avoid integar division. double tri_height = ceil(height/2.0); //print out an error statement if the first argument is even or negative. if (height%2 == 0 || height <= 0){ printf("ERROR: Bad argument. Height must be positive odd integer.\n"); return -1; } //print out an error statement if the height isn't a power of 2 or if it isn't greater that 2^(level -1) if ((int)log2(tri_height) < log2(tri_height) || tri_height < pow(2,level - 1)){ printf("ERROR: Height does not allow evenly dividing requested number of levels.\n"); return -1; } //print the rightsideup triangle for(int y = 0; y < tri_height; y++){ printTriangle(y, height, level); printf("\n"); } //print the upsidedown triangle for(int y = tri_height-2; y >= 0; y--){ printTriangle(y, height, level); printf("\n"); } }
dan-seol/C
stringtest.c
<filename>stringtest.c #include <stdio.h> int main(int argc, char *argv[]){ char name[100] = "Daniel"; char sis[100] = "Anne"; char mom[100] = "Heewon"; int c = 0; //char s[100]; // gets(s); input from the user. while (name[c] != '\0') { printf("%c", name[c]); c++; } printf("\n"); c=0; while (sis[c] != '\0') { printf("%c", sis[c]); c++; } printf("\n"); c=0; while (mom[c] != '\0') { printf("%c", mom[c]); c++; } printf("\n"); }
dan-seol/C
q2_Alison.c
<gh_stars>0 #include <stdio.h> #include <string.h> int main(int argc, char* argv[]){ //return an error statement if there is not the right amount of arguments if(argc != 2){ printf("ERROR: You must have 1 argument."); return -1; } //save the first argument as the filename const char* filename = argv[1]; //create a file pointer FILE *fp; //open the file and have the file pointer point to it fp = fopen(filename, "r+"); //print an error message if fp is null if(fp == NULL){ printf("ERROR: There is an error with the file."); return -1; } //get length of the file size_t length; fseek(fp, 0 , SEEK_END); length = ftell(fp); rewind(fp); //copy the file contents to the file char haystack[length+1]; fread(haystack, 1, length+1, fp); haystack[length] = '\0'; //set the start of the open pointer to the beginning of the haystack char *open = haystack; //this keeps track of the open pointer char *timeStamp = open; //pointers to be used in the while loop char *close; char *innerOpen; char *innerClose; //use a while loop to iterate through the whole file while(1){ //set open to the next occurance of "<a href ..." open = strstr(timeStamp, "<a href=\"/wiki/" ); //break the loop if open is null if(open == NULL){ break; } //set close to the next occurance of "</a>" close= strstr(open,"</a>"); //break the loop if close is null if(close == NULL){ break; } //create a char array labRat that is the size of the difference of the pointers size_t sizelabRat = close - open; char labRat[sizelabRat]; //copy the characters between the pointers open and close into labRat strncpy(labRat, open, close - open); labRat[sizelabRat] = '\0'; char *c; //test to see if there is another occurance between "<a href... " in the labRat if((c = strstr(labRat + 16, "<a href=\"/wiki/" )) != NULL){ timeStamp = open + 16; continue; } //look for "title=\" and "\>" in the string array innerOpen = strstr(open, "title=\""); innerClose = strstr(innerOpen, "\">"); //if "title=\" is in labRat, get the name and print it if(innerOpen != NULL && innerClose != NULL){ size_t sizeInner = innerClose - (innerOpen + 7); char pageName[sizeInner]; strncpy(pageName, innerOpen + 7, innerClose - (innerOpen + 7)); pageName[sizeInner] = '\0'; printf("%s \n", pageName); } //increase the position of the timeStamp by 15 (the length of "<a href ...") timeStamp = open + 16; } }
dan-seol/C
ctChar2.c
<reponame>dan-seol/C #include <stdio.h> /* count characters in input; 2nd version */ int main(int argc, char* argv[]){ double nc; for(nc = 0; getchar() != EOF; ++nc){ ; printf("%.0f\n", nc); } return 0; }
dan-seol/C
func.c
#include <stdio.h> int cumsum(int a, int b){ // returns the sum_{i=a}^{b} i int val = 0; for(int i = a; i < b+1; i++){ val += i; } return val; } int main(void){ printf("The sum of all integers from %d to %d is %d\n", 3, 10, cumsum(3,10)); printf("The sum of all integers from %d to %d is %d\n", 6, 17, cumsum(6,17)); } //function components // a return type // a fileName // an argument List // a function body list //the name must be unique //pass arguments by values //define a local scope
dan-seol/C
FC_for.c
#include <stdio.h> int main(void){ int j; for(int i= 0; i< 300; i +=20){ j = 5*(i-32)/9; printf("%d\t%d\n",i, j); } }
dan-seol/C
midQ6.c
#include <stdio.h> #include <string.h> int main(void){ char *my_word_array[3] = {NULL, NULL, NULL}; char first[100] = "one"; my_word_array[0] = first; my_word_array[1] = "two"; char third[100]; third[0] = '3'; my_word_array[2] = third; // strcpy(my_word_array[3], "4"); printf("The words are: %s %s %s. \n", my_word_array[0], my_word_array[1], my_word_array[2]); }
dan-seol/C
q1a_simple_diamond.c
<reponame>dan-seol/C<filename>q1a_simple_diamond.c #include <stdio.h> #include <stdlib.h> // Used for atoi() function #include <string.h> // Used for strlen() function #include <math.h> #define TRUE 1 #define FALSE 0 void line(int n, int m){ for(int i=0; i<n; i++){ if((n/2)-(m) < i && i <= n/2){ printf("*"); } else if(n/2< i && i < (n/2 +m) ){ printf("*"); } else { printf(" "); } } printf("\n"); } void diamond(int n) { for(int i = 1; i <=(n/2)+1; i++){ line(n, i); } for(int j = n/2; j >=1; j--){ line(n, j); } } int main(int argc, char *argv[]) { //case separated when there are zero arguments if( argc > 2 ) { printf("ERROR: Wrong number of arguments. One required\n"); return 1; } else if (argc < 2){ printf("ERROR: Wrong number of arguments. One required\n"); return 1; } else { int n = (int) strtol(argv[1], NULL, 10); if(n % 2 == 0 ){ printf("ERROR: Bad argument. Height must be positive odd integer \n"); return 1; } printf("%d\n", n); diamond(n); } }
dan-seol/C
midQ7.c
<gh_stars>0 #include <stdio.h> int main(void) { int i=2; int x =3; while(1){ x = x+x; break; } for(i = i+i; i<x; x++){ i = i+i; } printf("%d %d\n", x, i); return 0; }
dan-seol/C
LARA/linked.h
<filename>LARA/linked.h #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct ACCOUNT { int accountNumber; float balance; struct ACCOUNT *next; } ACCOUNT; static ACCOUNT *head = NULL; static ACCOUNT *tail = NULL; void findUpdate(int account, float amount) { //you mean float amount, right? ACCOUNT *current = (ACCOUNT *) malloc(sizeof(ACCOUNT)); if(head == NULL ){ current->accountNumber = account; current->balance = amount; current->next = NULL; head = current; tail = current; } else { current=head; while(current != NULL) { if(current->accountNumber == account){ current->balance += amount; return; } if(current->next == NULL){ ACCOUNT *newAccount = (ACCOUNT*) malloc(sizeof(ACCOUNT)); newAccount->accountNumber = account; newAccount->balance = amount; newAccount->next = NULL; current->next = newAccount; return; } current = current->next; } } } void prettyPrint() { ACCOUNT *current = head; printf("######################### ACCOUNT RECORDS BELOW #########################\n"); while(current != NULL) { printf("[ ACCOUNT ID: %-5d BALANCE: $ %-6.2f ]\n", current->accountNumber, current->balance); current = current->next; } printf("######################### ACCOUNT RECORDS ABOVE #########################\n"); }
dan-seol/C
memsetTest.c
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char* argv[]){ if(argc != 3){ printf("ERROR: please type in a string and a positive integer\n"); return 0; } int arg2 = atoi(argv[2]); if(arg2 <1 ){ printf("ERROR: please type in a strictly positive integer\n"); return 0; } if(strlen(argv[1]) < arg2){ printf("ERROR: your integer is longer than your string\n"); return 0; } char str[256]; printf("Here is your string\n"); strcpy(str, argv[1]); puts(str); printf("I am going to change the first %d characters of your string into a dollar sign\n", arg2); memset(str, '$', arg2); puts(str); return 0; }
dan-seol/C
strCmpTest.c
#include <stdio.h> #include <string.h> //strcmp() : Compares the ascii value of the first unmatched character //Compares two strings int main(int argc, char* argv[]){ if(argc != 3){ printf("ERROR: please type in a string and a positive integer\n"); return 0; } char s1[256]; char s2[256]; strcpy(s1, argv[1]); strcpy(s2, argv[2]); int ret = strcmp(s1, s2); if(ret < 0) { printf("s1 is less than s2\n"); return 1; } else if(ret > 0) { printf("s2 is less than s1\n"); return 1; } else { printf("s1 is equal to s2\n"); return 1; } }
dan-seol/C
stringLen.c
<filename>stringLen.c #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]){ for(int i = 1; i< argc; i++){ int length = 0; char* pos = argv[i]; while(*pos){ // the pointer towards \0 gets to be evaluated as zero pos++; length++; } printf("The %d-th string %s has length %d. \n", i, argv[i], length); } }
dan-seol/C
sorting_exercise_starter.c
/* FILE: sorting_excersize_starter.c * * Please fill this in with some code to sort. You can use the * linear sort algorithm suggested on the Lecture 6 slides * or something you learned in a previous course. * Good luck! * * Author: <NAME> * Date: Sept 19, 2018 */ #include <stdio.h> int main(){ int array[4]; array[0] = 4; array[1] = 2; array[2] = 1; array[3] = 3; // Write your code here, try to sort the array for(int i=0; i<4; i++){ int min = array[i]; for(int j=i+1; j<4; j++){ if(min > array[j]){ array[i] = array[j]; array[j] = min; min = array[i]; } } } printf( "The array holds: " ); for( int i=0; i<4; i++ ) printf( "%d ", array[i] ); printf("\n"); printf( "If you coded it correctly, you should see 1 2 3 4\n"); return 0; }
dan-seol/C
arithmetictest.c
<gh_stars>0 #include <stdio.h> #include <math.h> int power2(int m){ if(m==0){ return 1; } else if (m < 0) { // positive integer assumes printf("This functions is defined for nonnegative integers only"); return -1; } else { return 2*power2(m-1); } } int main(void){ int n = 5; printf("%d\n", n/2); int m= 9; printf("%f %d\n",log2(m), (int)(log2(m))); printf("%d\n", (log2(m) - (int)log2(m) ==0)); printf("%d\n", power2(0)); printf("%d\n", power2(2)); printf("%d\n", power2(3)); }
dan-seol/C
countChar.c
#include <stdio.h> int main(int argc, char *argv[]){ char s[100] = "Rahman"; char t[100]; int a = 0; int b = 0; printf("Type in a word:"); fgets(t, 99, stdin); while(s[a] != '\0'){ a++; } while(t[b] != '\0'){ b++; } printf("The word \'Rahman\' has %d characters\n", a); printf("The word you typed has %d characters", b-1); return 0; }
dan-seol/C
LARA/reverse.c
#include <stdio.h> int getLength(char* str) { int length = 0; char* pos = str; while (*pos) { //Every string in C is stored as an array of char's. e.g. "Hello" is stored as {'H', 'E', 'L', 'L', 'O', '\0'}. //Something to take away is that the pointer (in our case, it will be *pos) towards '\0' will be evaluated as zero. pos++; length++; } return length; } int main(int argc, char* argv[]){ if(argc !=3){ printf("Wrong number of arguments. Please input: ./reverse WORD1 WORD2\n"); return 1; } else { int length1 = getLength(argv[1]); int length2 = getLength(argv[2]); int numberOfMatchingCharacters = 0; char word1[1024]; char word2[1024]; char word2flipped[1024]; for(int l1 = 0; l1 <length1+1; l1++){ word1[l1] = argv[1][l1]; } for(int l2 = 0; l2< length2+1; l2++){ word2[l2] = argv[2][l2]; } for(int i = 0; i<length2; i++){ word2flipped[i] = word2[length2-1-i]; } word2flipped[length2] = '\0'; if(length1 != length2){ printf("WORD1=%s WORD2=%s - NOT REVERSE", word1, word2); return 0; } else { for(int j=0; j<length1; j++){ if(word1[j]==word2flipped[j]){ numberOfMatchingCharacters++; } } if(numberOfMatchingCharacters==length1){ printf("WORD1=%s WORD2=%s - REVERSE", word1, word2); return 0; } else { printf("WORD=%s WORD2=%s - NOT REVERSE", word1, word2); return 0; } } } }
dan-seol/C
countLn.c
#include <stdio.h> /* count characters in input; 2nd version */ int main(int argc, char* argv[]){ int c, n1; n1 = 0; while ((c = getchar()) != EOF) { if(c == '\n'){ ++n1; } printf("%d\n", n1); } return 0; }
dan-seol/C
wFile.c
#include <stdio.h> #include <stdlib.h> int main () { FILE * fp; fp = fopen ("file.txt", "w+"); fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012); fclose(fp); return(0); }
dan-seol/C
FC_constant.c
<filename>FC_constant.c #include <stdio.h> #define LOWER 0 #define UPPER 300 #define STEP 20 int main(void){ float F, C; int lower, upper, step; F = LOWER; while(F <= UPPER){ C = (5.0/9.0)*(F-32); printf("%3.2f\t%3.3f\n", F, C); F += STEP; } }
dan-seol/C
FC_float.c
#include <stdio.h> int main(void){ float F, C; int lower, upper, step; lower = -20; upper = 300; step = 20; F = lower; while(F <= upper){ C = (5.0/9.0)*(F-32); printf("%3.2f\t%3.0f\n", F, C); F += step; } }
dan-seol/C
LARA/main.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "ssv.h" #include "linked.h" #define SIZE 1024 int main(){ int *idTracker = (int*) malloc(sizeof(int)); float *balanceTracker = (float*) malloc(sizeof(float)); FILE *fp = fopen("students.ssv", "r"); char record[SIZE]; while(fgets(record, 2*SIZE, fp) != NULL) { parse(record, idTracker, balanceTracker); printf("%d %f\n", *idTracker, *balanceTracker); //*idTracker=3; //*balanceTracker=20.0; findUpdate(*idTracker, *balanceTracker); } prettyPrint(); return 0; }
dan-seol/C
howLarge.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main () { FILE *fp = fopen("file.txt","r"); size_t sz; fseek(fp, 0L, SEEK_END); sz = ftell(fp); rewind(fp); char file_data_array[sz+1]; fread(file_data_array, 1, sz+1, fp); printf("File contents:\n%s\n", file_data_array); printf("%lu\n", strlen(file_data_array)); for(int pos = 0; pos<sz+1; pos++){ printf("Character %d has AASCI value %d.\n", pos, file_data_array[pos]); } while(fgetc(fp) !=EOF){ printf("I read the character %c. \n", fgetc(fp)); } printf("%lu\n", strlen("We are in 2012")); return(0); }
dan-seol/C
midQ5.c
#include <stdio.h> void swap(int* i, int* j){ int k; k = *i; *i = *j; *j = k; } int main(void){ int a =2; int b= 3; int *temp = &a; swap(temp, &b); printf("%d %d %d \n", a, b, *temp); return 0; }
dan-seol/C
countLine.c
<reponame>dan-seol/C<filename>countLine.c<gh_stars>0 #include <stdio.h> #include <stdlib.h> #define BUFFSIZE 1024 int countlines( FILE *fin) { int nlines = 0; char line[BUFFSIZE]; while(fgets(line, BUFFSIZE, fin) != NULL) { nlines++; } return nlines; } int main(int argc, char *argv[]) { FILE *file; file = fopen("test.txt", "r"); printf("The number of lines in the test.txt would be %d\n", countlines(file)); }
TheDukeFamily/EnableAudioVideo
playVideo/playVideo/GGStartMovieHelper.h
<filename>playVideo/playVideo/GGStartMovieHelper.h<gh_stars>0 // // GGStartMovieHelper.h // playVideo // // Created by Mac on 2018/6/11. // Copyright © 2018年 Mr.Gao. All rights reserved. // #import <Foundation/Foundation.h> @interface GGStartMovieHelper : NSObject + (instancetype)shareInstance; + (void)showStartMovieWithURL:(NSURL *)URL; @end
TheDukeFamily/EnableAudioVideo
playVideo/playVideo/UIImage+LaunchImage.h
<reponame>TheDukeFamily/EnableAudioVideo // // UIImage+LaunchImage.h // StartAppWithLaunchMovie // // Created by 邓法芝 on 2017/7/8. // Copyright © 2017年 邓法芝. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (LaunchImage) + (instancetype)getLaunchImage; @end
TheDukeFamily/EnableAudioVideo
playVideo/playVideo/GGStartMovieView.h
// // GGStartMovieView.h // playVideo // // Created by Mac on 2018/6/11. // Copyright © 2018年 Mr.Gao. All rights reserved. // #import <UIKit/UIKit.h> @interface GGStartMovieView : UIView + (instancetype)movieView; @property (nonatomic,strong) NSURL *movieURL; @end
KentWind/TX23-UReadings
internetConn.h
<gh_stars>1-10 #ifndef internetConn_h #define internetConn_h /* Circuit: Ethernet shield attached to pins 10, 11, 12, 13 */ #include <SPI.h> #include <Ethernet.h> // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): class internetConn{ public: void startConn(); void maintainConn(); void printIPAddress(); private: }; #endif
KentWind/TX23-UReadings
TX23Manipulations.h
<filename>TX23Manipulations.h #ifndef TX23manipulations_h #define TX23manipulations_h #include <LaCrosse_TX23.h> class TX23manipulations{ public: float metersToMiles(float speed); float getMeterToMile(); void printTX23Data(LaCrosse_TX23 anemometer); int getDir(); int getSpeed(); private: const float meterToMile = 2.2369; int theDirection; float theSpeed; }; #endif
abakobo/monkey2
modules/steamworks/marshal.h
<filename>modules/steamworks/marshal.h #ifndef MARSHAL_H #define MARSHAL_H #include <bbmonkey.h> #include <steam_api.h> //public delegate void SteamAPI_LeaderboardFindResult_t_CallResult(LeaderboardFindResult_t pLeaderboardFindResult_t, bool bIOFailure); enum SteamEventType{ StatsReceived, StatsStored, LeaderboardFound, LeaderboardUploaded, LeaderboardDownload, AchievementAwarded, AchievementStored, PlayersCounted, All }; class Marshal : public bbObject { public: UserStatsReceived_t userStatsReceived; UserStatsStored_t userStatsStored; UserAchievementStored_t userAchievementStored; LeaderboardFindResult_t leaderboardFindResult; LeaderboardScoreUploaded_t leaderboardScoreUploaded; LeaderboardScoresDownloaded_t leaderboardScoresDownloaded; NumberOfCurrentPlayers_t numberOfCurrentPlayers; Marshal(); virtual ~Marshal(); void gcMark(); STEAM_CALLBACK( Marshal, ReceivedUserStats, UserStatsReceived_t, m_ReceivedUserStats); STEAM_CALLBACK( Marshal, StoredUserStats, UserStatsStored_t, m_StoredUserStats); STEAM_CALLBACK( Marshal, StoredUserAchievement, UserAchievementStored_t, m_StoredUserAchievement); CCallResult<Marshal,UserStatsReceived_t> m_callResultStatsReceived; void ReceivedUserStats(UserStatsReceived_t *p, bool b); CCallResult<Marshal,LeaderboardFindResult_t> m_callResultFindLeaderboard; void FoundLeaderboard(LeaderboardFindResult_t *p, bool b); CCallResult<Marshal,LeaderboardScoreUploaded_t> m_callResultScoreUploaded; void ScoreUploaded(LeaderboardScoreUploaded_t *p, bool b); CCallResult<Marshal,LeaderboardScoresDownloaded_t> m_callResultScoresDownloaded; void ScoresDownloaded(LeaderboardScoresDownloaded_t *p, bool b); CCallResult<Marshal,NumberOfCurrentPlayers_t> m_callResultCountPlayers; void CountedPlayers(NumberOfCurrentPlayers_t *p, bool b); void SetEventHandler(SteamEventType steamEvent, int callback); void SetCallHandler(SteamEventType steamEvent, SteamAPICall_t steamAPICall, int callback); private: int eventCallback[SteamEventType::All]; }; #endif // MARSHAL_H
abakobo/monkey2
modules/m2conio/native/posix_input.h
#ifndef POSIX_INPUT_H #define POSIX_INPUT_H int getch(void); int kbhit(void); #endif
houbin/alarm
public/user_interface_defines.h
#ifndef user_interface_defines_h__ #define user_interface_defines_h__ #ifdef WIN32 #include <winsock2.h> #include <windows.h> #endif #include <string> #include <vector> #include <string.h> #include <time.h> #include <stdint.h> /** * @brief 用户基本信息 */ typedef struct userInfo_ { std::string username; std::string security_mail; //... }USER_INFO; typedef struct LOGIN_INFO { std::string login_platform; std::string moblie_id; std::string language_type; }C_LOGIN_INFO; enum OnlineStatus { OFFLINE = 0, ONLINE, }; enum alarmflag { ALARM_ON = 0, ALARM_OFF = 1, }; enum CommonStatus { UNKNOWN = -1, }; enum PwdLevel { PWD_LOW = 0, PWD_HIGH = 1, }; typedef struct clientPlatformInfo_ { int terminal_type; //登录平台类型 int language_type; //语言类型 std::string moblie_id; //手机唯一识别符 clientPlatformInfo_() { terminal_type = UNKNOWN; language_type = UNKNOWN; } } CLIENT_PLATFORM_INFO; /* 用户信息表 */ typedef struct AccountInfo { std::string username; std::string mail; std::string phone; std::string nickname; }AccountInfo; /* 客户端版本信息 */ typedef struct SoftVersionInfo { std::string soft_version; std::string soft_version_addr; std::string soft_version_desp; }SoftVersionInfo; #define STR_PTCP_HAS_CLOSED "TCP_CLOSED" #define STR_PTCP_HAS_ERROR "TCP_ERROR" enum PushMessage { NOTIFY_OFFLINE_ = 3102, PTCP_ERROR = 3103, PTCP_CLOSED = 3104, }; /** * @brief 设备信息 */ enum DeviceType { DEV_TYPE_UNKNOWN = 0, DEV_TYPE_IPC = 1, DEV_TYPE_HOME_IPC = 2, DEV_TYPE_DVR = 3, DEV_TYPE_NVR = 4, DEV_TYPE_JNVR = 5, DEV_TYPE_CARD = 6, }; enum DeviceSubType { DEV_TYPE_SUB_UNKNOWN = 0, DEV_TYPE_IPC_H200 = 1, DEV_TYPE_IPC_H400 = 2, DEV_TYPE_IPC_E2 = 3, DEV_TYPE_IPC_E2_0130 = 31, }; typedef struct deviceInfo_ { std::string device_guid; // 设备guid(云视通号) int device_type; // 设备类型 0-未知 1-DVR 2-IPC int device_sub_type; // 设备型号id std::string device_sub_type_str;// 字符串型号 std::string device_version; // 设备软件版本 std::string device_username; // 设备用户名 std::string device_password; // <PASSWORD> std::string device_name; // 设备昵称 std::string device_ip; // 设备ip int device_netstat; // IPC网络状态,0-有线连接,1-wifi连接 int net_storage_switch; // 云存储开关,0-关闭,1-打开 int tf_storage_switch; // TF存储开关 int alarm_switch; // 告警开关,0-关闭,1-打开 std::string alarm_video_ftp_url;// 告警录像的ftp上传路径 std::string alarm_snap_ftp_url; // 告警抓拍图的ftp上传路径 std::string alarm_ftp_acc; // 告警FTP的用户名 std::string alarm_ftp_pwd; // 告警FTP的密码 std::string alarm_time; // 安全防护时间段 格式hh,hh std::string jpeg_ftp_url_big; // 场景大图ftp路径 std::string jpeg_ftp_url_small; // 场景小图ftp路径 std::string jpeg_ftp_acc; // 场景图ftp用户名 std::string jpeg_ftp_pwd; // 场景图ftp密码 int jpeg_upload_timing; // 场景图上传时间间隔 单位sec int video_fluency; // 视频流畅度,0-标清,1-高清,2-流畅 int baby_mode; // baby模式 0-关闭,1开启 int full_alarm_mode; // 全监控模式 0-关闭,1开启 int online_status; // (1在线 0离线) int humiture_flag; // 是否支持温湿度 0-不支持 1-支持 struct tm timestamp; // 时间戳 double temperature; // 温度 double humidity; // 湿度 int reset_flag; // 出厂设置标识 1为出厂状态 0非出厂状态 int device_verify; // 设备用户名密码校验0成功 -1失败 deviceInfo_() { device_type = 0; device_sub_type = 0; device_netstat = 0; net_storage_switch = 0; tf_storage_switch = 0; alarm_switch = 0; jpeg_upload_timing = 0; video_fluency = 0; baby_mode = 0; full_alarm_mode = 0; humiture_flag = 0; memset(&timestamp, 0, sizeof (timestamp)); temperature = 0; humidity = 0; reset_flag = -1; device_verify = 0; } }DEVICE_INFO; /** * @brief 用户自身配置的设备信息 */ typedef struct user_device_config_ { std::string user_name; // 用户名 std::string device_guid; // 设备GUID int video_link_type; // 视频连接模式 0-云视通,1-IP端口 std::string video_username; // 云视通连接模式 用户名 std::string video_password; // 云视通连接模式 密码 std::string video_ip; // 普通连接模式 IP int video_port; // 普通连接模式 端口 int device_verify; // 设备用户名密码校验0成功 -1失败 int device_permission; // 用户的设备权限 user_device_config_() { video_link_type = 0; video_port = 0; device_verify = 0; device_permission = 0; } }USER_DEVICE_CONFIG; /** * @brief 用户设备信息 */ typedef struct user_device_info_ { DEVICE_INFO device_info; USER_DEVICE_CONFIG user_device_config; }USER_DEVICE_INFO; /** * @brief 设备信息列表 */ typedef struct devicesList_ { std::vector<DEVICE_INFO> vec_device_info; }DEVICES_LIST; /** * @brief 用户-设备信息列表 */ typedef struct userDevicesList_ { std::vector<USER_DEVICE_INFO> vec_user_device_info; }USER_DEVICES_LIST; /** * @brief 设备环境信息(温湿度) */ typedef struct device_environment_info_ { std::string device_guid; struct tm timestamp; double temperature; double humidity; int score; int assessment; device_environment_info_() { memset(&timestamp, 0, sizeof (struct tm)); temperature = 0; humidity = 0; score = 0; assessment = 0; } bool operator>(const device_environment_info_ &denvinfo) const { return score > denvinfo.score; } }DEVICE_ENV_INFO; typedef struct humiture_statistics_info_ { std::string device_guid; std::string date; int hour; double statTemperature; double statHumidity; int score; int assessment; humiture_statistics_info_() { hour = 0; statTemperature = 0; statHumidity = 0; score = 0; assessment = 0; } }HUMITURE_STAT_INFO; /** * @brief 设备升级文件信息 */ typedef struct updateFileInfo_ { std::string update_version; std::string file_url; int file_size; std::string file_checksum; std::string file_description; }UPDATE_FILE_INFO; /** * @brief 设备通道信息 */ typedef struct deviceChannelInfo_ { int channel_no; int channel_permission; std::string channel_name; }DEVICE_CHANNEL_INFO; /** * @brief 报警消息 */ typedef struct alarmInfo_ { std::string alarm_guid; std::string device_guid; int alarm_type; std::string alarm_pic_url; uint32_t alarm_pic_size; std::string alarm_video_url; uint32_t alarm_video_size; alarmInfo_() { alarm_type = 0; alarm_pic_size = 0; alarm_video_size = 0; } }ALARM_INFO; enum IReturnCode { SUCCESS = 0, FAILED = -1, USER_HAS_EXIST = 2, USER_NOT_EXIST = 3, PASSWORD_ERROR = 4, SESSION_NOT_EXSIT = 5, SQL_NOT_FIND = 6, PTCP_HAS_CLOSED = 7, LOW_STRENGTH_PASSWORD = <PASSWORD>, //低强度密码用户 HIGH_STRENGTH_PASSWORD = <PASSWORD>, //高强度密码用户 /** DeviceRegisterResponse */ DEVICE_HAS_EXIST = 8, DEVICE_NOT_EXIST = 9, DEVICE_NOT_BIND = 10, DEVICE_HIS_NOT_EXIST = 11, DEVICE_HUMITURE_NOT_EXIST = 12, DEVICE_CONF_NOT_SET = 13, DEVICE_HAS_NO_UPDATE = 14, DEVICE_IS_RESET = 15, DEVICE_HUM_NOT_SUPPORT = 16, DEVICE_HAS_BIND = 17, GENERATE_PASS_ERROR = -2, REDIS_OPT_ERROR = -3, MY_SQL_ERROR = -4, REQ_RES_TIMEOUT = -5, CONN_OTHER_ERROR = -6, CANT_CONNECT_SERVER = -7, JSON_INVALID = -8, REQ_RES_OTHER_ERROR = -9, JSON_PARSE_ERROR = -10, SEND_MAIL_FAILED = -11, DEVICE_UPDATE_ERROR = -12, DEVICE_VERIFY_FAILED = -13, DEVICE_NOT_ONLINE = -14, ACCOUNTNAME_INVALID = -15, ACCOUNTNAME_OTHER = -16, PASSWORD_DANGER = -17, NEED_UPDATE = -18, RELAY_ERROR = -19, DEVICE_RESULT_ERROR = -20, OTHER_ERROR = -1000, }; enum HumitureAssessment { HUMITURE_OK = 0, TEMPERATURE_TOO_HIGH = 1, TEMPERATURE_TOO_LOW = 2, HUMIDITY_TOO_HIGH = 4, HUMIDITY_TOO_LOW = 8, }; #endif // user_interface_defines_h__
houbin/alarm
userOnline/src/user_alive.h
<filename>userOnline/src/user_alive.h #ifndef DEVICE_ALIVE_H_ #define DEVICE_ALIVE_H_ #include "push_msg_queue.h" #include "../../util/http_client.h" extern PushMsgQueue *g_msg_push_queue; extern HttpClient *g_http_client; extern void ClearGuidFdCache(); extern int StartHttpClient(); #endif
houbin/alarm
voice_server/include/socket_wrapper.h
<gh_stars>0 /** * @created: 2012/05/18 * * @file socket_wrapper.h * * @author <NAME> <<EMAIL>> * * @version 1.0 * * @LICENSE * * @brief 对socket操作的封装处理 * */ #ifndef SOCKET_WRAPPER_H__ #define SOCKET_WRAPPER_H__ #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <netinet/tcp.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <time.h> #include <assert.h> #include <string> #define BACKLOG 50 namespace SocketOperate { /** * @brief 设置socket为非阻塞 * @param [in] * @return If successful true is returned, if not false is returned. */ static inline bool SetSocketNoBlock(const int sock_fd) { int flags = fcntl(sock_fd, F_GETFL, 0); if(-1 == flags) { return false; } flags |= O_NONBLOCK; if(-1 == fcntl(sock_fd, F_SETFL, flags)) { return false; } return true; } /** * @brief 关闭socket * @param [in] * @return If successful true is returned, if not false is returned. */ static inline bool CloseSocket(const int sock_fd) { if(sock_fd < 0) return true; if(shutdown(sock_fd, SHUT_WR) < 0) { //log } if(close(sock_fd) < 0) return false; return true; } static inline bool WriteSfd(const int sfd, const char* buf, const int buf_len) { int msg_len = buf_len, send_ret = 0; const char *send_data = buf; time_t first_time = 0; while (msg_len > 0) { send_ret = send(sfd, send_data, msg_len, MSG_NOSIGNAL); //发送成功,则把相应标志位设置为0 if (send_ret >= msg_len) { break; } //没有发送完,则继续发送 else if (send_ret > 0) { msg_len -= send_ret; send_data += send_ret; continue; } //发送失败 else { //系统调用失败或发送缓冲区满需要继续发送该消息 if ((errno == EINTR) || (errno == EAGAIN)) { if (first_time == 0) { first_time = time(NULL); } else { if ((time(NULL) - first_time) > 3) { return false; } } continue; } } return false; } return true; } /** * @brief 通过sockaddr_in结构信息得到主机port * @param [in] * @return int 主机类型 port */ static inline int GetHostPort(const sockaddr_in sock_addr_in) { return ntohs(sock_addr_in.sin_port); } /** * @brief 通过sockaddr_in结构信息得到主机ip * @param [in] * @return string 主机类型 ip地址 */ static inline std::string GetHostAddr(const sockaddr_in* sock_addr_in) { char ip_buf[32]; std::string stradd = ::inet_ntop(AF_INET, &sock_addr_in->sin_addr, ip_buf, sizeof(ip_buf)); return stradd; } }; #endif
houbin/alarm
userOnline/src/json_opt.h
/* * json_opt.h * * Created on: Mar 6, 2013 * Author: yaowei */ #ifndef JSON_OPT_H_ #define JSON_OPT_H_ #include "libjson/libjson.h" #include "libjson/_internal/Source/JSONNode.h" #include "../../public/user_interface_defines.h" #include "defines.h" using namespace std; class CJsonOpt { public: CJsonOpt(); virtual ~CJsonOpt(); void setJsonString(const std::string &msg); int GetMethod(string &method); int GetMid(); bool VerifyJsonField(const string &field); bool JsonParseCommon(); int JsonParseBeacon(string &session_id); int JsonParsePushMsg(string &guid); // 推送消息的回复消息 int JsonParsePushMsgResp(int &ret); public: bool JsonJoinCommon(string method, int ret = 0); string JsonJoinBeaconRes(int ret = 0); string JsonJoinPushMsgToClient(int push_mid); string JsonJoinPushMsgRes(int mid, int result); string JsonJoinUserLogout(int mid, string session); //for test //string JsonJoinUserLogin(); private: bool JsonParseField(const string &field); private: std::string json_string_; JSONNode in_; JSONNode out_; unsigned int mid_; string method_; }; #endif /* JSON_OPT_H_ */
houbin/alarm
voice_server/util/clock.h
<gh_stars>0 #ifndef UTIL_CLOCK_H_ #define UTIL_CLOCK_H_ #include "utime.h" namespace util { extern UTime GetClockNow(); } #endif
houbin/alarm
voice_server/util/utime.h
#ifndef UTIL_UTIME_H_ #define UTIL_UTIME_H_ #include <sys/time.h> #include <math.h> #include <stdint.h> namespace util { class UTime { public: uint32_t tv_sec; uint32_t tv_nsec; bool IsZero() { return ((tv_sec == 0) && (tv_nsec == 0)); } void normalize() { if (tv_nsec > 1000000000ul) { tv_sec += (tv_nsec / 1000000000ul); tv_nsec = tv_nsec % 1000000000ul; } } UTime() { tv_sec = 0; tv_nsec = 0;} UTime(uint32_t s) { tv_sec = s; tv_nsec = 0;} UTime(uint32_t s, uint32_t n) { tv_sec = s; tv_nsec = n; normalize(); } UTime(struct timeval &time) { tv_sec = time.tv_sec; tv_nsec = (time.tv_usec * 1000); } UTime(struct timespec &time) { tv_sec = time.tv_sec; tv_nsec = time.tv_nsec; } UTime(const UTime &time) { tv_sec = time.tv_sec; tv_nsec = time.tv_nsec; } UTime& operator=(const UTime& time) { this->tv_sec = time.tv_sec; this->tv_nsec = time.tv_nsec; return *this; } UTime& operator+=(const UTime &time) { this->tv_sec += time.tv_sec; this->tv_nsec += time.tv_nsec; normalize(); return *this; } UTime& operator+=(const double f) { double fs = trunc(f); double ns = (f - fs) * (double)1000000000.0; this->tv_sec += fs; this->tv_nsec += ns; normalize(); return *this; } UTime& operator-=(const UTime &time) { this->tv_sec = this->tv_sec - time.tv_sec - (this->tv_nsec < time.tv_nsec ? 1 : 0); this->tv_nsec = (this->tv_nsec < time.tv_nsec) ? (this->tv_nsec + 1000000000ul - time.tv_nsec) : (this->tv_nsec - time.tv_nsec); return *this; } void ToTimeSpec(struct timespec *ts) const { ts->tv_sec = tv_sec; ts->tv_nsec = tv_nsec; } }; inline UTime operator+(const UTime &l, const UTime &r) { return UTime(l.tv_sec + r.tv_sec, l.tv_nsec + r.tv_nsec); } inline UTime operator-(const UTime &l, const UTime &r) { return UTime(l.tv_sec - r.tv_sec - (l.tv_nsec < r.tv_nsec ? 1 : 0), (l.tv_nsec < r.tv_nsec) ? (l.tv_nsec + 1000000000ul - r.tv_nsec) : (l.tv_nsec - r.tv_nsec)); } inline bool operator>(const UTime &a, const UTime &b) { return (a.tv_sec > b.tv_sec) || ((a.tv_sec == b.tv_sec) && (a.tv_nsec > b.tv_nsec)); } inline bool operator<(const UTime &a, const UTime &b) { return ((a.tv_sec < b.tv_sec) || ((a.tv_sec == b.tv_sec) && (a.tv_nsec < b.tv_nsec))); } inline bool operator==(const UTime &a, const UTime &b) { return ((a.tv_sec == b.tv_sec) && (a.tv_nsec == b.tv_nsec)); } inline bool operator>=(const UTime &a, const UTime &b) { return !(operator<(a, b)); } inline bool operator<=(const UTime &a, const UTime &b) { return !(operator>(a, b)); } inline bool operator!=(const UTime &a, const UTime &b) { return !(operator==(a, b)); } } #endif
houbin/alarm
voice_server/util/logger.h
<reponame>houbin/alarm<filename>voice_server/util/logger.h<gh_stars>0 #ifndef UTIL_LOGGER_H_ #define UTIL_LOGGER_H_ #include <stdio.h> #include <string.h> #include <string> #include <sys/time.h> #include <time.h> #include <stdint.h> #include <pthread.h> #include <stdarg.h> #include <assert.h> #include <boost/scoped_ptr.hpp> #include "env.h" #include "mutex.h" #include "utime.h" #include "clock.h" #include "env_posix.h" #define __STDC_FORMAT_MACROS #include <inttypes.h> using namespace std; namespace util { enum LogLevel { TRACE = 0, DEBUG = 1, INFO = 2, WARN = 3, ERROR = 4, FATAL = 5, NUM_LOG_LEVELS, }; class Logger { private: string log_dir_; const size_t roll_size_; const int check_every_n_; const static int kRollPerSeconds_ = 24 * 60 * 60; int count_; boost::scoped_ptr<PosixWritableFile> file_; time_t last_roll_; static LogLevel g_log_level; Mutex mutex_; public: Logger(const string& log_dir, size_t roll_size = 100 * 1024 * 1024, bool threadsafe = true, int check_every_n = 1024); ~Logger(); void Logv(const char* format, va_list ap); void Append(const Slice &data); bool RollFile(); static string GetLogFileName(const string& log_dir, time_t *now); static LogLevel GetLogLevel(); static int32_t SetLogLevel(LogLevel level); }; int32_t NewLogger(const char* name, Logger **logger); void LogFunc(Logger *info_log, const char* format, ...); #define Log(info_log, format, ...) LogFunc(info_log, "[%s:%s:%d]: "format, __FILE__, __func__, __LINE__, ##__VA_ARGS__) #define LOG_TRACE(info_log, format, ...) if (util::Logger::GetLogLevel() <= TRACE) \ LogFunc(info_log, "[%s:%s:%d]: "format, __FILE__, __func__, __LINE__, ##__VA_ARGS__) #define LOG_DEBUG(info_log, format, ...) if (util::Logger::GetLogLevel() <= DEBUG) \ LogFunc(info_log, "[%s:%s:%d]: "format, __FILE__, __func__, __LINE__, ##__VA_ARGS__) #define LOG_INFO(info_log, format, ...) if (util::Logger::GetLogLevel() <= INFO) \ LogFunc(info_log, "[%s:%s:%d]: "format, __FILE__, __func__, __LINE__, ##__VA_ARGS__) #define LOG_WARN(info_log, format, ...) if (util::Logger::GetLogLevel() <= WARN) \ LogFunc(info_log, "[%s:%s:%d]: "format, __FILE__, __func__, __LINE__, ##__VA_ARGS__) #define LOG_ERROR(info_log, format, ...) if (util::Logger::GetLogLevel() <= ERROR) \ LogFunc(info_log, "[%s:%s:%d]: "format, __FILE__, __func__, __LINE__, ##__VA_ARGS__) #define LOG_FATAL(info_log, format, ...) if (util::Logger::GetLogLevel() <= FATAL) \ LogFunc(info_log, "[%s:%s:%d]: "format, __FILE__, __func__, __LINE__, ##__VA_ARGS__) } #endif
houbin/alarm
userOnline/src/context.h
#ifndef UTIL_CONTEXT_H_ #define UTIL_CONTEXT_H_ namespace util { class Context { private: // no copying allowed Context(const Context& other); const Context& operator=(const Context& other); protected: virtual void Finish(int r) = 0; public: Context() {} virtual ~Context() { } virtual void Complete(int r) { Finish(r); delete this; } }; } #endif
houbin/alarm
voice_server/src/dispatcher.h
<reponame>houbin/alarm<gh_stars>0 #ifndef DISPATCHER_H_ #define DISPATCHER_H_ #include <stdint.h> #include <string> #include "global.h" #include "json_opt.h" #include "connection.h" #include "voice_channel.h" #include "push_msg_timer_queue.h" using namespace std; class PushMsgContext; struct ConnectionInfo; class Dispatcher { private: string data_protocol_; public: Dispatcher(string data_protocol); ~Dispatcher(); int32_t HandleConnect(ConnectionInfo *conn_info); int32_t HandleTimeout(ConnectionInfo *conn_info); int32_t HandleClose(ConnectionInfo *conn_info); int32_t HandleError(ConnectionInfo *conn_info); virtual int32_t HandleMsg(ConnectionInfo *conn_info, string &msg_info) = 0; //virtual int32_t HandleMsg(ConnectionInfo *conn_info, Slice &s) = 0; }; class JsonDispatcher : public Dispatcher { public: JsonDispatcher(); ~JsonDispatcher(); int32_t HandleMsg(ConnectionInfo *conn_info, string &msg_info); int32_t HandleGetVoiceServerAddr(ConnectionInfo *conn_info, CJsonOpt &json_opt); }; class TlvDispatcher : public Dispatcher { private: VoiceChannelManager vc_manager_; PushMsgTimerQueue push_msg_timer_queue_; public: TlvDispatcher(); ~TlvDispatcher(); int32_t HandleMsg(ConnectionInfo *conn_info, string &tlv_data); void EncodeCommonTlv(string *resp_msg, uint32_t msg_len, uint32_t mid); void EncodeRet(string *resp_msg, uint32_t on_cmd, int32_t ret); int32_t SendMsg(int fd, string msg); int32_t ForwardMsgToDev(int push_fd, uint32_t push_mid, string &push_msg, PushMsgContext *ct); void PackHeartBeatRespMsg(uint32_t mid, int32_t ret, string &resp_msg); int32_t HandleHeartbeat(ConnectionInfo *conn_info, uint32_t mid, Slice &s); void PackClientBuildVcRespMsg(uint32_t mid, int32_t ret, string &string_msg); int32_t HandleClientBuildVc(ConnectionInfo *conn_info, uint32_t mid, Slice &s); void PackStartSendPushMsg(string &push_msg, uint32_t &push_mid); int32_t HandleClientStartSend(ConnectionInfo *conn_info, uint32_t mid, Slice &s); void PackStartSendRespMsg(uint32_t mid, string &resp_msg, int32_t ret); int32_t HandleOnPushStartSend(ConnectionInfo *conn_info, uint32_t mid, Slice &s); void PackSendVoicePushMsg(string &push_msg, uint32_t &push_mid, Slice &s); int32_t HandleClientSendVoice(ConnectionInfo *conn_info, uint32_t mid, Slice &s); void PackClientSendVoiceRespMsg(uint32_t mid, string &resp_msg, int32_t ret); int32_t HandleOnPushClientVoice(ConnectionInfo *conn_info, uint32_t mid, Slice &s); void PackClientFreeVcRespMsg(uint32_t mid, string &resp_msg, int32_t ret); int32_t HandleClientFreeVc(ConnectionInfo *conn_info, uint32_t mid, Slice &s); // dev protocol void PackDevBuildVcRespMsg(uint32_t mid, string &resp_msg, int32_t ret); int32_t HandleDevBuildVc(ConnectionInfo *conn_info, uint32_t mid, Slice &s); void PackDevFreeVcRespMsg(uint32_t mid, string &resp_msg, int32_t ret); int32_t HandleDevFreeVc(ConnectionInfo *conn_info, uint32_t mid, Slice &s); }; #endif
houbin/alarm
voice_server/util/mutex.h
<gh_stars>0 #ifndef UTIL_MUTEX_H_ #define UTIL_MUTEX_H_ #include <pthread.h> namespace util { class Mutex { private: const char *name_; pthread_mutex_t m_; // no copying Mutex(const Mutex &); void operator=(const Mutex &); public: Mutex(const char *name); ~Mutex(); void Lock(); void Unlock(); friend class Cond; class Locker { private: Mutex &m_; public: Locker(Mutex& m) : m_(m) { m_.Lock(); } ~Locker() { m_.Unlock(); } }; }; } #endif
houbin/alarm
voice_server/src/connection.h
#ifndef TCP_SERVER_CONNECTION_H_ #define TCP_SERVER_CONNECTION_H_ #include <event.h> #include <string> #include "tlv_define.h" class Worker; struct ConnectionInfo { uint64_t conn_id; int cfd; std::string cip; uint16_t cport; struct bufferevent *buffer_event; char in_buffer[CONN_BUFFER_LEN]; uint16_t in_buffer_len; //char out_buffer[CONN_BUFFER_LEN]; //uint16_t out_buffer_len; Worker *worker; int guid_type; // client or dev string guid; // client or dev guid }; #endif
houbin/alarm
userOnline/src/worker_threads.h
<reponame>houbin/alarm<filename>userOnline/src/worker_threads.h /* * CThread.h * * Created on: Mar 4, 2013 * Author: yaowei */ #ifndef WORK_THREAD_H_ #define WORK_THREAD_H_ #include <vector> #include <boost/thread.hpp> #include "defines.h" #include "redis_opt.h" class CWorkerThread { public: CWorkerThread(); virtual ~CWorkerThread(); public: bool InitThread(struct event_base* main_base); static void DispatchSfdToWorker(int sfd, int id); private: bool SetupThread(LIBEVENT_THREAD* me); static void ThreadLibeventProcess(int fd, short event, void* arg); static conn *conn_new(const CQ_ITEM* item, LIBEVENT_THREAD* libevent_thread_ptr) ; static void CreateWorker(void *(*func)(void *), void *arg); static void *WorkerLibevent(void *arg); static void RegisterThreadInitialized(void); static void WaitForThreadRegistration(int nthreads); static void ConnQueueInit(CQ *cq); static CQ_ITEM * ConnQueueItemNew(void); static void ConnQueuePush(CQ *cq, CQ_ITEM *item); static CQ_ITEM* ConnQueuePop(CQ *cq); static void ConnQueueItemFree(CQ_ITEM *item); static void ClientTcpReadCb(struct bufferevent *bev, void *arg); static void ClientTcpErrorCb(struct bufferevent *bev, short event, void *arg); static void conn_init(void); static conn *conn_from_freelist(); static bool conn_add_to_freelist(conn *c); static void conn_free(conn *c); static void conn_close(conn *c, struct bufferevent *bev); private: static CRedisOpt* redisOpt_ptr_; static std::vector<LIBEVENT_THREAD*> vec_libevent_thread_; static int init_count_; static pthread_mutex_t init_lock_; static pthread_cond_t init_cond_; /* Free list of CQ_ITEM structs */ static CQ_ITEM *cqi_freelist; static pthread_mutex_t cqi_freelist_lock; static int last_thread; /* * Free list management for connections. */ static boost::mutex mutex_; static std::vector<conn*> vec_freeconn_; static int freetotal_; static int freecurr_; }; #endif /* CTHREAD_H_ */
houbin/alarm
public/utils.h
<reponame>houbin/alarm /** * @created: 2012/05/16 * * @file utils.h * * @author <NAME> <<EMAIL>> * * @version 1.0 * * @LICENSE * * @brief 通用工具方法 * */ #ifndef UTILS_H__ #define UTILS_H__ #include <netinet/in.h> #include <sys/time.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <unistd.h> #include <algorithm> #include <exception> #include <fstream> #include <iostream> #include <sstream> #include <vector> #include <set> #include <map> #include <boost/algorithm/string.hpp> #include <boost/regex.hpp> #include <uuid/uuid.h> using namespace std; namespace utils { static inline void ShellCommand(const char *command, char *buf, int length) { FILE *stream; stream = popen(command,"r"); fread( buf, sizeof(char), length, stream); pclose( stream ); return; } static inline void DeleteElementFrom(const std::string& value, std::vector<std::string>& vec) { std::vector<std::string>::iterator iter; for(iter = vec.begin(); iter != vec.end();) { if((*iter).compare(value) == 0) iter = vec.erase(iter); else ++iter; } } static inline void SplitData(const std::string& str, const std::string& delimiter, std::vector<std::string>& vec_data) { std::string s = str; size_t pos = 0; std::string token; while ((pos = s.find(delimiter)) != std::string::npos) { token = s.substr(0, pos); vec_data.push_back(token); s.erase(0, pos + delimiter.length()); } } static inline std::string ReplaceString(const std::string& str, const std::string& flag, const std::string& replaceFlag) { boost::regex expressionReplace(flag); std::string strTemp = boost::regex_replace(str, expressionReplace, replaceFlag); return strTemp; } static inline bool FindCRLF(const std::string& s) { if(s.find("\r\n") != std::string::npos) return true; else return false; } static inline std::vector<std::string> SplitString(const std::string& str, const std::string& delimiter) { std::vector<std::string> vec_temp; boost::algorithm::split(vec_temp, str, boost::algorithm::is_any_of(delimiter)); DeleteElementFrom("", vec_temp); return vec_temp; } static inline std::string JoinListByDelimiter(const std::vector<std::string>&vec, const std::string& delimiter) { std::string str; for(unsigned int i = 0; i < vec.size(); ++i) { str = str + vec.at(i) + delimiter; } return str; } static inline std::string JoinSetByDelimiter(const std::set<std::string>& set_string, const std::string& delimiter) { std::string str; std::set<std::string>::iterator iter; for(iter = set_string.begin(); iter != set_string.end(); ++iter) { str = str + *iter + delimiter; } return str; } template<typename K, typename V> inline void MapKeyToSet(const std::map<K, V>& map_temp, std::set<K>& set_temp) { typedef typename std::map<K, V>::const_iterator iter_temp; iter_temp iter; for(iter = map_temp.begin(); iter != map_temp.end(); ++iter) { set_temp.insert(iter->first); } } template<typename T> std::string toString(const T& value) { std::ostringstream oss; oss << value; return oss.str(); } static inline std::string int2str(int v) { std::stringstream ss; ss << v; return ss.str(); } static inline std::string NowtimeString() { std::time_t time_now = std::time(NULL); tm* tm_now = localtime(&time_now); char time_str[sizeof("yyyymmddhhmmss")] = {0}; std::strftime(time_str, sizeof(time_str), "%Y%m%d%H%M%S", tm_now); return time_str; } static inline std::string GetCurrentDayString() { time_t time_; struct tm *ptm; time_ = time(NULL); ptm = localtime(&time_); char temp[100] = { 0 }; snprintf(temp, sizeof(temp), "%d-%d-%d", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday); std::string str; str.assign(temp); return str; } static inline std::string GetCurrentTime() { std::time_t time_now = std::time(NULL); tm* tm_now = localtime(&time_now); char time_str[100] ={ 0 }; std::strftime(time_str, sizeof(time_str), "%Y年%m月%d日 %H:%M:%S", tm_now); return time_str; } static inline std::string GetMonthString(const std::string& month) { int mon = atoi(month.c_str()); switch(mon) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; default: break; } return NULL; } static inline unsigned long GetTickCount() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { //error } return (ts.tv_sec*1000 + ts.tv_nsec/(1000*1000)); } template<class T> class Singleton: private T { public: static T &Instance() { static Singleton<T> _instance; return _instance; } private: Singleton() { } ~Singleton() { } }; template<typename T> T& G() { return Singleton<T>::Instance(); } template<typename T> inline void SafeDeleteArray(T*& p) { if (NULL != p) { delete[] p; p = 0; } } template<typename T> inline void SafeDelete(T*& p) { if (NULL != p) { delete p; p = 0; } } static inline void Unicode2UTF8OneWord(std::string& obj) { int count = 0; int index = 0; while((index = int(obj.find("\\u00", index))) != int(std::string::npos)) { count++; index++; } char ch[count+1]; index = 0; std::string substr; for(int i = 0; i < count; i++) { index = obj.find("\\u00", index); index += 4; substr = obj.substr(index, 2); ch[i] = strtol(substr.c_str(), NULL, 16); } ch[count] = '\0'; obj = ch; } static inline void Unicode2UTF8(std::string& obj) { int beg = 0; std::string substr; while((beg = int(obj.find("\\u00", 0))) != int(std::string::npos)) { substr = obj.substr(beg, 18); Unicode2UTF8OneWord(substr); obj.replace(beg, 18, substr); } } static inline std::string encrypt(const char* ch) { char* p = (char*)ch; int i = 0; while(*p != '\0') *p++ ^= i++; std::string str = ch; return str; } static inline std::string decrypt(const char* ch) { char* p = (char*)ch; int i = 0; while(*p != '\0') *p++ ^= i++; std::string str = ch; return str; } } #endif
houbin/alarm
deviceOnline/src/test.h
#ifndef TEST_H_ #define TEST_H_ #include "thread.h" using namespace util; class TestThread : public Thread { private: public: TestThread() { } ~TestThread() { } void *Entry(); }; #endif
houbin/alarm
deviceOnline/src/defines.h
/* * defines.h * * Created on: 2012-9-12 * Author: yaowei */ #ifndef DEFINES_H_ #define DEFINES_H_ #include <assert.h> #include <string.h> #include <pthread.h> #include <stdlib.h> #include <errno.h> #include <arpa/inet.h> #include <boost/shared_ptr.hpp> #include <boost/thread.hpp> #include <boost/thread/thread.hpp> #include <log4cxx/logger.h> #include <log4cxx/logstring.h> #include <log4cxx/propertyconfigurator.h> using namespace log4cxx; extern LoggerPtr g_logger; #include <event.h> #include <semaphore.h> #include "threadSafe_map.h" #include <string> #include "../../public/redis_key.h" #define DATA_BUFFER_SIZE 30*1024 #define CRLF "\r\n" typedef struct { char buf[DATA_BUFFER_SIZE]; unsigned int len; int sfd; struct event_base *base; }LOCAL_REV_DATA; typedef struct conn_queue_item CQ_ITEM; struct conn_queue_item { int sfd; int id; CQ_ITEM *next; }; /* A connection queue. */ typedef struct conn_queue CQ; struct conn_queue { CQ_ITEM *head; CQ_ITEM *tail; pthread_mutex_t lock; pthread_cond_t cond; }; typedef struct { pthread_t thread_id; /* unique ID of this thread */ struct event_base *base; /* libevent handle this thread uses */ struct event notify_event; /* listen event for notify pipe */ int notify_receive_fd; /* receiving end of notify pipe */ int notify_send_fd; /* sending end of notify pipe */ struct conn_queue *new_conn_queue; /* queue of new connections to handle */ } LIBEVENT_THREAD; typedef struct conn conn; struct conn { int sfd; int id; char* rBuf; int rlen; char* wBuf; int wlen; bool isVerify; conn *next; /* Used for generating a list of conn structures */ LIBEVENT_THREAD *thread; /* Pointer to the thread object serving this connection */ bool is_login; bool is_online; std::string dev_id; }; #endif /* DEFINES_H_ */
houbin/alarm
userOnline/src/threadSafe_map.h
<reponame>houbin/alarm #ifndef THREAD_SAFE_MAP_H_ #define THREAD_SAFE_MAP_H_ #include <boost/thread.hpp> #include <map> template<typename K, typename V> class CThreadSafeMap { public: CThreadSafeMap() {} ~CThreadSafeMap() { if (!map_.empty()) { map_.clear(); } } void insert(const K& key, const V& value) { boost::mutex::scoped_lock oLock(mutex_); map_.insert(std::pair<K, V>(key, value)); } bool find(const K& key, V& value) { bool ret = false; boost::mutex::scoped_lock oLock(mutex_); if (map_.size() > 0) { typedef typename std::map<K, V>::iterator iter_thread; iter_thread iter= map_.find(key); if(iter != map_.end()) { value = iter->second; ret = true; } } return ret; } bool findValueByKey(const K& key, const V& value) { bool ret = false; boost::mutex::scoped_lock oLock(mutex_); if (map_.size() > 0) { typedef typename std::map<K, V>::iterator iter_thread; iter_thread iter = map_.find(key); if (iter != map_.end()) { if(value == iter->second) { ret = true; } } } return ret; } bool findAndSet(const K& key, const V& new_value, V& old_value) { bool ret = false; boost::mutex::scoped_lock oLock(mutex_); if (map_.size() > 0) { typedef typename std::map<K, V>::iterator iter_thread; iter_thread iter= map_.find(key); if(iter != map_.end()) { old_value = iter->second; map_.erase(iter); map_.insert(std::pair<K, V>(key, new_value)); ret = true; } } return ret; } void erase(const K& key) { boost::mutex::scoped_lock oLock(mutex_); map_.erase(key); } void clear() { boost::mutex::scoped_lock oLock(mutex_); if (!map_.empty()) { map_.clear(); } return; } int size() { boost::mutex::scoped_lock oLock(mutex_); return map_.size(); } bool empty() { boost::mutex::scoped_lock oLock(mutex_); return map_.empty(); } private: boost::mutex mutex_; std::map<K, V> map_; }; #endif
houbin/alarm
voice_server/include/errcode.h
<reponame>houbin/alarm #ifndef TCPSERVER_ERRCODE_H_ #define TCPSERVER_ERRCODE_H_ #endif
houbin/alarm
voice_server/util/env_posix.h
<filename>voice_server/util/env_posix.h<gh_stars>0 #ifndef UTIL_ENV_POSIX_H_ #define UTIL_ENV_POSIX_H_ #include <string> #include "env.h" using namespace std; namespace util { class PosixWritableFile : public WritableFile { private: string filename_; FILE *file_; size_t written_bytes_; public: PosixWritableFile(string filename); ~PosixWritableFile(); int32_t Append(const Slice& data); int32_t Close(); int32_t Flush(); int32_t Sync(); size_t WrittenBytes() const { return written_bytes_; } }; } #endif
houbin/alarm
deviceOnline/src/device_alive.h
<reponame>houbin/alarm<filename>deviceOnline/src/device_alive.h #ifndef DEVICE_ALIVE_H_ #define DEVICE_ALIVE_H_ #include "push_msg_queue.h" #include "../../util/http_client.h" extern PushMsgQueue *g_push_msg_queue; extern HttpClient *g_http_client; extern void ClearDeviceCache(); extern int StartHttpClient(); #endif
houbin/alarm
voice_server/src/global.h
#ifndef TCPSERVER_GLOBAL_H_ #define TCPSERVER_GLOBAL_H_ #include "../util/logger.h" #include "../util/config.h" extern util::Logger *g_logger; extern util::Config *g_config; #define DATA_PROTOCOL_JSON "json" #define DATA_PROTOCOL_TLV "tlv" #endif
houbin/alarm
voice_server/util/context.h
#ifndef UTIL_CONTEXT_H_ #define UTIL_CONTEXT_H_ namespace util { class Context { private: // no copying allowed Context(const Context& other); const Context& operator=(const Context& other); protected: virtual void Finish(int r) = 0; public: Context() {} virtual ~Context() { } virtual void Complete(int r) { Finish(r); delete this; } }; } #endif
houbin/alarm
deviceOnline/src/logic_opt.h
<gh_stars>0 /* * message_opt.h * * Created on: Mar 18, 2013 * Author: yaowei */ #ifndef MESSAGE_OPT_H_ #define MESSAGE_OPT_H_ #include "defines.h" #include "redis_opt.h" #include "../../public/message.h" #include "../../public/user_interface_defines.h" #include "libjson/_internal/Source/JSONNode.h" class CJsonOpt; class CRedisOpt; class CLogicOpt { public: explicit CLogicOpt(conn* c); virtual ~CLogicOpt(); void StartLogicOpt(const std::string& message); static int SetDeviceFdCache(std::string dev_id, int fd); static int GetDeviceFdFromCache(std::string dev_id, int &fd); static int RemoveDeviceFdFromCache(std::string dev_id); static int SetDeviceAddrCache(std::string dev_id, std::string public_addr, std::string private_addr, std::string dev_ip); static int GetDeviceAddrFromCache(std::string dev_id, std::string &public_addr, std::string &private_addr, std::string &dev_ip); static int RemoveDeviceAddrFromCache(std::string dev_id); static int RemoveDeviceFromCache(std::string dev_id); private: int DeviceLogin(); int DeviceBeacon(); int HandleSetStreamServerResp(); int HandlePushMsgResp(); private: void SendToClient(); private: CJsonOpt* jsonOpt_ptr_; int result_; conn* conn_; std::string responseToClient_; bool is_online_; std::string dev_id_; }; #endif /* MESSAGE_OPT_H_ */
houbin/alarm
voice_server/src/voice_channel.h
<reponame>houbin/alarm #ifndef VOICE_CHANNEL_ #define VOICE_CHANNEL_ #include <map> #include "global.h" #include <event.h> using namespace std; using namespace util; struct ClientVcInfo { string client_id; int client_fd; struct bufferevent *client_bev; string dev_id; }; struct DevVcInfo { string dev_id; int dev_fd; struct bufferevent *dev_bev; string client_id; }; class VoiceChannelManager { private: Mutex mutex_; map<string, ClientVcInfo> client_vc_map_; // client -> ClientVcInfo multimap<string, DevVcInfo> dev_vc_map_; // dev -> DevVcInfo public: VoiceChannelManager() : mutex_("VoiceChannelManager::Mutex") { } ~VoiceChannelManager() { } int32_t ConnectByClient(string client_id, ClientVcInfo client_vc_info); int32_t ConnectByDev(string dev_id, DevVcInfo dev_vc_info); int32_t DisconnectByClient(string client_id, string dev_id); int32_t DisconnectByDev(string dev_id, string client_id); int32_t RouteClientToDev(string client_id, string dev_id, int &dev_fd); }; #endif
houbin/alarm
voice_server/util/rwlock.h
<reponame>houbin/alarm #ifndef UTIL_RWLOCK_H_ #define UTIL_RWLOCK_H_ #include <pthread.h> #include <assert.h> namespace util { class RWLock { private: mutable pthread_rwlock_t rwlock_; const char *name_; public: RWLock(const char *name) : name_(name) { pthread_rwlock_init(&rwlock_, NULL); } ~RWLock() { pthread_rwlock_destroy(&rwlock_); } void GetReadLock() { pthread_rwlock_rdlock(&rwlock_); } void PutReadLock() { pthread_rwlock_unlock(&rwlock_); } void GetWriteLock() { pthread_rwlock_wrlock(&rwlock_); } void PutWriteLock() { pthread_rwlock_unlock(&rwlock_); } class RDLocker { private: RWLock &rwlock_; public: RDLocker(RWLock &rwlock) : rwlock_(rwlock) { rwlock_.GetReadLock(); } ~RDLocker() { rwlock_.PutReadLock(); } }; class WRLocker { private: RWLock &rwlock_; public: WRLocker(RWLock &rwlock) : rwlock_(rwlock) { rwlock_.GetWriteLock(); } ~WRLocker() { rwlock_.PutWriteLock(); } }; }; } #endif
houbin/alarm
userOnline/src/redis_conn_pool.h
<reponame>houbin/alarm /* * redis_conn_pool.h * * Created on: Apr 9, 2013 * Author: yaowei */ #ifndef REDIS_CONN_POOL_H_ #define REDIS_CONN_POOL_H_ #include <deque> #include <hiredis/hiredis.h> #include "defines.h" typedef struct redisConnInfo_ { int max_conn_num; std::string ip; int port; } RedisConnInfo; class CRedisConnPool { public: static CRedisConnPool* GetInstance(); bool Init(const RedisConnInfo& redisConnInfo); void Destroy(); redisContext* GetRedisContext(); void ReleaseRedisContext(redisContext* conn); private: CRedisConnPool(); virtual ~CRedisConnPool(); redisContext* CreateNewRedisContext(); void SafeRedisFree(redisContext *conn) { if (conn) { redisFree(conn); conn = NULL; } } static CRedisConnPool* redisConnPool_; static boost::mutex instance_mutex_; std::deque<redisContext*> queue_redisContext_; RedisConnInfo redisConnInfo_; }; #endif /* REDIS_CONN_POOL_H_ */
houbin/alarm
voice_server/util/cond.h
#ifndef UTIL_COND_H_ #define UTIL_COND_H_ #include <pthread.h> #include <assert.h> #include "mutex.h" #include "utime.h" namespace util { class Cond { private: pthread_cond_t cond_; Mutex *waiter_mutex_; // no copying allowed Cond(const Cond &); void operator=(Cond &c); public: Cond(); ~Cond(); int32_t Wait(Mutex &mutex); int32_t WaitUtil(Mutex &mutex, UTime time); int32_t WaitAfter(Mutex &mutex, UTime after); int32_t Signal(); int32_t SignalAll(); }; } #endif
houbin/alarm
userOnline/src/master_thread.h
<reponame>houbin/alarm /* * net_core.h * * Created on: Mar 4, 2013 * Author: yaowei */ #ifndef MASTER_THREAD__H_ #define MASTER_THREAD__H_ #include "defines.h" #include "threadSafe_map.h" class CWorkerThread; class CMasterThread { public: CMasterThread(); virtual ~CMasterThread(); public: bool InitMasterThread(); void Run(); static CThreadSafeMap<int, int> map_csfd_id_; //客户端连接sfd-->随机唯一id,和业务进程传来的sfd和id对应,防止sfd被其他客户端重用导致错发 private: bool CheckLibeventVersion(); bool InitRemoteListenSocket(evutil_socket_t& listen_socket); static void AccepCb(evutil_socket_t listen_socket, short event, void* arg); static int GetClientfdMapId(); private: struct event_base *main_base_; evutil_socket_t remote_listen_socket_; struct event *listen_event_; static int id_; CWorkerThread *work_thread_ptr_; }; #endif /* NET_CORE_H_ */
houbin/alarm
voice_server/util/common.h
#ifndef UTIL_COMMON_H_ #define UTIL_COMMON_H_ namespace util { void safe_close(int fd); bool set_socket_noblock(const int sock_fd); } #endif
houbin/alarm
voice_server/src/tlv_define.h
<gh_stars>0 #ifndef TLV_DEFINE_H_ #define TLV_DEFINE_H_ enum { TYPE_LENGTH = 0, TYPE_MID = 1, TYPE_CLIENT_ID = 2, TYPE_DEV_ID = 3, TYPE_HEARTBEAT = 4, TYPE_ON_HEARTBEAT = 5, TYPE_CLIENT_BUILD_VC = 1000, TYPE_ON_CLIENT_BUILD_VC = 1001, TYPE_CLIENT_START_SEND = 1002, TYPE_ON_CLIENT_START_SEND = 1003, TYPE_CLIENT_SEND_VOICE_DATA = 1004, TYPE_ON_CLIENT_SEND_VOICE_DATA = 1005, TYPE_CLIENT_FREE_VC = 1006, TYPE_ON_CLIENT_FREE_VC = 1007, TYPE_PUSH_CLIENT_START_SEND = 1008, TYPE_ON_PUSH_CLIENT_START_SEND = 1009, TYPE_PUSH_CLIENT_VOICE_DATA = 1010, TYPE_ON_PUSH_CLIENT_VOICE_DATA = 1012, TYPE_DEV_BUILD_VC = 2000, TYPE_ON_DEV_BUILD_VC = 2001, // TYPE_DEV_SEND_VOICE_DATA = 2002, // TYPE_ON_DEV_SEND_VOICE_DATA = 2003, TYPE_DEV_FREE_VC = 2004, TYPE_ON_DEV_FREE_VC = 2005, TYPE_MAX_NUMBER }; enum MsgType { MSG_TYPE_PRINT = 0, MSG_TYPE_ECHO = 1, MSG_TYPE_PINGPONG = 2 }; #define CONN_BUFFER_LEN (10 * 1024) #define MAX_MSG_LENGTH 2048 //static const uint32_t kMsgMagicCode = 0x49564f4a; #define kMsgHeaderSize (4+4) #define MAX_GUID_LEN 256 enum { GUID_CLIENT = 1, GUID_DEV = 2, }; #endif
houbin/alarm
deviceOnline/src/global_settings.h
/* * global_settings.h * * Created on: Mar 12, 2013 * Author: yaowei */ #ifndef GLOBAL_SETTINGS_H_ #define GLOBAL_SETTINGS_H_ #include <string> class CGlobalSettings { public: std::string public_addr_; std::string private_addr_; int remote_listen_port_; unsigned int thread_num_; int local_listen_port_; int local_conn_timeout_; std::string redis_ip_; int redis_port_; int client_heartbeat_timeout_; std::string httpserver_url_; }; #endif /* GLOBAL_SETTINGS_H_ */
houbin/alarm
voice_server/src/push_msg_timer_queue.h
#ifndef PUSH_MSG_TIMER_QUEUE_H_ #define PUSH_MSG_TIMER_QUEUE_H_ #include <map> #include "../util/mutex.h" #include "../util/cond.h" #include "../util/utime.h" #include "../util/thread.h" #include "../util/atomic.h" #include "../util/coding.h" #include "../util/context.h" #include "../include/socket_wrapper.h" #include "../../public/error_code.h" #include "global.h" #include "tlv_define.h" using namespace std; using namespace util; extern AtomicUInt32 g_push_msg_mid; struct PushMsgInfo { uint32_t recv_mid_; int recv_cfd_; uint32_t push_mid_; uint32_t response_type_; }; class PushMsgContext : public Context { public: uint32_t recv_mid_; int recv_cfd_; uint32_t push_mid_; uint32_t response_type_; PushMsgContext(uint32_t recv_mid, int recv_cfd, uint32_t push_mid, uint32_t response_type) : recv_mid_(recv_mid), recv_cfd_(recv_cfd), push_mid_(push_mid), response_type_(response_type) { } ~PushMsgContext() { } uint32_t GetPushMid() { return push_mid_; } void EncodeRespMsg(string *resp_msg, uint32_t msg_len); void Finish(int ret); }; class PushMsgTimerQueue : public Thread { private: Mutex mutex_; Cond cond_; multimap<UTime, PushMsgContext*> schedule_; map<uint32_t, multimap<UTime, PushMsgContext*>::iterator> events_; bool stop_; public: PushMsgTimerQueue(); ~PushMsgTimerQueue(); int32_t AddEventAfter(double seconds, uint32_t mid, PushMsgContext *push_msg_ct); int32_t AddEventAt(UTime when, uint32_t mid, PushMsgContext *ct); int32_t CancelEvent(uint32_t mid); int32_t CancelEventUnlocked(uint32_t mid); int32_t GetAndCancelEvent(uint32_t mid, PushMsgInfo &push_msg_info); void Start(); void Shutdown(); void *Entry(); }; #endif
houbin/alarm
voice_server/src/master.h
<filename>voice_server/src/master.h #ifndef TCP_SERVER_MASTER_H_ #define TCP_SERVER_MASTER_H_ #include <stdint.h> #include <vector> #include <event.h> #include <netinet/in.h> #include <arpa/inet.h> #include "../util/thread.h" #include "../util/mutex.h" #include "../util/cond.h" #include "global.h" #include "dispatcher.h" using namespace util; using namespace std; class Worker; #define DATA_PROTOCOL_JSON "json" #define DATA_PROTOCOL_TLV "tlv" struct MasterOption { string data_protocol_; // 数据传输的协议 int listen_port_; // master侦听的端口 uint16_t worker_count_; // master挂的worker数量 uint32_t worker_conn_count_; // 每个worker连接的数目,暂时没有使用 int read_timeout_; // 连接的读数据超时 int write_timeout_; // 连接的写数据超时 }; class Master : public Thread { public: Master(string name, MasterOption &master_option); ~Master(); int32_t Init(); int32_t Start(); void *Entry(); void Wait(); void Shutdown(); int32_t OpenServerSocket(); void AcceptCb(int fd, short event, void *arg); int AcceptClient(struct sockaddr_in *client_addr); int32_t PickOneWorker(Worker **worker); string GetDataProtocol(); Dispatcher* GetDispatcher(); private: string name_; int listen_fd_; struct event_base *main_base_; struct event *listen_event_; vector<Worker*> workers_; MasterOption master_option_; Dispatcher *dispatcher_; bool stop_; uint64_t conn_count_; //记录连接次数,包含已经断开的 }; #endif
houbin/alarm
public/config_file.h
<filename>public/config_file.h // ConfigFile.h // Class for reading named values from configuration files // <NAME> v2.1 24 May 2004 <EMAIL> // Copyright (c) 2004 <NAME> // // 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. // Typical usage // ------------- // // Given a configuration file "settings.inp": // atoms = 25 // length = 8.0 # nanometers // name = <NAME> // // Named values are read in various ways, with or without default values: // ConfigFile config( "settings.inp" ); // int atoms = config.read<int>( "atoms" ); // double length = config.read( "length", 10.0 ); // string author, title; // config.readInto( author, "name" ); // config.readInto( title, "title", string("Untitled") ); // // See file example.cpp for more examples. #ifndef SECPLATFORM_COMMON_CONFIGFILE_H #define SECPLATFORM_COMMON_CONFIGFILE_H #include <string> #include <map> #include <iostream> #include <fstream> #include <sstream> #include <locale> class ConfigFile { // Data protected: std::string myDelimiter; // separator between key and value std::string myComment; // separator between value and comments std::string mySentry; // optional string to signal end of file std::map<std::string,std::string> myContents; // extracted keys and values typedef std::map<std::string,std::string>::iterator mapi; typedef std::map<std::string,std::string>::const_iterator mapci; // Methods public: ConfigFile( std::string filename, std::string delimiter = "=", std::string comment = "#", std::string sentry = "EndConfigFile" ) : myDelimiter(delimiter), myComment(comment), mySentry(sentry) { // Construct a ConfigFile, getting keys and values from given file std::locale old_locale = std::locale::global(std::locale("")); std::ifstream in( filename.c_str() ); std::locale::global(old_locale); if( !in ) throw file_not_found( filename ); in >> (*this); } ConfigFile() : myDelimiter( std::string(1,'=') ), myComment( std::string(1,'#') ) { // Construct a ConfigFile without a file; empty } // Search for key and read value or optional default value template<class T> T read( const std::string& key ) const; // call as read<T> template<class T> T read( const std::string& key, const T& value ) const; template<class T> bool readInto( T& var, const std::string& key ) const; template<class T> bool readInto( T& var, const std::string& key, const T& value ) const; // Modify keys and values template<class T> void add( std::string key, const T& value ); void remove( const std::string& key ) { // Remove key and its value myContents.erase( myContents.find( key ) ); return; } // Check whether key exists in configuration bool keyExists( const std::string& key ) const { // Indicate whether key is found mapci p = myContents.find( key ); return ( p != myContents.end() ); } // Check or change configuration syntax std::string getDelimiter() const { return myDelimiter; } std::string getComment() const { return myComment; } std::string getSentry() const { return mySentry; } std::string setDelimiter( const std::string& s ) { std::string old = myDelimiter; myDelimiter = s; return old; } std::string setComment( const std::string& s ) { std::string old = myComment; myComment = s; return old; } // Write or read configuration friend std::ostream& operator<<( std::ostream& os, const ConfigFile& cf ); friend std::istream& operator>>( std::istream& is, ConfigFile& cf ); protected: template<class T> static std::string T_as_string( const T& t ); template<class T> static T string_as_T( const std::string& s ); static void trim( std::string& s ) { // Remove leading and trailing whitespace static const char whitespace[] = " \n\t\v\r\f"; s.erase( 0, s.find_first_not_of(whitespace) ); s.erase( s.find_last_not_of(whitespace) + 1U ); } // Exception types public: struct file_not_found { std::string filename; file_not_found( const std::string& filename_ = std::string() ) : filename(filename_) {} }; struct key_not_found { // thrown only by T read(key) variant of read() std::string key; key_not_found( const std::string& key_ = std::string() ) : key(key_) {} }; }; /* static */ template<class T> std::string ConfigFile::T_as_string( const T& t ) { // Convert from a T to a string // Type T must support << operator std::ostringstream ost; ost << t; return ost.str(); } /* static */ template<class T> T ConfigFile::string_as_T( const std::string& s ) { // Convert from a string to a T // Type T must support >> operator T t; std::istringstream ist(s); ist >> t; return t; } /* static */ template<> inline std::string ConfigFile::string_as_T<std::string>( const std::string& s ) { // Convert from a string to a string // In other words, do nothing return s; } /* static */ template<> inline bool ConfigFile::string_as_T<bool>( const std::string& s ) { // Convert from a string to a bool // Interpret "false", "F", "no", "n", "0" as false // Interpret "true", "T", "yes", "y", "1", "-1", or anything else as true bool b = true; std::string sup = s; for( std::string::iterator p = sup.begin(); p != sup.end(); ++p ) *p = (char)toupper(*p); // make string all caps if( sup==std::string("FALSE") || sup==std::string("F") || sup==std::string("NO") || sup==std::string("N") || sup==std::string("0") || sup==std::string("NONE") ) b = false; return b; } template<class T> T ConfigFile::read( const std::string& key ) const { // Read the value corresponding to key mapci p = myContents.find(key); if( p == myContents.end() ) throw key_not_found(key); return string_as_T<T>( p->second ); } template<class T> T ConfigFile::read( const std::string& key, const T& value ) const { // Return the value corresponding to key or given default value // if key is not found mapci p = myContents.find(key); if( p == myContents.end() ) return value; return string_as_T<T>( p->second ); } template<class T> bool ConfigFile::readInto( T& var, const std::string& key ) const { // Get the value corresponding to key and store in var // Return true if key is found // Otherwise leave var untouched mapci p = myContents.find(key); bool found = ( p != myContents.end() ); if( found ) var = string_as_T<T>( p->second ); return found; } template<class T> bool ConfigFile::readInto( T& var, const std::string& key, const T& value ) const { // Get the value corresponding to key and store in var // Return true if key is found // Otherwise set var to given default mapci p = myContents.find(key); bool found = ( p != myContents.end() ); if( found ) var = string_as_T<T>( p->second ); else var = value; return found; } template<class T> void ConfigFile::add( std::string key, const T& value ) { // Add a key with given value std::string v = T_as_string( value ); trim(key); trim(v); myContents[key] = v; return; } inline std::ostream& operator<<( std::ostream& os, const ConfigFile& cf ) { // Save a ConfigFile to os for( ConfigFile::mapci p = cf.myContents.begin(); p != cf.myContents.end(); ++p ) { os << p->first << " " << cf.myDelimiter << " "; os << p->second << std::endl; } return os; } inline std::istream& operator>>( std::istream& is, ConfigFile& cf ) { // Load a ConfigFile from is // Read in keys and values, keeping internal whitespace typedef std::string::size_type pos; const std::string& delim = cf.myDelimiter; // separator const std::string& comm = cf.myComment; // comment const std::string& sentry = cf.mySentry; // end of file sentry const pos skip = delim.length(); // length of separator std::string nextline = ""; // might need to read ahead to see where value ends while( is || nextline.length() > 0 ) { // Read an entire line at a time std::string line; if( nextline.length() > 0 ) { line = nextline; // we read ahead; use it now nextline = ""; } else { std::getline( is, line ); } // Ignore comments line = line.substr( 0, line.find(comm) ); // Check for end of file sentry if( sentry != "" && line.find(sentry) != std::string::npos ) return is; // Parse the line if it contains a delimiter pos delimPos = line.find( delim ); if( delimPos < std::string::npos ) { // Extract the key std::string key = line.substr( 0, delimPos ); line.replace( 0, delimPos+skip, "" ); // See if value continues on the next line // Stop at blank line, next line with a key, end of stream, // or end of file sentry bool terminate = false; while( !terminate && is ) { std::getline( is, nextline ); terminate = true; std::string nlcopy = nextline; ConfigFile::trim(nlcopy); if( nlcopy == "" ) continue; nextline = nextline.substr( 0, nextline.find(comm) ); if( nextline.find(delim) != std::string::npos ) continue; if( sentry != "" && nextline.find(sentry) != std::string::npos ) continue; nlcopy = nextline; ConfigFile::trim(nlcopy); if( nlcopy != "" ) line += "\n"; line += nextline; terminate = false; } // Store key and value ConfigFile::trim(key); ConfigFile::trim(line); cf.myContents[key] = line; // overwrites if key is repeated } } return is; } #endif // SECPLATFORM_COMMON_CONFIGFILE_H // Release notes: // v1.0 21 May 1999 // + First release // + Template read() access only through non-member readConfigFile() // + ConfigurationFileBool is only built-in helper class // // v2.0 3 May 2002 // + Shortened name from ConfigurationFile to ConfigFile // + Implemented template member functions // + Changed default comment separator from % to # // + Enabled reading of multiple-line values // // v2.1 24 May 2004 // + Made template specializations inline to avoid compiler-dependent linkage // + Allowed comments within multiple-line values // + Enabled blank line termination for multiple-line values // + Added optional sentry to detect end of configuration file // + Rewrote messy trimWhitespace() function as elegant trim()