gpt4 book ai didi

c++ - 如何通过串行端口接收 JPEG 图像

转载 作者:太空狗 更新时间:2023-10-29 23:14:09 24 4
gpt4 key购买 nike

因此,我尝试使用 Xbee Series 1 将 jpeg 图像 (4Kb) 从树莓派无线发送到我的 Mac。我在树莓派上有一张图像,可以将其读入二进制格式。我已经使用这种二进制格式将其保存到另一个图像文件中,并且它正确地创建了图像的拷贝。这告诉我我正在正确阅读它。所以我试图通过串行端口(由 xbee 传输)将该数据发送到我的 Mac。旁注,我认为 Xbee 只能传输每个数据包 80 字节的数据。我不知道这会如何影响我正在做的事情。

我的问题是,我不知道如何读取数据并将其正确存储到 jpeg 文件本身。我发现的大多数 Read() 函数都要求您输入要读取的长度,但我不知道如何判断它有多长,因为它只是一个串行流。

这是我发送 jpeg 的代码。

#include "xSerial.hpp"
#include <iostream>
#include <cstdlib>
using namespace std;

int copy_file( const char* srcfilename, const char* dstfilename );


int main(){

copy_file("tylerUseThisImage.jpeg", "copyImage.jpeg");

return 0;
}

int copy_file( const char* srcfilename, const char* dstfilename )
{
long len;
char* buf = NULL;
FILE* fp = NULL;

// Open the source file
fp = fopen( srcfilename, "rb" );
if (!fp) return 0;

// Get its length (in bytes)
if (fseek( fp, 0, SEEK_END ) != 0) // This should typically succeed
{ // (beware the 2Gb limitation, though)
fclose( fp );
return 0;
}

len = ftell( fp );
std::cout << len;
rewind( fp );
// Get a buffer big enough to hold it entirely
buf = (char*)malloc( len );
if (!buf)
{
fclose( fp );
return 0;
}

// Read the entire file into the buffer
if (!fread( buf, len, 1, fp ))
{
free( buf );
fclose( fp );
return 0;
}

fclose( fp );

// Open the destination file
fp = fopen( dstfilename, "wb" );
if (!fp)
{
free( buf );
return 0;
}
// this is where I send data in but over serial port.
//serialWrite() is just the standard write() being used
int fd;
fd = xserialOpen("/dev/ttyUSB0", 9600);
serialWrite(fd, buf, len);

//This is where the file gets copied to another file as a test
// Write the entire buffer to file
if (!fwrite( buf, len, 1, fp ))
{
free( buf );
fclose( fp );
return 0;
}

// All done -- return success
fclose( fp );
free( buf );
return 1;
}

在接收端,我知道我需要打开串行端口来读取和使用某种 read(),但我不知道这是如何完成的。使用串行库,它具有一些功能来检查串行数据是否可用并返回可读取的字符数。

关于可供读取的字符数的一个问题,这个数字会随着串行流的到来而增长,还是会立即告诉要读取的数据的整个长度?

但最后,我知道在打开串行端口后,我需要将数据读入缓冲区,然后将该缓冲区写入文件,但我没有任何运气。这是我迄今为止尝试过的。

// Loop, getting and printing characters
char temp;
bool readComplete = false;
int bytesRead = 0;

fp = fopen("copyImage11.jpeg", "rwb");

for (;;)
{
if(xserialDataAvail(fd) > 0)
{
bytesRead = serialRead(fd, buf, len);
readComplete = true;
}
if (readComplete)
{
if (!fwrite(buf, bytesRead, 1, fp))
{
free(buf);
fclose(fp);
return 0;
}

fclose(fp);
free(buf);
return 1;
}
}

我的代码没有出现错误,它只是没有正确创建 jpeg 文件。也许我没有正确传输它,或者我没有正确读取/写入文件。任何帮助,将不胜感激。谢谢大家摇滚!

最佳答案

如果您正在定义自己的协议(protocol),那么您首先需要有一个发送长度的方法。

我建议通过发送短的 ascii 文本 block 来测试您的代码,以确认您的输入/输出。一旦成功,您就可以使用 ascii 设置传输;即发送长度,并让您的接收器准备好接收预期的 block 。

关于c++ - 如何通过串行端口接收 JPEG 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35468757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com