在英特尔® Galileo 或英特尔® Edison 上处理 Arduino* sketch 时,大家可能会遇到希望添加来自底层 Yocto* Linux 操作系统的部分功能的情况。 因此我们本篇博客的主题就是: 如何实现这两个领域之间的高效通信。我们首先定义一些需要遵从的标准:
标准
1、磁盘(SD 卡,eMMC)上没有通信,目的是降低磁盘磨损和提升性能
2、事件触发的通信,例如,尤其是我们不想定期检查状态,但希望在处于闲置状态时得到事件的通知
Linux 上的进程间通信 (IPC)
在英特尔® Galileo 或英特尔® Edison 上运行的 Arduino* sketch 实际上是 Linux 进程以并行的方式运行至其他 Linux 进程。 由于开发板上运行的 Linux 非常成熟,因此我们还可以使用标准方法实现 Arduino* 进程与本机进程之间的进程间通信 (IPC)。 Linux 提供多种 IPC 方法。 其中一种是 “内存映射 IPC”。 从本质上来说,它指的是 IPC 进程共享同一内存。 这意味着,只要共享该内存区域的任何一条进程进行任何更改,其他所有进程就会马上看到它所作出的更改。 它还符合我们第一条不在磁盘上写入通信数据的标准,但只在内存上操作。
互斥体和条件变量
共享内存会出现以下问题,比如:
1、如何确保只有一条进程在特定时间运算该共享数据? (同步)
2、如果数据发生变化,如何通知其他进程? (通知)
下面我们来回答这两个问题。 我们使用包含在 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 的进程。
在伪代码中:
1 pthread_mutex_lock(&mutex);
2
3 // read / write shared memory data here
4
5 pthread_mutex_unlock(&mutex);
必须以同样的方式进行,以锁定写入和读取访问,否则,读取操作会访问“只更新了一半”的数据。 接下来我们将介绍 Pthread 的另一个概念,即如何通知数据变化。
通知 - 条件变量
与互斥体概念类似,如果进程尝试访问已被锁定的互斥体,Pthread 将提供条件变量概念。 条件变量允许线程或(本案例中的)进程请求进入睡眠状态,直到通过变量被唤醒。 为此,需要采用函数 pthread_cond_wait。
互斥体和条件变量结合后,会产生以下伪代码:
1 pthread_mutex_lock(&mutex);
2 pthread_cond_wait(&cond_variable, &mutex);
3
4 // read shared memory data here
5
6 pthread_mutex_unlock(&mutex);
其他进程需要解锁互斥体,并通过调用 pthread_cond_signal 发出数据变化信号。 这样就会唤醒睡眠的进程。
如欲了解更多详情,请查阅有关 Pthread 的教材或在线教程。 下一部分,我们将介绍示例实施。
实施
部分说明:
1、就互斥体和条件变量而言,我们需要明确设置属性,以支持进程间的使用
2、由于 Arduino* IDE 不附带直接共享内存 IPC 所需的所有库,因此我们选择通过 内存映射文件利用共享内存 IPC。 从本质上讲,将通信文件放入映射至主内存的文件系统,可以提供相同的功能。 Edison 附带的 Yocto* Linux 以及 SD 卡 Yocto* 映像 (https://software.intel.com/iot) 包含 temp folder /tmp mounted to tmpfs(在内存中)。 例如,该文件夹中的所有文件都可以。我们选择文件 "/tmp/arduino"。 它仅适用于 IPC。
3、由于 Arduino 进程会在系统启动时开始,因此我们假设 Arduino 进程是要初始化互斥体和条件变量的进程。
4、我们仅展示 Arduino 进程等待运算 Linux 本机进程的数据的情况。 如要达到其他目的,代码必须进行相应的修改。
5、为了说明这一概念,我们如此放置数据,以共享内存映射结构 mmapData(定义 IO 8 的内置 LED 和外置 LED 是开启还是关闭)中的两个布尔变量:
1 bool led8_on; // led on IO8 bool led13_on; // built-in led
显而易见,这里也可以加入其他任何数据。 mmapData 结构中的其他两个变量分别为互斥体和条件变量
注:
MIT 许可证下方提供以下示例代码。
包含以下三个文件:
1、mmap.ino:放在 Arduino* IDE 上的sketch
2、mmap.cpp:发送数据的本机进程
3、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++ 编译器。 使用可能需运行的预安装编译器
1 g++ mmap.cpp -lpthread -o mmap
将 mmap.cpp 和 mmap.h 放在文件夹中, 这样会生成一个可以执行的二进制代码,如下所示:
1 ./mmap {0,1}{0,1}
其中,"{0,1}" 表示 0 或 1。 例如, "./mmap 00" 表示关闭两个 LED,"./mmap 11" 表示开启两个 LED。 其他针对 Arduino* IDE 上的 serial monitor 的输出,以及启动 Linux 本机进程的控制台的输出显示了另外已设置的数据。
mmap.ino
01 /*
02 * Author: Matthias Hahn
03 * Copyright (C) 2014 Intel Corporation
04 * This file is part of mmap IPC sample provided under the MIT license
05 *
06 * Permission is hereby granted, free of charge, to any person obtaining a copy
07 * of this software and associated documentation files (the "Software"), to deal
08 * in the Software without restriction, including without limitation the rights
09 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
25 #include "mmap.h"
26
27 using namespace std;
28
29 /* assume /tmp mounted on /tmpfs -> all operation in memory */
30 /* we can use just any file in tmpfs. assert(file size not modified && file permissions left readable) */
31 struct mmapData* p_mmapData; // here our mmapped data will be accessed
32
33 int led8 = 8;
34 int led13 = 13;
35
36
37 void exitError(const char* errMsg) {
38 /* print to the serial Arduino is attached to, i.e. /dev/ttyGS0 */
39 string s_cmd("echo 'error: ");
40 s_cmd = s_cmd + errMsg + " - exiting' > /dev/ttyGS0";
41 system(s_cmd.c_str());
42 exit(EXIT_FAILURE);
43 }
44
45 void setup() {
46 int fd_mmapFile; // file descriptor for memory mapped file
47 /* open file and mmap mmapData*/
48 fd_mmapFile = open(mmapFilePath, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
49 if (fd_mmapFile == -1) exitError("couldn't open mmap file");
50 /* make the file the right size - exit if this fails*/
51 if (ftruncate(fd_mmapFile, sizeof(struct mmapData)) == -1) exitError("couldn' modify mmap file");
52 /* memory map the file to the data */
53 /* assert(filesize not modified during execution) */
54 p_mmapData = static_cast
55 if (p_mmapData == MAP_FAILED) exitError("couldn't mmap");
56 /* initialize mutex */
57 pthread_mutexattr_t mutexattr;
58 if (pthread_mutexattr_init(&mutexattr) == -1) exitError("pthread_mutexattr_init");
59 if (pthread_mutexattr_setrobust(&mutexattr, PTHREAD_MUTEX_ROBUST) == -1) exitError("pthread_mutexattr_setrobust");
60 if (pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED) == -1) exitError("pthread_mutexattr_setpshared");
61 if (pthread_mutex_init(&(p_mmapData->mutex), &mutexattr) == -1) exitError("pthread_mutex_init");
62
63 /* initialize condition variable */
64 pthread_condattr_t condattr;
65 if (pthread_condattr_init(&condattr) == -1) exitError("pthread_condattr_init");
66 if (pthread_condattr_setpshared(&condattr, PTHREAD_PROCESS_SHARED) == -1) exitError("pthread_condattr_setpshared");
67 if (pthread_cond_init(&(p_mmapData->cond), &condattr) == -1) exitError("pthread_mutex_init");
68
69 /* for this test we just use 2 LEDs */
70 pinMode(led8, OUTPUT);
71 pinMode(led13, OUTPUT);
72 }
73
74 void loop() {
75 /* block until we are signalled from native code */
76 if (pthread_mutex_lock(&(p_mmapData->mutex)) != 0) exitError("pthread_mutex_lock");
77 if (pthread_cond_wait(&(p_mmapData->cond), &(p_mmapData->mutex)) != 0) exitError("pthread_cond_wait");
78
79 if (p_mmapData->led8_on) {
80 system("echo 8:1 > /dev/ttyGS0");
81 digitalWrite(led8, HIGH);
82 }
83 else {
84 system("echo 8:0 > /dev/ttyGS0");
85 digitalWrite(led8, LOW);
86 }
87 if (p_mmapData->led13_on) {
88 system("echo 13:1 > /dev/ttyGS0");
89 digitalWrite(led13, HIGH);
90 }
91 else {
92 system("echo 13:0 > /dev/ttyGS0");
93 digitalWrite(led13, LOW);
94 }
95 if (pthread_mutex_unlock(&(p_mmapData->mutex)) != 0) exitError("pthread_mutex_unlock");
96 }
mmap.cpp
01 /*
02 * Author: Matthias Hahn
03 * Copyright (C) 2014 Intel Corporation
04 * This file is part of mmap IPC sample provided under the MIT license
05 *
06 * Permission is hereby granted, free of charge, to any person obtaining a copy
07 * of this software and associated documentation files (the "Software"), to deal
08 * in the Software without restriction, including without limitation the rights
09 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
25 /* mmap.cpp
26 Linux native program communicating via memory mapped data with Arduino sketch.
27 Compilation: g++ mmap.cpp -lpthread -o mmap
28 Run: ./mmap
29 For "random" blink you may run following commands in the command line:
30 while [ 1 ]; do ./mmap $(($RANDOM % 2))$(($RANDOM % 2)); done
31 */
32
33 #include "mmap.h"
34
35 void exitError(const char* errMsg) {
36 perror(errMsg);
37 exit(EXIT_FAILURE);
38 }
39
40
41 using namespace std;
42
43
44 /**
45 * @brief: for this example uses a binary string "
46 * if no arg equals "00"
47 * For "random" blink you may run following commands in the command line:
48 * while [ 1 ]; do ./mmap $(($RANDOM % 2))$(($RANDOM % 2)); done
49 */
50 int main(int argc, char** argv) {
51 struct mmapData* p_mmapData; // here our mmapped data will be accessed
52 int fd_mmapFile; // file descriptor for memory mapped file
53
54 /* Create shared memory object and set its size */
55 fd_mmapFile = open(mmapFilePath, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
56 if (fd_mmapFile == -1) exitError("fd error; check errno for details");
57
58 /* Map shared memory object read-writable */
59 p_mmapData = static_cast
60 if (p_mmapData == MAP_FAILED) exitError("mmap error");
61 /* the Arduino sketch might still be reading - by locking this program will be blocked until the mutex is unlocked from the reading sketch
62 * in order to prevent race conditions */
63 if (pthread_mutex_lock(&(p_mmapData->mutex)) != 0) exitError("pthread_mutex_lock");
64 if (argc == 1) {
65 cout "8:0" endl;
66 cout "13:0" endl;
67 p_mmapData->led8_on = false;
68 p_mmapData->led13_on = false;
69 }
70 else if (argc > 1) {
71 // assert(correct string given)
72 int binNr = atol(argv[1]);
73 if (binNr >= 10) {
74 cout "8:1" endl;
75 p_mmapData->led8_on = true;
76 }
77 else {
78 cout "8:0" endl;
79 p_mmapData->led8_on = false;
80 }
81 binNr %= 10;
82 if (binNr == 1) {
83 cout "13:1" endl;
84 p_mmapData->led13_on = true;
85 }
86 else {
87 cout "13:0" endl;
88 p_mmapData->led13_on = false;
89 }
90 }
91 // signal to waiting thread
92 if (pthread_mutex_unlock(&(p_mmapData->mutex)) != 0) exitError("pthread_mutex_unlock");
93 if (pthread_cond_signal(&(p_mmapData->cond)) != 0) exitError("pthread_cond_signal");
94 }
mmap.h
01 /*
02 * Author: Matthias Hahn
03 * Copyright (C) 2014 Intel Corporation
04 * This file is part of mmap IPC sample provided under the MIT license
05 *
06 * Permission is hereby granted, free of charge, to any person obtaining a copy
07 * of this software and associated documentation files (the "Software"), to deal
08 * in the Software without restriction, including without limitation the rights
09 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
25 #ifndef MMAP_HPP
26 #define MMAP_HPP
27
28 #include
29 #include
30 #include
31 #include
32 #include
33 #include
34 #include
35 #include
37 /* assert(/tmp mounted to tmpfs, i.e. resides in RAM) */
38 /* just use any file in /tmp */
39 static const char* mmapFilePath = "/tmp/arduino";
40
41
42 struct mmapData {
43 bool led8_on; // led on IO8
44 bool led13_on; // built-in led
45 pthread_mutex_t mutex;
46 pthread_cond_t cond;
47 };
48
49 #endif
文章来源:英特尔开发人员专区