将C转换成Python

2024-05-14 06:57:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试转换一个C模块,它解析Linux库rtl-fm的输出。它用于通过DVB-T加密狗从电子能量表获取能量使用情况

C模块工作得很好,但我希望它用python编写,以便与我拥有的其他python模块交互

我把常数放进去了常量.py在

我完全被困在转换行:cursamp=(int16Βt)(fgetc(stdin)| fgetc(stdin)<;<;8);我尝试了很多不同的方式转换。每次尝试都以错误告终!在

这似乎有两种类型的问题:1。输入结果2的类型转换。如何将fgetc()转换为python。在

我也有困难转换而(!feof(stdin))到python中

有谁能帮忙吗?在

C代码如下:

#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <math.h>

#include <stdlib.h> // For exit function

#define VOLTAGE         240 /* Refernce Voltage */
#define CENTERSAMP      100 /* Number of samples needed to compute for the wave center */
#define PREAMBLE_COUNT      40  /* Number of high(1) samples for a valid preamble */
#define MINLOWBIT       3   /* Number of high(1) samples for a logic 0 */
#define MINHIGHBIT      8   /* Number of high(1) samples for a logic 1 */
#define E2BYTECOUNT     8   /* Efergy E2 Message Byte Count */
#define FRAMEBITCOUNT       64  /* Number of bits for the entire frame (not including preamble) */


#define LOGTYPE        1 // Allows changing line-endings - 0 is for Unix /n, 1 for Windows /r/n
#define SAMPLES_TO_FLUSH  10 // Number of samples taken before writing to file.
                 // Setting this too low will cause excessive wear to flash due to updates to
                 // filesystem! You have been warned! Set to 10 samples for 6 seconds = every min.

int loggingok;   // Global var indicating logging on or off
int samplecount; // Global var counter for samples taken since last flush
FILE *fp;    // Global var file handle

int calculate_watts(char bytes[])
{

char tbyte;
double current_adc;
double result;
int i;

time_t ltime; 
struct tm *curtime;
char buffer[80];

    /* add all captured bytes and mask lower 8 bits */

    tbyte = 0;

    for(i=0;i<7;i++)
        tbyte += bytes[i];

    tbyte &= 0xff;

    /* if checksum matches get watt data */

    if (tbyte == bytes[7])
    {
        time( &ltime );
        curtime = localtime( &ltime );
        strftime(buffer,80,"%x,%X", curtime);

        current_adc = (bytes[4] * 256) + bytes[5];
        result  = (VOLTAGE * current_adc) / ((double) 32768 / (double) pow(2,bytes[6]));
        printf("%s,%f\n",buffer,result);
        if(loggingok) {
          if(LOGTYPE) {
            fprintf(fp,"%s,%f\r\n",buffer,result);
          } else {
            fprintf(fp,"%s,%f\n",buffer,result);
          }
          samplecount++;
          if(samplecount==SAMPLES_TO_FLUSH) {
            samplecount=0;
            fflush(fp);
          }
        }
        fflush(stdout);
        return 1;
    }
    //printf("Checksum Error \n");
    return 0;
}

void  main (int argc, char**argv) 
{

char bytearray[9];
char bytedata;

int prvsamp;
int hctr;
int cursamp;
int bitpos;
int bytecount;

int i;
int preamble;
int frame;
int dcenter;
int dbit;

long center;

    if(argc==2) {
      fp = fopen(argv[1], "a"); // Log file opened in append mode to avoid destroying data
      samplecount=0; // Reset sample counter
      loggingok=1;
      if (fp == NULL) {
          perror("Failed to open log file!"); // Exit if file open fails
          exit(EXIT_FAILURE);
      }
    } else {
      loggingok=0;
    }

    printf("Efergy E2 Classic decode \n\n");


    /* initialize variables */

    cursamp = 0;
    prvsamp = 0;

    bytedata = 0;
    bytecount = 0;
    hctr = 0;
    bitpos = 0;
    dbit = 0;
    preamble = 0;
    frame = 0;

    dcenter = CENTERSAMP;
    center = 0;

    while( !feof(stdin) ) 
    {

        cursamp  = (int16_t) (fgetc(stdin) | fgetc(stdin)<<8);

        /* initially capture CENTERSAMP samples for wave center computation */

        if (dcenter > 0)
        {
            dcenter--;
            center = center + cursamp;  /* Accumulate FSK wave data */ 

            if (dcenter == 0)
            {
                /* compute for wave center and re-initialize frame variables */

                center = (long) (center/CENTERSAMP);

                hctr  = 0;
                bytedata = 0;
                bytecount = 0;
                bitpos = 0;
                dbit = 0;
                preamble = 0;
                frame = 0;
            }

        }
        else
        {
            if ((cursamp > center) && (prvsamp < center))       /* Detect for positive edge of frame data */
                hctr = 0;
            else 
                if ((cursamp > center) && (prvsamp > center))       /* count samples at high logic */
                {
                    hctr++;
                    if (hctr > PREAMBLE_COUNT)  
                        preamble = 1;
                }
                else 
                    if (( cursamp < center) && (prvsamp > center))
                    {
                        /* at negative edge */

                        if ((hctr > MINLOWBIT) && (frame == 1))
                        {
                            dbit++;
                            bitpos++;   
                            bytedata = bytedata << 1;
                            if (hctr > MINHIGHBIT)
                                bytedata = bytedata | 0x1;

                            if (bitpos > 7)
                            {
                                bytearray[bytecount] = bytedata;
                                bytedata = 0;
                                bitpos = 0;

                                bytecount++;

                                if (bytecount == E2BYTECOUNT)
                                {

                                    /* at this point check for checksum and calculate watt data */
                                    /* if there is a checksum mismatch compute for a new wave center */

                                    if (calculate_watts(bytearray) == 0)
                                        dcenter = CENTERSAMP;   /* make dcenter non-zero to trigger center resampling */
                                }
                            }

                            if (dbit > FRAMEBITCOUNT)
                            {   
                                /* reset frame variables */

                                bitpos = 0;
                                bytecount = 0;
                                dbit = 0;
                                frame = 0;
                                preamble = 0;
                                bytedata = 0;
                            }
                        }

                        hctr = 0;

                    } 
                    else
                        hctr = 0;

            if ((hctr == 0) && (preamble == 1))
            {
                /* end of preamble, start of frame data */
                preamble = 0;
                frame = 1;
            }

        } /* dcenter */

        prvsamp = cursamp;

    } /* while */
    if(loggingok) {
        fclose(fp); // If rtl-fm gives EOF and program terminates, close file gracefully.
    }
}

以及Python转换(在没有文件记录的情况下简化了一点):

^{pr2}$

Tags: oftoforifframeintcentersamples
1条回答
网友
1楼 · 发布于 2024-05-14 06:57:50

C的fgetc(stdin)转换为python2的ord(sys.stdin.read(1)[0]),返回stdin下一个字节中的一个数值。(在python3中,必须将sys.stdin重新打开为二进制文件才能实现这一点,否则.read(1)将得到一个Unicode字符,而不是一个字节)。在

|和{}运算符在Python中的工作方式与在C中相同,因此,没有问题。在

在EOF,sys.stdin.read(1)返回一个空列表(因此[0]将失败,但您可以通过“分解”上述表达式来检查)。例如:

ateof = False

def getabyte():
    data = sys.stdin.read(1)
    if data: return False, ord(data)
    else: return True, 0

def getanint():
    global ateof
    ateof, byte1 = getabyte()
    if not ateof:
        ateof, byte2 = getabyte()
    if ateof: return True, 0
    else: return False, byte1 | (byte2<<8)

net of finicky问题wrt endianness(字节顺序)和字符的有符号性(C和Python共有的问题)。在

相关问题 更多 >

    热门问题