隔壁他二叔 发表于 2016-5-14 10:02:05

ARDUINO* 和 LINUX 本地进程实现高效通信

ARDUINO* 和 LINUX 本地进程实现高效通信
Matthias H. (Intel), Hai Shen (Intel), 2016 年 4 月 17 日

在英特尔® Galileo 或英特尔® Edison 上处理 Arduino* sketch 时,大家可能会遇到希望添加来自底层 Yocto* Linux 操作系统的部分功能的情况。 因此我们本篇博客的主题就是: 如何实现这两个领域之间的高效通信。我们首先定义一些需要遵从的标准标准
[*]磁盘(SD 卡,eMMC)上没有通信,目的是降低磁盘磨损和提升性能
[*]事件触发的通信,例如,尤其是我们不想定期检查状态,但希望在处于闲置状态时得到事件的通知
Linux 上的进程间通信 (IPC)在英特尔® Galileo 或英特尔® Edison 上运行的 Arduino* sketch 实际上是 Linux 进程以并行的方式运行至其他 Linux 进程。 由于开发板上运行的 Linux 非常成熟,因此我们还可以使用标准方法实现 Arduino* 进程与本机进程之间的进程间通信 (IPC)。 Linux 提供多种 IPC 方法。 其中一种是 “内存映射 IPC”。 从本质上来说,它指的是 IPC 进程共享同一内存。 这意味着,只要共享该内存区域的任何一条进程进行任何更改,其他所有进程就会马上看到它所作出的更改。 它还符合我们第一条不在磁盘上写入通信数据的标准,但只在内存上操作。互斥体和条件变量共享内存会出现以下问题,比如:
[*]如何确保只有一条进程在特定时间运算该共享数据? (同步)
[*]如果数据发生变化,如何通知其他进程? (通知)
下面我们来回答这两个问题。 我们使用包含在 POSIX 线程 (Pthread) 库(支持 Linux)之中的 “互斥体” 和 “条件变量”。同步 - 互斥体互斥 (mutex) 是所有多任务操作系统都会提供的一种标准概念。 在本博客中,我们不介绍概念和详情,只提供有关 POSIX 线程 (Pthread) 互斥体的高级信息。 如欲了解更多信息,请查阅有关操作系统的教材(比如 Tanenbaum, Woodhull: Operating Systems 3rd ed. Pearson 2006),或上网搜索。顾名思义,Pthread 库主要专注于线程编程。 然而,它还提供适用于进程的强大指令。 而且,分别面向英特尔® Galileo 和英特尔® Edison 的 Arduino* IDE 也支持即购即用 pthread(比如,pthread 库链接),因此可轻松集成。 所以,使用 Pthread 来满足我们的要求似乎是自然而然的选择。通常,互斥体可确保一条线程仅访问代码的某个关键区域。 此处在处理进程时,我们使用互斥体的方法是,只有一条进程可以在代码中继续 pthread_mutex_lock 请求。 操作系统将其他所有进程设置为睡眠状态,直到互斥体调用 pthread_mutex_unlock,之后操作系统将唤醒其他请求pthread_mutex_lock 的进程。在伪代码中:pthread_mutex_lock(&mutex);

// read / write shared memory data here

pthread_mutex_unlock(&mutex);
必须以同样的方式进行,以锁定写入和读取访问,否则,读取操作会访问“只更新了一半”的数据。 接下来我们将介绍 Pthread 的另一个概念,即如何通知数据变化。通知 - 条件变量与互斥体概念类似,如果进程尝试访问已被锁定的互斥体,Pthread 将提供条件变量概念。 条件变量允许线程或(本案例中的)进程请求进入睡眠状态,直到通过变量被唤醒。 为此,需要采用函数 pthread_cond_wait。互斥体和条件变量结合后,会产生以下伪代码:pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond_variable, &mutex);

// read shared memory data here

pthread_mutex_unlock(&mutex);
其他进程需要解锁互斥体,并通过调用 pthread_cond_signal 发出数据变化信号。 这样就会唤醒睡眠的进程。如欲了解更多详情,请查阅有关 Pthread 的教材或在线教程。 下一部分,我们将介绍示例实施。实施部分说明:
[*]就互斥体和条件变量而言,我们需要明确设置属性,以支持进程间的使用
[*]由于 Arduino* IDE 不附带直接共享内存 IPC 所需的所有库,因此我们选择通过 内存映射文件利用共享内存 IPC。 从本质上讲,将通信文件放入映射至主内存的文件系统,可以提供相同的功能。 Edison 附带的 Yocto* Linux 以及 SD 卡 Yocto* 映像 (https://software.intel.com/iot) 包含 temp folder /tmp mounted totmpfs(在内存中)。 例如,该文件夹中的所有文件都可以。我们选择文件 "/tmp/arduino"。 它仅适用于 IPC。
[*]由于 Arduino 进程会在系统启动时开始,因此我们假设 Arduino 进程是要初始化互斥体和条件变量的进程。
[*]我们仅展示 Arduino 进程等待运算 Linux 本机进程的数据的情况。 如要达到其他目的,代码必须进行相应的修改。
[*]为了说明这一概念,我们如此放置数据,以共享内存映射结构 mmapData(定义 IO 8 的内置 LED 和外置 LED 是开启还是关闭)中的两个布尔变量:
bool led8_on;   // led on IO8 bool led13_on;// built-in led
显而易见,这里也可以加入其他任何数据。 mmapData 结构中的其他两个变量分别为互斥体和条件变量
注:MIT 许可证下方提供以下示例代码。包含以下三个文件:
[*]mmap.ino:放在 Arduino* IDE 上的sketch
[*]mmap.cpp:发送数据的本机进程
[*]mmap.h:标头文件 - 用于 Arduino* IDE 和 Linux native 的同一个文件
例如,如果用于 Arduino*,Arduino* sketch 目录中应该有一个包含 "mmap.ino" 和 "mmap.h" 的文件夹。 如果用于 Linux native,应该有一个包含 "mmap.cpp" 和 "mmap.h" 的文件夹。如需运行 sketch,只需打开 Arduino* IDE 中的 "mmap" sketch,并将其上传至相应的开发板(第一代英特尔® Galileo,第二代英特尔® Galileo,或英特尔® Edison)。 如果用于 native,英特尔物联网开发人员套件 (https://software.intel.com/iot) 附带了一个交叉编译器,英特尔® Edison 附带了 Yocto* Linux 和 SD 卡 Yocto* 映像 fon ( https://software.intel.com/iot),英特尔® Galileo 附带了一个预安装的 C++ 编译器。 使用可能需运行的预安装编译器g++mmap.cpp   -lpthread -o mmap
将 mmap.cpp 和 mmap.h 放在文件夹中, 这样会生成一个可以执行的二进制代码,如下所示:./mmap {0,1}{0,1}
其中,"{0,1}" 表示 0 或 1。 例如, "./mmap 00" 表示关闭两个 LED,"./mmap 11" 表示开启两个 LED。 其他针对 Arduino* IDE 上的 serial monitor 的输出,以及启动 Linux 本机进程的控制台的输出显示了另外已设置的数据。mmap.ino/*
* Author: Matthias Hahn <matthias.hahn@intel.com>
* Copyright (C) 2014 Intel Corporation
* This file is part of mmap IPC sample provided under the MIT license
*
* 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 "mmap.h"

using namespace std;

/* assume /tmp mounted on /tmpfs -> all operation in memory */
/* we can use just any file in tmpfs. assert(file size not modified && file permissions left readable) */
struct mmapData* p_mmapData; // here our mmapped data will be accessed

int led8 = 8;
int led13 = 13;


void exitError(const char* errMsg) {
/* print to the serial Arduino is attached to, i.e. /dev/ttyGS0 */
string s_cmd("echo 'error: ");
s_cmd = s_cmd + errMsg + " - exiting' > /dev/ttyGS0";
system(s_cmd.c_str());
exit(EXIT_FAILURE);
}

void setup() {
int fd_mmapFile; // file descriptor for memory mapped file
/* open file and mmap mmapData*/
fd_mmapFile = open(mmapFilePath, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd_mmapFile == -1) exitError("couldn't open mmap file");
/* make the file the right size - exit if this fails*/
if (ftruncate(fd_mmapFile, sizeof(struct mmapData)) == -1) exitError("couldn' modify mmap file");
/* memory map the file to the data */
/* assert(filesize not modified during execution) */
p_mmapData = static_cast<struct mmapData*>(mmap(NULL, sizeof(struct mmapData), PROT_READ | PROT_WRITE, MAP_SHARED, fd_mmapFile, 0));
if (p_mmapData == MAP_FAILED) exitError("couldn't mmap");
/* initialize mutex */
pthread_mutexattr_t mutexattr;
if (pthread_mutexattr_init(&mutexattr) == -1) exitError("pthread_mutexattr_init");
if (pthread_mutexattr_setrobust(&mutexattr, PTHREAD_MUTEX_ROBUST) == -1) exitError("pthread_mutexattr_setrobust");
if (pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED) == -1) exitError("pthread_mutexattr_setpshared");
if (pthread_mutex_init(&(p_mmapData->mutex), &mutexattr) == -1) exitError("pthread_mutex_init");

/* initialize condition variable */
pthread_condattr_t condattr;
if (pthread_condattr_init(&condattr) == -1) exitError("pthread_condattr_init");
if (pthread_condattr_setpshared(&condattr, PTHREAD_PROCESS_SHARED) == -1) exitError("pthread_condattr_setpshared");
if (pthread_cond_init(&(p_mmapData->cond), &condattr) == -1) exitError("pthread_mutex_init");

/* for this test we just use 2 LEDs */
pinMode(led8, OUTPUT);
pinMode(led13, OUTPUT);
}

void loop() {
/* block until we are signalled from native code */
if (pthread_mutex_lock(&(p_mmapData->mutex)) != 0) exitError("pthread_mutex_lock");
if (pthread_cond_wait(&(p_mmapData->cond), &(p_mmapData->mutex)) != 0) exitError("pthread_cond_wait");

if (p_mmapData->led8_on) {
    system("echo 8:1 > /dev/ttyGS0");
    digitalWrite(led8, HIGH);
}
else {
    system("echo 8:0 > /dev/ttyGS0");
    digitalWrite(led8, LOW);
}
if (p_mmapData->led13_on) {
    system("echo 13:1 > /dev/ttyGS0");
    digitalWrite(led13, HIGH);
}
else {
    system("echo 13:0 > /dev/ttyGS0");
    digitalWrite(led13, LOW);
}
if (pthread_mutex_unlock(&(p_mmapData->mutex)) != 0) exitError("pthread_mutex_unlock");
}
mmap.cpp
/*
* Author: Matthias Hahn <matthias.hahn@intel.com>
* Copyright (C) 2014 Intel Corporation
* This file is part of mmap IPC sample provided under the MIT license
*
* 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.
*/

/* mmap.cpp
   Linux native program communicating via memory mapped data with Arduino sketch.
   Compilation: g++mmap.cpp   -lpthread -o mmap
   Run: ./mmap <LED8><LED13> (e.g. ./mmap 01 -> LED 8 off, LED 13 on)
   For "random" blink you may run following commands in the command line:
   while [ 1 ]; do ./mmap $(($RANDOM % 2))$(($RANDOM % 2)); done
*/

#include "mmap.h"

void exitError(const char* errMsg) {
perror(errMsg);
exit(EXIT_FAILURE);
}


using namespace std;


/**
* @brief: for this example uses a binary string "<led8><led13>"; e.g. "11": both leds on
* if no arg equals "00"
* For "random" blink you may run following commands in the command line:
* while [ 1 ]; do ./mmap $(($RANDOM % 2))$(($RANDOM % 2)); done
*/
int main(int argc, char** argv) {
struct mmapData* p_mmapData; // here our mmapped data will be accessed
int fd_mmapFile; // file descriptor for memory mapped file

/* Create shared memory object and set its size */
fd_mmapFile = open(mmapFilePath, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd_mmapFile == -1) exitError("fd error; check errno for details");

/* Map shared memory object read-writable */
p_mmapData = static_cast<struct mmapData*>(mmap(NULL, sizeof(struct mmapData), PROT_READ | PROT_WRITE, MAP_SHARED, fd_mmapFile, 0));
if (p_mmapData == MAP_FAILED) exitError("mmap error");
/* the Arduino sketch might still be reading - by locking this program will be blocked until the mutex is unlocked from the reading sketch
   * in order to prevent race conditions */
if (pthread_mutex_lock(&(p_mmapData->mutex)) != 0) exitError("pthread_mutex_lock");
if (argc == 1) {
    cout << "8:0" << endl;
    cout << "13:0" << endl;
    p_mmapData->led8_on = false;
    p_mmapData->led13_on = false;
}
else if (argc > 1) {
    // assert(correct string given)
    int binNr = atol(argv);
    if (binNr >= 10) {
      cout << "8:1" << endl;
      p_mmapData->led8_on = true;
    }
    else {
      cout << "8:0" << endl;
      p_mmapData->led8_on = false;
    }
    binNr %= 10;
    if (binNr == 1) {
      cout << "13:1" << endl;
      p_mmapData->led13_on = true;
    }
    else {
      cout << "13:0" << endl;
      p_mmapData->led13_on = false;
    }
}
// signal to waiting thread
if (pthread_mutex_unlock(&(p_mmapData->mutex)) != 0) exitError("pthread_mutex_unlock");
if (pthread_cond_signal(&(p_mmapData->cond)) != 0) exitError("pthread_cond_signal");
}



页: [1]
查看完整版本: ARDUINO* 和 LINUX 本地进程实现高效通信