在英特尔® Galileo 或英特尔® Edison 上处理 Arduino* sketch 时,大家可能会遇到希望添加来自底层 Yocto* Linux 操作系统的部分功能的情况。 因此我们本篇博客的主题就是: 如何实现这两个领域之间的高效通信。我们首先定义一些需要遵从的标准
在英特尔® 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 的教材或在线教程。 下一部分,我们将介绍示例实施。
部分说明:
bool led8_on; // led on IO8 bool led13_on; // built-in led显而易见,这里也可以加入其他任何数据。 mmapData 结构中的其他两个变量分别为互斥体和条件变量
MIT 许可证 下方提供以下示例代码。
包含以下三个文件:
例如,如果用于 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 本机进程的控制台的输出显示了另外已设置的数据。
/* * 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"); }
/* * 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[1]); 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"); }
/* * 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. */ #ifndef MMAP_HPP #define MMAP_HPP #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <iostream> #include <string.h> #include <stdlib.h> #include <cstdio> #include <pthread.h> /* assert(/tmp mounted to tmpfs, i.e. resides in RAM) */ /* just use any file in /tmp */ static const char* mmapFilePath = "/tmp/arduino"; struct mmapData { bool led8_on; // led on IO8 bool led13_on; // built-in led pthread_mutex_t mutex; pthread_cond_t cond; }; #endif