1. 程式人生 > >嵌入式設計模式(Design Patterns for Embedded Systems in C)的學習記錄

嵌入式設計模式(Design Patterns for Embedded Systems in C)的學習記錄

  工作三年有餘,一直在搞嵌入式。準確的說從大學開始就一直在搞,已經到了病入膏肓的地步。此間總是不時出現一些奇怪的想法:人家搞Java、搞C#的動不動就是什麼架構/框架的,搞了這麼久的的嵌入式,我到底搞了什麼?架構/框架?統統木聽說過。。。似乎那些高大上的東西都是針對上層程式設計的!難道嵌入式就這麼Low麼?   最近終於靜下心來,有功夫讀了讀Bruce Powel Douglass的《Design Patterns for Embedded Systems in C》。讀完全書用了好久。。在書中發現了不少更加系統化的東西,一些在實際工作中用到的但是不知道其準確定義的東西!但是,也同時發現,好多東西完全看不懂。。。以下內容主要是邊讀邊記錄的一些自己感覺有用的知識點,除此之外沒有任何意義!

(1)最開始看了看這本書的中文翻譯版,看看了裡面有些翻譯看不懂(沒辦法,水平太低,可能還沒有理解那些高深的東西)! (2)貌似在這本書中,作者都是以面向物件的思想來進行舉例說明的。如果你是一個純嵌入式底層人員,對於面向物件可能有些陌生。 (3)以下內容不是翻譯!不是翻譯!不是翻譯!僅僅是在看書的時候覺得有用的東西,做一下記錄而已。其中有些部分確實不懂,均已??處理。

看的第一部分

  主要就是本書的前三個章節。陸陸續續看完,這部分看完比較早,先記錄一下。下面這些英文標題、章節名稱,與原書中的標題是一致的。

CHAPTER 1 What Is Embedded Programming?

1.1 What’s Special About Embedded Systems?

  An important subset of embedded systems are real-time systems(實時系統是嵌入式系統的一個重要子集). Many people have the mistaken impression that “real time” means “real fast” but that is not true(很多人錯誤的認為“實時”就是“真正的快”,這是不正確的). A real-time system is one in which timeliness constraints must be satisfied for system correctness(滿足實時性約束的). A common, if simplistic, categorization of real-time systems is into two groups(分為兩大類). “Hard” real-time systems(“硬”實時系統) are ones in which timeliness constraints are modeled as deadlines, points in time by which the execution of specific actions are required to be complete(完全以時間作為實時性約束條件,時間到之前必須完成指定動作). “Soft” real-time systems(“軟”實時系統) are those that are not “hard”; that is, some other (usually stochastic) measure than deadlines is used to determine timeliness(引入除時間限制外的其他實時性約束條件). This may include average throughput(平均吞吐量), average execution time(平均執行時間), maximum burst length(最大脈衝長度), or some other measure. All systems may be modeled as hard real-time systems, but this often results in “over-designing” the system to be faster or have more available resources than is necessary, raising the recurring cost (approximately “manufacturing cost”) of the system.

1.1.1 Embedded Design Constraints

  From the inside, one of the most striking characteristics of embedded systems is severity of their constraints(從內部來看,嵌入式系統的一個顯著地特點就是嚴格的約束條件).   Reliability, robustness, and safety are other kinds of constraints levied on embedded systems(可靠性、健壯性、安全性是嵌入式系統需要遵循的另一些約束條件).

1.1.3 OS, RTOS, or Bareback?

  RTOSs run applications and tasks using one of three basic design schemas(三種基本設計模式中的一種). Event-driven systems handle events as they arise and schedule tasks to handle the processing(事件驅動的系統通過任務排程器來處理出現的多個任務). Most such systems use task priority as a quantitative means by which to determine which task will run if multiple tasks are ready to run(通過任務優先順序來決定哪個就緒的任務來執行). Task priorities are most often static(任務優先順序通常為靜態的) (i.e., specified at design time as such with rate-monotonic scheduling) but some are dynamic(也有動態的), varying the task priorities to account for current operating conditions (such as earliest deadline first scheduling*). The other two approaches to task scheduling implement a “fairness doctrine” either by giving all tasks a periodic time slice in which to run (time-base schemas, such as ***round robin scheduling(輪詢排程)***) or by running the task set cyclically (sequence-based schemas, such as cyclic executive scheduling).

1.1.4 Embedded Middleware

  中介軟體在實際工作中,還是經常用到的!

1.1.6 Debugging and Testing

  The state of the art in developing defect-free software is an agile practice known as ***test-driven development (TDD)***(開發沒有缺陷的軟體的最先進的方法被稱為測試驅動開發). In TDD, the unit tests for a piece of software are written simultaneously with, or even slightly before, the software it will verify(單元測試程式要與主程式同時編寫,甚至提前編寫).   There are many different kinds of unit tests that can be applied to software in general and embedded software in particular. These include(軟體常用的單元測試分類如下):

  • Functional(功能) – tests the behavior or functionality of a system or system element(測試功能是否完善)
  • Quality of Service(服務質量) – tests the “performance” of a system or system element, often to measure the performance of the system or element against its performance requirements (測試效能是否達標)
  • Precondition tests(先決條件) – tests that the behavior of the system or system element is correct in the case that the preconditional invariants are met and in the case that the preconditional invariants are violated (測試預定的條件滿足或者不滿足時,系統的表現)
  • Range(區間) – tests values within a data range
  • Statistical(統計) – tests values within a range by selecting them stochastically from a probability density function (PDF)
  • Boundary(邊界) – tests values just at the edges of, just inside, and just outside a data range (測試區間邊界內、邊界上及邊界外的值)
  • Coverage(覆蓋率) – tests that all execution paths are executed during a test suite
  • Stress(壓力) – tests data that exceeds the expected bandwidth of a system or system element
  • Volume(容積) – also known as “load testing(負載測試)” – tests the system with large amounts of data that meet or exceed its design load
  • Fault Seeding(故障播種?) – tests in which a fault is intentionally introduced to the system to ensure the system handles it properly (這個應該是指故意引入一些錯誤,看看系統反應)
  • Regression tests(迴歸測試) – normally a subset of previously passed tests to ensure that modification to a system did not introduce errors into previously correctly functioning systems

  In a desktop system, unit testing software with test cases that explore all of these concerns is rare (and difficult) enough. When you embedded that software on a less-accessible target platform it becomes even more difficult. A number of different strategies can be employed to execute test cases, such as(這裡主要是說,寫測試用例是,要覆蓋全部的問題是非常困難的,尤其是在嵌入式平臺上,以下是一些嵌入式平臺常用的測試手段)

  • “printf” testing – tests the system by writing to a file or to stdout (使用printf列印可能的錯誤,這個非常常用!)
  • “Test buddies” – writing test fixtures that embed the test cases in their own functionality
  • Testing on host – performing most of the tests on the host platforms using a host native complier and a critical subset on the target platform using a cross compiler (這個在嵌入式Linux中非常常用,其他也可以通過硬體偵錯程式來實現)
  • Simulating on host – simulating the target platform on the host with cross-compiled software and retesting a critical subset on the target with the same object code (許多開發工具中自帶軟體模擬功能,基本可以模擬硬體執行,可以試著用用,但是通常會使用硬體偵錯程式來實現硬體除錯)
  • Commercial software testing tools – using software testing tools, such as TestRT™, LDRA™, or VectorCAST™ (主要是使用一些軟體追蹤器)
  • Commercial hardware-software integrated tools – this includes tools such as logic analyzers, in-circuit emulators, JTAG-compliant testing tools, and ROM emulators (使用硬體偵錯程式)

1.2 OO or Structured – It’s Your Choice

Structured programming:

  • On one hand, functions or procedures form the foundation of behavioral programming(函式和過程形成基本的程式設計基礎)
  • The other side of structured programming is the notion of data structuring(資料的結構化).

OO:Object-oriented programming is based on an orthogonal paradigm(面向物件程式設計基於正交正規化).

(1)這本書採用了基於面向物件的程式設計思想,因此後續章節講了如何用C語言來模擬面向物件的思想。 (2)基本的模擬方法就是用結構體來封裝資料和方法(函式指標) (3)如果想要詳細瞭解C實現面向物件的思想,光看本書這一點章節中的東西是遠遠不夠的!

CHAPTER 2 Embedded Programming with The HarmonyTMHarmony^{TM} for Embedded RealTime Process

  整個第二章主要就是以作者自己搞得Harmony™ for Embedded RealTime為例,來講解如何進行嵌入式系統設計。?至於這個東西是個啥我還沒搞清楚?!

2.1.2 What Is a Design Pattern?

  A design pattern is “a generalized solution to a commonly occurring problem.” (設計模式是對經常出現的問題的通解)To be a pattern, the problem must recur often enough to be usefully generalizable and the solution must be general enough to be applied in a wide set of application domains. If it only applies to a single application domain, then it is probably an analysis pattern5. Analysis patterns define ways for organizing problem-specific models and code for a particular application domain.

CHAPTER 3 Design Patterns for Accessing Hardware

  整個第三章主要講了各種訪問硬體的設計模式。   Probably the most distinguishing property of embedded systems is that they must access hardware directly. Broadly, software-accessible hardware can be categorized into four kinds – infra­structure, communications, sensors, and actuators(大體上,嵌入式軟體可訪問的硬體可以分為四類:基礎設施、通訊、感測器和致動器).   Let’s turn our attention now to a number of design patterns that have proven themselves useful for the manipulation of hardware(開始介紹設計模式). The Hardware Proxy Pattern, discussed next, is an archetypal pattern for the abstraction of hardware for the purpose of encapsulating details that are likely to change from the usage of the information provided to or by the hardware(接下來討論的硬體代理模式是以封裝詳細資訊為目的的硬體抽象模式的一個比較典型的模式,這裡沒明白!). The Hardware Adapter Pattern extends the Hardware Proxy Pattern to provide the ability to support different hardware interfaces(硬體適配模式主要是擴充套件硬體代理抹模式,以提供支援不同硬體介面的能力). The Mediator Pattern supports coordination of multiple hardware devices to achieve a system level behavior(中介模式支援多個硬體裝置的協調以實現系統級行為). The Observer Pattern is a way of distributing sensed data to the software elements that need it(觀察者模式是將感測資料分發給需要它的軟體元素的一種方式). The Debouncing and Interrupt Patterns are simple reusable approaches to interface with hardware devices(去抖動和中斷模式是與硬體裝置介面的簡單可重用方法). The Timer Interrupt Pattern extends the Interrupt timer to provide accurate timing for embedded systems(定時器中斷模式擴充套件了中斷定時器,為嵌入式系統提供準確的定時).

Hardware Proxy Pattern(硬體代理模式)

  The Hardware Proxy Pattern creates a software element responsible for access to a piece of hardware and encapsulation of hardware compression and coding implementation(硬體代理模式建立一個軟體元素,負責訪問硬體並封裝硬體壓縮和編碼實現).

Hardware Adapter Pattern(硬體適配模式)

  The Hardware Adapter Pattern extends the Hardware Proxy Pattern to provide the ability to support different hardware interfaces.   The Hardware Adapter Pattern provides a way of adapting an existing hardware interface into the expectations of the application. This pattern is a straightforward derivative of the Adapter Pattern.

Mediator Pattern(中介者模式)

  The Mediator Pattern supports coordination of multiple hardware devices to achieve a system level behavior.   The Mediator Pattern provides a means of coordinating a complex interaction among a set of elements.

Observer Pattern(觀察者模式)

  The Observer Pattern is a way of distributing sensed data to the software elements that need it.   The Observer Pattern is one of the most common patterns around. When present, it provides a means for objects to “listen in” on others while requiring no modifications whatsoever to the data servers. In the embedded domain, this means that sensor data can be easily shared to elements that may not even exist when the sensor proxies are written.

Debouncing Pattern(去抖模式)

  This simple pattern is used to reject multiple false events arising from intermittent contact of metal surfaces.   Push buttons, toggle switches, and electromechanical relays are input devices for digital systems that share a common problem – as metal connections make contact, the metal deforms or “bounces”, producing intermittent connections during switch open or closure. Since this happens very slowly (order of milliseconds) compared to the response speed of embedded systems (order of microseconds or faster), this results in multiple electronic signals to the control system. This pattern addresses this concern by reducing the multiple signals into a single one by waiting a period of time after the initial signal and then checking the state(嵌入式的許多輸入裝置,例如按鍵、開關等受制於物理限制,其響應速度與嵌入式裝置處理速度不是一個數量級) 按鍵 去抖模式

Interrupt Pattern(中斷模式)

  The physical world is fundamentally both concurrent and asynchronous; it’s nonlinear too, but that’s a different story. Things happen when they happen and if your embedded system isn’t paying attention, those occurrences may be lost. Interrupt handlers (a.k.a. Interrupt Service Routines, or ISRs) are a useful way to be notified when an event of interest occurs even if your embedded system is off doing other processing. 中斷模式

Polling Pattern(輪詢模式)

  Another common pattern for getting sensor data or signals from hardware is to check periodi­cally, a process known as polling(通過週期性訪問來獲取資料,即為輪詢). Polling is useful when the data or signals are not so urgent that they cannot wait until the next polling period to be received or when the hardware isn’t capable of generating interrupts when data or signals become available(非緊急性資料或沒有中斷時,該模式非常有用!).   This pattern comes in two flavors(這個模式有兩種版本). Figure 3-17 shows the pattern structure for opportunistic polling(機會輪詢) while Figure 3-18 shows the pattern for periodic polling(週期輪詢). The difference is that in the former pattern the applicationFunction will embed calls to poll() when convenient, and in the latter, a timer is created to start polling(區別是:前者是在何時的實際去輪詢,而後者則是在定時器中輪詢). 機會輪詢 定時輪詢   Periodic polling is a special case of the Interrupt Pattern(週期輪序時中斷模式的一個特殊情況). In addition, the hardware checks may be done by invoking data acquisition services of Hardware Proxies or Hardware Adapters. In addition, the Observer Pattern can be merged in as well, with the polling element (Opportu­nisticPoller or PeriodicPoller) serving as the data server and the PollDataClients serving as the data clients.

看的第二部分

  主要就是本書的第四、五、六三個章節。相比於前面的幾個章節,該部分在實際中接觸使用的更加多。

CHAPTER 4 Design Patterns for Embedding Concurrency and Resource Management

先跳過,看看後面的狀態機

CHAPTER 5 Design Patterns for State Machines

  狀態機在嵌入式設計中是非常常見的,在裸機程式中是一種相當有效穩定的模式。本書的第五章就是對狀態機這種設計模式的詳細介紹。

5.1 Oh Behave!

Behavior can be defined as a change in condition or value over time(行為可以定義為隨時間變化的條件或者值的改變). It is often a response to an external event or request, but autonomous systems decide for themselves when and how to behave.

5.2 Basic State Machine Concepts

  A Finite State Machine (FSM,有限狀態機) is a directed graph composed of three primary elements(三種主要元素組成的有向圖): states(狀態), transitions(轉換), and actions(動作). A state is a condition of a system or element (usually a class in an object-oriented system)(狀態是指系統或者元素的狀態). Looking back to , the element is the microwave oven (or at least the collection of elements involved in cooking) and the states are the conditions of that system – Off, Ready, Microwaving, DoorOpen, and Paused. Usual names for states are verbs, adverbs, and verb phrases. State   A transition is a path from one state to another(轉換是從一種狀態到另一種狀態的路徑), usually initiated by an event of interest; it connects a predecessor state with a subsequent state when the element is in the predecessor state and receives the triggering event.   The actual behaviors executed by the element are represented in actions(實際的動作通過代表動作的元素來執行).

5.3 Single Event Receptor Pattern

  Single event receptor state machines (henceforth known as SERSMs,單事件接收器狀態機) can be used for both synchronous and asynchronous events(同時用於同步事件和非同步事件).

5.4 Multiple Event Receptor Pattern

  Multiple event receptor finite state machines (MERSMs,多事件接收器狀態機) are generally only used for synchro­nous state machines(通常用於同步事件狀態機) because the client is often aware of the set of events that it might want to send to the server state machine. In this pattern, there is a single event receptor for each event sent from the client.

未完待續。。。。