Multiple SPI masters active at once - arm

I'm facing the problem when trying to get 2 SPI masters working at same time. They both have different pins(mosi, miso, sck, ss) and one is used by SD-Card and another one accelerometer. My device is nRF52832 and I have been trying to use SPI drivers from nRF52 SDK 15.2.0.
I'm not sure if they can be initialized and in use same time, but its feeling quite wrong if the program needs to init and uninit another spi instance whenever it needs to communicate with another one.
Seems that whenever one instance gets initialized the second one does not work correctly. The program does not give any error. This is my first touch to embedded systems and because of that, my skill level is the novice. I really would appreciate all the help.
/**
* Copyright (c) 2016 - 2018, Nordic Semiconductor ASA
*
* All rights reserved.
*
* 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, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, 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 Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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.
*
*/
/** #file
* #defgroup fatfs_example_main main.c
* #{
* #ingroup fatfs_example
* #brief FATFS Example Application main file.
*
* This file contains the source code for a sample application using FAT filesystem and SD card library.
*
*/
#include "nrf.h"
#include "bsp.h"
#include "ff.h"
#include "diskio_blkdev.h"
#include "nrf_block_dev_sdc.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "nrf_gpio.h"
#include "nrf_delay.h"
#include "nrf_drv_spi.h"
#define FILE_NAME "NORDIC.TXT"
#define TEST_STRING "SD card example."
#define SDC_SCK_PIN 16 ///< SDC serial clock (SCK) pin.
#define SDC_MOSI_PIN 17 ///< SDC serial data in (DI) pin.
#define SDC_MISO_PIN 18 ///< SDC serial data out (DO) pin.
#define SDC_CS_PIN 11 ///< SDC chip select (CS) pin.
#define SDC2_SCK_PIN 5
#define SDC2_MOSI_PIN 4
#define SDC2_MISO_PIN 3
#define SDC2_CS_PIN 12
#define SPI_AC_INSTANCE 1
static const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_AC_INSTANCE);
/**
* #brief SDC block device definition
* */
NRF_BLOCK_DEV_SDC_DEFINE(
m_block_dev_sdc,
NRF_BLOCK_DEV_SDC_CONFIG(
SDC_SECTOR_SIZE,
APP_SDCARD_CONFIG(SDC_MOSI_PIN, SDC_MISO_PIN, SDC_SCK_PIN, SDC_CS_PIN)
),
NFR_BLOCK_DEV_INFO_CONFIG("Nordic", "SDC", "1.00")
);
/**
* #brief Function for demonstrating FAFTS usage.
*/
static void fatfs_example()
{
static FATFS fs;
static DIR dir;
static FILINFO fno;
static FIL file;
uint32_t bytes_written;
FRESULT ff_result;
DSTATUS disk_state = STA_NOINIT;
// Initialize FATFS disk I/O interface by providing the block device.
static diskio_blkdev_t drives[] =
{
DISKIO_BLOCKDEV_CONFIG(NRF_BLOCKDEV_BASE_ADDR(m_block_dev_sdc, block_dev), NULL)
};
diskio_blockdev_register(drives, ARRAY_SIZE(drives));
NRF_LOG_INFO("Initializing disk 0 (SDC)...");
for (uint32_t retries = 3; retries && disk_state; --retries)
{
disk_state = disk_initialize(0);
}
if (disk_state)
{
NRF_LOG_INFO("Disk initialization failed.");
return;
}
uint32_t blocks_per_mb = (1024uL * 1024uL) / m_block_dev_sdc.block_dev.p_ops->geometry(&m_block_dev_sdc.block_dev)->blk_size;
uint32_t capacity = m_block_dev_sdc.block_dev.p_ops->geometry(&m_block_dev_sdc.block_dev)->blk_count / blocks_per_mb;
NRF_LOG_INFO("Capacity: %d MB", capacity);
NRF_LOG_INFO("Mounting volume...");
ff_result = f_mount(&fs, "", 1);
if (ff_result)
{
NRF_LOG_INFO("Mount failed.");
return;
}
NRF_LOG_INFO("\r\n Listing directory: /");
ff_result = f_opendir(&dir, "/");
if (ff_result)
{
NRF_LOG_INFO("Directory listing failed!");
return;
}
do
{
ff_result = f_readdir(&dir, &fno);
if (ff_result != FR_OK)
{
NRF_LOG_INFO("Directory read failed.");
return;
}
if (fno.fname[0])
{
if (fno.fattrib & AM_DIR)
{
NRF_LOG_RAW_INFO(" <DIR> %s",(uint32_t)fno.fname);
}
else
{
NRF_LOG_RAW_INFO("%9lu %s", fno.fsize, (uint32_t)fno.fname);
}
}
}
while (fno.fname[0]);
NRF_LOG_RAW_INFO("");
NRF_LOG_INFO("Writing to file " FILE_NAME "...");
ff_result = f_open(&file, FILE_NAME, FA_READ | FA_WRITE | FA_OPEN_APPEND);
if (ff_result != FR_OK)
{
NRF_LOG_INFO("Unable to open or create file: " FILE_NAME ".");
return;
}
ff_result = f_write(&file, TEST_STRING, sizeof(TEST_STRING) - 1, (UINT *) &bytes_written);
if (ff_result != FR_OK)
{
NRF_LOG_INFO("Write failed\r\n.");
}
else
{
NRF_LOG_INFO("%d bytes written.", bytes_written);
}
(void) f_close(&file);
return;
}
static uint8_t tx_buf[3];
static uint8_t rx_buf[10]; /**< RX buffer. */
uint8_t accReadByte(uint8_t RegisterAddress)
{
tx_buf[0] = 0x7F & RegisterAddress;
tx_buf[1] = 0x80 & RegisterAddress;
APP_ERROR_CHECK(nrf_drv_spi_transfer(&spi, tx_buf, 2, rx_buf, 1+2));
return rx_buf[2];
}
void initAcc()
{
//nrf_gpio_set_cfg_output(SDC2_CS_PIN);
nrf_drv_spi_config_t spi_config = NRF_DRV_SPI_DEFAULT_CONFIG;
spi_config.ss_pin = SDC2_CS_PIN;
spi_config.miso_pin = SDC2_MISO_PIN;
spi_config.mosi_pin = SDC2_MOSI_PIN;
spi_config.sck_pin = SDC2_SCK_PIN;
spi_config.frequency = NRF_SPI_FREQ_250K;
APP_ERROR_CHECK(nrf_drv_spi_init(&spi, &spi_config, NULL, NULL));
}
/**
* #brief Function for main application entry.
*/
int main(void)
{
bsp_board_init(BSP_INIT_LEDS);
APP_ERROR_CHECK(NRF_LOG_INIT(NULL));
NRF_LOG_DEFAULT_BACKENDS_INIT();
NRF_LOG_INFO("FATFS example started.");
fatfs_example();
initAcc();
if ( accReadByte(0x0D) == 0x6A )
{
NRF_LOG_INFO("Got right whoami!");
}
while (true)
{
__WFE();
}
}
/** #} */

Problem solved. SD-Card and the accelerometer both have different serial bus in default. When initialized another one first, second one failed in bus initialization and that caused nRF52832 not to get the right answer.

Related

Looking for Informix4GL by Example header file 'fgicfunc.h'

I am working through the Informix4GL by Example cookbook. Exercise 13 deals with creating external callable modules written in C. The example code contains this line:
#include "fgicfunc.h"
But I cannot find this file or a description of its contents. It is supposed to be related to the Informix database software product but I do not have this installed. Does anyone here have that file; and if you do then can you provide me the contents?
Despite the copyright notice, etc, this is published when you install the I4GL p-code compiler.
/**************************************************************************/
/* */
/* Licensed Materials - Property of IBM */
/* */
/* "Restricted Materials of IBM" */
/* */
/* IBM Informix 4GL */
/* (c) Copyright IBM Corporation 2010 All rights reserved. */
/* */
/**************************************************************************/
/***************************************************************************
*
* INFORMIX SOFTWARE, INC.
*
* PROPRIETARY DATA
*
* THIS DOCUMENT CONTAINS TRADE SECRET DATA WHICH IS THE PROPERTY OF
* INFORMIX SOFTWARE, INC. THIS DOCUMENT IS SUBMITTED TO RECIPIENT IN
* CONFIDENCE. INFORMATION CONTAINED HEREIN MAY NOT BE USED, COPIED OR
* DISCLOSED IN WHOLE OR IN PART EXCEPT AS PERMITTED BY WRITTEN AGREEMENT
* SIGNED BY AN OFFICER OF INFORMIX SOFTWARE, INC.
*
* THIS MATERIAL IS ALSO COPYRIGHTED AS AN UNPUBLISHED WORK UNDER
* SECTIONS 104 AND 408 OF TITLE 17 OF THE UNITED STATES CODE.
* UNAUTHORIZED USE, COPYING OR OTHER REPRODUCTION IS PROHIBITED BY LAW.
*
*
* Title: fgicfunc.h
* Description: 4GL C function header file
*
***************************************************************************
*/
#ifndef IBM_I4GL_FGICFUNC_H
#define IBM_I4GL_FGICFUNC_H
typedef struct
{
char *cf_name; /* name of function */
int (*cf_ptr)(int); /* pointer to the function */
short cf_nargs; /* number of arguments, < 0 means variable */
} cfunc_t;
#endif /* IBM_I4GL_FGICFUNC_H */
We can discuss the erratic boxing comments another time.

How to improve Mersenne Twister vor AVX/SSE?

Today i have started a project having the goal to optimize the generation of random numbers.
I want to wipe several hard drives, using the Mersenne Twister PRNG, but unfortunately i'm only able to produce around 200MB/s of random data, on 8 hard drives, so 25MB/s each.
Is there a way to optimize this code, using AVX, or SSE (for legacy reasons) to improve this code?
Is it something what can be done without having studied computer science?
Unfortunately i'm a simple C programmer, only having the experience of a few years, but not having studied computer science yet.
Could someone provide some information, how to bring this forward?
Which of these processes could be improved? Can someone give some examples, how an enhanced version of it could look like? Can someone provide some good books to retrieve a better knowledge about this matter?
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Copyright (C) 2005, Mutsuo Saito,
All rights reserved.
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. The names of its contributors may not 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 OWNER 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.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat # math.sci.hiroshima-u.ac.jp (remove space)
*/
#include <stdio.h>
#include "mt19937ar.h"
/* Period parameters */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
static unsigned long mt[N]; /* the array for the state vector */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
/* initializes mt[N] with a seed */
void init_genrand(unsigned long s)
{
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt[mti] &= 0xffffffffUL;
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
void init_by_array(unsigned long init_key[], int key_length)
{
int i, j, k;
init_genrand(19650218UL);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
+ init_key[j] + j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
}
/* generates a random number on [0,0xffffffff]-interval */
unsigned long genrand_int32(void)
{
unsigned long y;
static unsigned long mag01[2]={0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
int kk;
if (mti == N+1) /* if init_genrand() has not been called, */
init_genrand(5489UL); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
mti = 0;
}
y = mt[mti++];
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
I think, Mersenne Twister PRNG is not suitable for your purpose, because of it is not cryptographically secure. If cryptographer can guess or recover piece of MT sequence (for example, from initially 0-filled disk part), he can recover your generator state, and recover entire your sequence, by re-run PRNG from that state.
I suggest you to use modification of RC4 PRNG, but works with array of "uint16_t [1 << 16]", rather than original byte-oriented RC4 with array "uint8_t [1 << 8]". This modification will give you 2 benefits:
For each computation step, you will extract 2 bytes, not one, as in the original. By other words, you will get ~2x performance improvement, this is important for you.
Period of this generator would be extremely long, I estimate it as 2^(2^14).
To preserve attack to your KSA (major RC4 vulnerability), I suggest you to "empty intial run" 2^18 times before usage. By other words, you initially, just read and drop initial 2^18 uint16_t values from PRNG.
Also, you can modify the KSA, to make it more hack-resistant.

best way to create a string array through macro

I am trying to crate a parametric static array in a header file.
Let me elaborate my requirement
Wanted to create below array in header file statically which can be resolved at
compile time
static char test_array[][256] = {
"hello_1",
"hello_2",
"hello_3" };
I need to generate this using macro which can do substitution with %d for 1,2 and 3 and the number
of parameter also not fixed. What I mean here is tomorrow this array I can simply change through header file to
static char test_array[][256] = {
"hello_1",
"hello_45",
"hello_39",
"hello_101" };
I have the code to do it at run time in .c file but specifically I want to do it in a header file through macros .
The best way would be to write generator, that generates header array in compile time. A short time ago I wrote program that may point you the right direction:
/*
* Copyright (c) 2018 Krzysztof "Palaiologos" Szewczyk
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#define PERLINE 30
#define BUFSIZE 1024
static const char hexrange[] = "0123456789ABCDEF";
char buf[BUFSIZE];
int lineidx,line,i,bytes;
int main(int argc, const char * argv[]) {
FILE * in, * out;
if (argc != 4) {
fprintf(stderr, "Usage: %s infile outfile symbol\n", argv[0]);
return 1;
}
in = fopen(argv[1], "rb");
out = fopen(argv[2], "wb");
if (!in || !out) {
fputs("Could not open one of input files.\n", stderr);
return 1;
}
fprintf(out, "/* Generated by HexExport (by Krzysztof Szewczyk a.k.a. Palaiologos) */\n\n");
fprintf(out, "static const unsigned char %s[] = {", argv[3]);
while ((bytes = fread(buf, 1, sizeof(buf), in)) > 0) {
for (i = 0; i < bytes; ++i) {
int byte = ((uint8_t *)buf) [i];
if (lineidx++ == 0) {
if (line++)
fputc(',', out);
fputs("\n\t", out);
} else
fputs(", ", out);
fputs("0x", out);
fputc(hexrange[byte >> 4], out);
fputc(hexrange[byte & 0xF], out);
if (lineidx >= PERLINE)
lineidx = 0;
}
}
fputs("\n};\n", out);
fclose(in);
fclose(out);
return 0;
}
What it does, simply, is to generate hex array from file. You can modify it to accomplish your task. Generating such array using macro is either impossible or very hard task. Source code taken from this place

Read excel file in C using libxls

I am trying to create an application that reads an excel file using libxls.
I've already downloaded libxls but I do not know how to use it.
Can someone please show me a minimum program to read from a XLS file
If you mean libxls:
There are tests inside the source archive which can be used as sample code.
Here's the content of libxls-1.4.0/test/test2.c:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* This file is part of libxls -- A multiplatform, C/C++ library
* for parsing Excel(TM) files.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY David Hoerl ''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 David Hoerl 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.
*
* Copyright 2004 Komarov Valery
* Copyright 2006 Christophe Leitienne
* Copyright 2008-2012 David Hoerl
*
*/
// THIS FILE LETS YOU QUICKLY FEED A .xls FILE FOR PARSING
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "libxls/xls.h"
int main(int argc, char *argv[])
{
xlsWorkBook* pWB;
xlsWorkSheet* pWS;
unsigned int i;
if(argc != 2) {
printf("Need file arg\n");
exit(0);
}
struct st_row_data* row;
WORD t,tt;
pWB=xls_open(argv[1],"UTF-8");
if (pWB!=NULL)
{
for (i=0;i<pWB->sheets.count;i++)
printf("Sheet N%i (%s) pos %i\n",i,pWB->sheets.sheet[i].name,pWB->sheets.sheet[i].filepos);
pWS=xls_getWorkSheet(pWB,0);
xls_parseWorkSheet(pWS);
printf("pWS->rows.lastrow %d\n", pWS->rows.lastrow);
for (t=0;t<=pWS->rows.lastrow;t++)
{
printf("DO IT");
row=&pWS->rows.row[t];
xls_showROW(row);
for (tt=0;tt<=pWS->rows.lastcol;tt++)
{
xls_showCell(&row->cells.cell[tt]);
}
}
printf("Count of rows: %i\n",pWS->rows.lastrow);
printf("Max col: %i\n",pWS->rows.lastcol);
printf("Count of sheets: %i\n",pWB->sheets.count);
xls_showBookInfo(pWB);
} else {
printf("pWB == NULL\n");
}
return 0;
}
If you mean libxl:
Below you'll find a data reading example written in C from http://www.libxl.com/.
Furthermore they provide documentation and more examples on their homepage.
BookHandle book = xlCreateBook();
if(book)
{
if(xlBookLoad(book, L"example.xls"))
{
SheetHandle sheet = xlBookGetSheet(book, 0);
if(sheet)
{
double d;
const wchar_t* s = xlSheetReadStr(sheet, 2, 1, NULL);
if(s) wprintf(L"%s\n", s);
d = xlSheetReadNum(sheet, 3, 1, NULL);
printf("%g\n", d);
}
}
xlBookRelease(book);
}

How to create a simple sysfs class attribute in Linux kernel v3.2

I'm learning how to use sysfs in my Linux modules, but I'm having the hardest time finding current documentation on these topics. The Linux Device Drivers 3rd Edition book I've been using seems to be rather dated in this area unfortunately (e.g. the class_device structure appears to be completely gone in current Linux versions).
I'm simply trying to get an attribute to appear, under the respective sysfs class for my module, that will allow me to read the value of a module variable from kernel space.
In my code, I have a class created that allows udev to create a device node at /dev/foo for my module:
dev_t foo_dev;
alloc_chrdev_region(&foo_dev, 0, 1, "bar");
struct class *bar = class_create(THIS_MODULE, "bar");
device_create(bar, NULL, foo_dev, NULL, "foo");
struct cdev foo_dev_file;
cdev_init(&foo_dev_file, &fops); /* fops defined earlier */
cdev_add(&foo_dev_file, foo_dev, 1);
When I insert the module I get a sysfs class directory created and populated with some default attributes at /sys/class/bar/foo/. How can I create attributes that show up under this new directory?
I have the concepts down pretty well I believe -- create attribute structure, define sysfs_ops functions, etc -- my problem is that I don't know which particular kernel structure to use (class_attribute?), nor how to make these attributes appear under the right sysfs directory.
Would anyone point me to a tutorial or article detailing the process for current Linux kernels?
Even though my knowledge is still fairly low on the topic, I'm going to post an answer just because of the age of this question. If somebody else has a better answer, please post! :)
First off, I'm going to assume that you've read that whole chapter (specifically about kobjects & ksets). So just about every struct in the device driver model has these cutely included in them. If you want to manipulate the kobject for the class its self (not sure if that's wise or not), that's your struct class's dev_kobj member.
However, you want to manipulate the attributes of that class. I believe you do this by defining a (usually static), NULL-terminated array of them as follows and then assigning its address to the struct class's class_attrs member (taken from drivers/uwb/driver.c):
static struct class_attribute uwb_class_attrs[] = {
__ATTR(beacon_timeout_ms, S_IWUSR | S_IRUGO,
beacon_timeout_ms_show, beacon_timeout_ms_store),
__ATTR_NULL,
};
/** Device model classes */
struct class uwb_rc_class = {
.name = "uwb_rc",
.class_attrs = uwb_class_attrs,
};
When I don't know how to use something, I usually git grep the repository for somebody else who has used it and try to learn from it that way. It would seem that this is why they tend to say kernel "hackers" and not "developers".
Minimal runnable example
Usage:
insmod /sysfs.ko
cd /sys/kernel/lkmc_sysfs
printf 12345 >foo
cat foo
# => 1234
dd if=foo bs=1 count=2 skip=1 status=none
# => 23
sysfs.c
#include <linux/init.h>
#include <linux/kobject.h>
#include <linux/module.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include <uapi/linux/stat.h> /* S_IRUSR, S_IWUSR */
enum { FOO_SIZE_MAX = 4 };
static int foo_size;
static char foo_tmp[FOO_SIZE_MAX];
static ssize_t foo_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buff)
{
strncpy(buff, foo_tmp, foo_size);
return foo_size;
}
static ssize_t foo_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buff, size_t count)
{
foo_size = min(count, (size_t)FOO_SIZE_MAX);
strncpy(foo_tmp, buff, foo_size);
return count;
}
static struct kobj_attribute foo_attribute =
__ATTR(foo, S_IRUGO | S_IWUSR, foo_show, foo_store);
static struct attribute *attrs[] = {
&foo_attribute.attr,
NULL,
};
static struct attribute_group attr_group = {
.attrs = attrs,
};
static struct kobject *kobj;
static int myinit(void)
{
int ret;
kobj = kobject_create_and_add("lkmc_sysfs", kernel_kobj);
if (!kobj)
return -ENOMEM;
ret = sysfs_create_group(kobj, &attr_group);
if (ret)
kobject_put(kobj);
return ret;
}
static void myexit(void)
{
kobject_put(kobj);
}
module_init(myinit);
module_exit(myexit);
MODULE_LICENSE("GPL");
GitHub upstream.
Tested with Linux kernel 5.0.
There is a good tutorial in the link below
http://pete.akeo.ie/2011/08/writing-linux-device-driver-for-kernels.html
parrot_driver.c:
/*
* Linux 2.6 and 3.0 'parrot' sample device driver
*
* Copyright (c) 2011, Pete Batard <pete#akeo.ie>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/mutex.h>
#include <linux/kfifo.h>
#include "parrot_driver.h"
/* Module information */
MODULE_AUTHOR(AUTHOR);
MODULE_DESCRIPTION(DESCRIPTION);
MODULE_VERSION(VERSION);
MODULE_LICENSE("GPL");
/* Device variables */
static struct class* parrot_class = NULL;
static struct device* parrot_device = NULL;
static int parrot_major;
/* Flag used with the one_shot mode */
static bool message_read;
/* A mutex will ensure that only one process accesses our device */
static DEFINE_MUTEX(parrot_device_mutex);
/* Use a Kernel FIFO for read operations */
static DECLARE_KFIFO(parrot_msg_fifo, char, PARROT_MSG_FIFO_SIZE);
/* This table keeps track of each message length in the FIFO */
static unsigned int parrot_msg_len[PARROT_MSG_FIFO_MAX];
/* Read and write index for the table above */
static int parrot_msg_idx_rd, parrot_msg_idx_wr;
/* Module parameters that can be provided on insmod */
static bool debug = false; /* print extra debug info */
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "enable debug info (default: false)");
static bool one_shot = true; /* only read a single message after open() */
module_param(one_shot, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "disable the readout of multiple messages at once (default: true)");
static int parrot_device_open(struct inode* inode, struct file* filp)
{
dbg("");
/* Our sample device does not allow write access */
if ( ((filp->f_flags & O_ACCMODE) == O_WRONLY)
|| ((filp->f_flags & O_ACCMODE) == O_RDWR) ) {
warn("write access is prohibited\n");
return -EACCES;
}
/* Ensure that only one process has access to our device at any one time
* For more info on concurrent accesses, see http://lwn.net/images/pdf/LDD3/ch05.pdf */
if (!mutex_trylock(&parrot_device_mutex)) {
warn("another process is accessing the device\n");
return -EBUSY;
}
message_read = false;
return 0;
}
static int parrot_device_close(struct inode* inode, struct file* filp)
{
dbg("");
mutex_unlock(&parrot_device_mutex);
return 0;
}
static ssize_t parrot_device_read(struct file* filp, char __user *buffer, size_t length, loff_t* offset)
{
int retval;
unsigned int copied;
/* The default from 'cat' is to issue multiple reads until the FIFO is depleted
* one_shot avoids that */
if (one_shot && message_read) return 0;
dbg("");
if (kfifo_is_empty(&parrot_msg_fifo)) {
dbg("no message in fifo\n");
return 0;
}
retval = kfifo_to_user(&parrot_msg_fifo, buffer, parrot_msg_len[parrot_msg_idx_rd], &copied);
/* Ignore short reads (but warn about them) */
if (parrot_msg_len[parrot_msg_idx_rd] != copied) {
warn("short read detected\n");
}
/* loop into the message length table */
parrot_msg_idx_rd = (parrot_msg_idx_rd+1)%PARROT_MSG_FIFO_MAX;
message_read = true;
return retval ? retval : copied;
}
/* The file_operation scructure tells the kernel which device operations are handled.
* For a list of available file operations, see http://lwn.net/images/pdf/LDD3/ch03.pdf */
static struct file_operations fops = {
.read = parrot_device_read,
.open = parrot_device_open,
.release = parrot_device_close
};
/* Placing data into the read FIFO is done through sysfs */
static ssize_t sys_add_to_fifo(struct device* dev, struct device_attribute* attr, const char* buf, size_t count)
{
unsigned int copied;
dbg("");
if (kfifo_avail(&parrot_msg_fifo) < count) {
warn("not enough space left on fifo\n");
return -ENOSPC;
}
if ((parrot_msg_idx_wr+1)%PARROT_MSG_FIFO_MAX == parrot_msg_idx_rd) {
/* We've looped into our message length table */
warn("message length table is full\n");
return -ENOSPC;
}
/* The buffer is already in kernel space, so no need for ..._from_user() */
copied = kfifo_in(&parrot_msg_fifo, buf, count);
parrot_msg_len[parrot_msg_idx_wr] = copied;
if (copied != count) {
warn("short write detected\n");
}
parrot_msg_idx_wr = (parrot_msg_idx_wr+1)%PARROT_MSG_FIFO_MAX;
return copied;
}
/* This sysfs entry resets the FIFO */
static ssize_t sys_reset(struct device* dev, struct device_attribute* attr, const char* buf, size_t count)
{
dbg("");
/* Ideally, we would have a mutex around the FIFO, to ensure that we don't reset while in use.
* To keep this sample simple, and because this is a sysfs operation, we don't do that */
kfifo_reset(&parrot_msg_fifo);
parrot_msg_idx_rd = parrot_msg_idx_wr = 0;
return count;
}
/* Declare the sysfs entries. The macros create instances of dev_attr_fifo and dev_attr_reset */
static DEVICE_ATTR(fifo, S_IWUSR, NULL, sys_add_to_fifo);
static DEVICE_ATTR(reset, S_IWUSR, NULL, sys_reset);
/* Module initialization and release */
static int __init parrot_module_init(void)
{
int retval;
dbg("");
/* First, see if we can dynamically allocate a major for our device */
parrot_major = register_chrdev(0, DEVICE_NAME, &fops);
if (parrot_major < 0) {
err("failed to register device: error %d\n", parrot_major);
retval = parrot_major;
goto failed_chrdevreg;
}
/* We can either tie our device to a bus (existing, or one that we create)
* or use a "virtual" device class. For this example, we choose the latter */
parrot_class = class_create(THIS_MODULE, CLASS_NAME);
if (IS_ERR(parrot_class)) {
err("failed to register device class '%s'\n", CLASS_NAME);
retval = PTR_ERR(parrot_class);
goto failed_classreg;
}
/* With a class, the easiest way to instantiate a device is to call device_create() */
parrot_device = device_create(parrot_class, NULL, MKDEV(parrot_major, 0), NULL, CLASS_NAME "_" DEVICE_NAME);
if (IS_ERR(parrot_device)) {
err("failed to create device '%s_%s'\n", CLASS_NAME, DEVICE_NAME);
retval = PTR_ERR(parrot_device);
goto failed_devreg;
}
/* Now we can create the sysfs endpoints (don't care about errors).
* dev_attr_fifo and dev_attr_reset come from the DEVICE_ATTR(...) earlier */
retval = device_create_file(parrot_device, &dev_attr_fifo);
if (retval < 0) {
warn("failed to create write /sys endpoint - continuing without\n");
}
retval = device_create_file(parrot_device, &dev_attr_reset);
if (retval < 0) {
warn("failed to create reset /sys endpoint - continuing without\n");
}
mutex_init(&parrot_device_mutex);
/* This device uses a Kernel FIFO for its read operation */
INIT_KFIFO(parrot_msg_fifo);
parrot_msg_idx_rd = parrot_msg_idx_wr = 0;
return 0;
failed_devreg:
class_unregister(parrot_class);
class_destroy(parrot_class);
failed_classreg:
unregister_chrdev(parrot_major, DEVICE_NAME);
failed_chrdevreg:
return -1;
}
static void __exit parrot_module_exit(void)
{
dbg("");
device_remove_file(parrot_device, &dev_attr_fifo);
device_remove_file(parrot_device, &dev_attr_reset);
device_destroy(parrot_class, MKDEV(parrot_major, 0));
class_unregister(parrot_class);
class_destroy(parrot_class);
unregister_chrdev(parrot_major, DEVICE_NAME);
}
/* Let the kernel know the calls for module init and exit */
module_init(parrot_module_init);
module_exit(parrot_module_exit);
parrot_driver.h:
/*
* Linux 2.6 and 3.0 'parrot' sample device driver
*
* Copyright (c) 2011, Pete Batard <pete#akeo.ie>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define DEVICE_NAME "device"
#define CLASS_NAME "parrot"
#define PARROT_MSG_FIFO_SIZE 1024
#define PARROT_MSG_FIFO_MAX 128
#define AUTHOR "Pete Batard <pete#akeo.ie>"
#define DESCRIPTION "'parrot' sample device driver"
#define VERSION "0.3"
/* We'll use our own macros for printk */
#define dbg(format, arg...) do { if (debug) pr_info(CLASS_NAME ": %s: " format , __FUNCTION__ , ## arg); } while (0)
#define err(format, arg...) pr_err(CLASS_NAME ": " format, ## arg)
#define info(format, arg...) pr_info(CLASS_NAME ": " format, ## arg)
#define warn(format, arg...) pr_warn(CLASS_NAME ": " format, ## arg)

Resources