- What is hal linux
- Пакет HAL-0.5.14
- Знакомимся с пакетом HAL
- Информация о пакете
- Дополнительные загрузкие
- Зависимости пакета HAL
- Обязательные
- Рекомендуемые
- Необязательные (для создания документации)
- Необязательные
- Установка пакета HAL
- Пояснение команд
- Зависимости времени выполнения
- Конфигурирование пакета HAL
- Конфигурационные файлы
- Подробнее о конфигурировании
- Разрешение пользователям вызывать методы HAL
- Установка программ, помогающих выполнять монтирование
- Изменение параметров монтирования, используемых по умолчанию
- Добавление разрешенных параметров монтирования
- Загрузочный скрипт
- Важно
- Описание пакета
- HAL Introduction
- 1. HAL is based on traditional system design techniques
- 1.1. Part Selection
- 1.2. Interconnection Design
- 1.3. Implementation
- 1.4. Testing
- 1.5. Summary
- 2. HAL Concepts
- 3. HAL components
- 3.1. External Programs with HAL hooks
- 3.2. Internal Components
- 3.3. Hardware Drivers
- 3.4. Tools and Utilities
- 4. Timing Issues In HAL
What is hal linux
Библиотека сайта rus-linux.net
На главную -> MyLDP -> Электронные книги по ОС Linux
Beyond Linux From Scratch. Version 2011-12-30 | ||
Назад | 11. Системные утилиты | Вперед |
Пакет HAL-0.5.14
Знакомимся с пакетом HAL
HAL является слоем аппаратных абстракций, представляющим собой часть программного обеспечения, в котором реализуются представления различных устройств, подключаемых к системе. Кроме этого, в HAL хранятся подробные метаданные для каждой единицы оборудования, а также реализован механизм, позволяющий системе и программам рабочего стола реагировать на изменение конфигурации аппаратных средств и, тем самым реализовывать системную политику.
Самой важной задачей HAL является предоставление в UNIX-подобных настольных системах функций plug-and-play, предназначенных для получения подробного и расширяемого описания характеристик и возможностей устройств. Одним из примеров функциональных возможностей, предоставляемых HAL, является реакция на подключение вами устройства USB, предназначенного для хранения данных. HAL может автоматически создать в /media точку монтирования и смонтировать устройство.
Информация о пакете
- Загрузка (HTTP): http://hal.freedesktop.org/releases/hal-0.5.14.tar.bz2
- Контрольная сумма MD5: c627d8fb0f9afff94f3c687b5216bc06
- Размер загружаемого пакета: 924 KB
- Оценочный размер требуемого дискового пространства: 25 MB
- Оценочное время сборки: 0,5 SBU
Дополнительные загрузкие
- Загрузка (HTTP): http://hal.freedesktop.org/releases/hal-info-20091130.tar.bz2
- Загрузка (FTP):
- Контрольная сумма MD5: 995b8d2dbfb0646b07c92bb8d23cbcf1
- Размер загружаемого пакета: 108 KB
Зависимости пакета HAL
Обязательные
Рекомендуемые
PCI Utilities-3.1.8 (с текущим файлом pci.ids ) и usbutils-004 (с текущим файлом usb.ids )
Необязательные (для создания документации)
Необязательные
Установка пакета HAL
Вы должны перед установкой пакета создать специального пользователя и группу. Хотя по умолчанию в инструкциях BLFS демон HAL запускается пользователем в роли root , будет установлен конфигурационный файл, в котором жестко прописано имя специального пользователя. Из-за этого при запуске демона D-BUS будет выдаваться ошибочное сообщение. В роли пользователя root выполните следующие команды:
Установите пакет HAL с помощью следующих команд:
Чтобы проверить результаты, выполните команду make check.
Теперь в роли пользователя root выполните:
Установите данные об устройствах HAL с помощью следующих команд:
Теперь в роли пользователя root выполните:
Пояснение команд
—libexecdir=/usr/lib/hal : Этот параметр указывает, что файлы libexec будут установлены в директории /usr/lib/hal , а не в директории /usr/libexec .
—localstatedir=/var : Этот параметр указывает, что файл pid будет создан в директории /var/run/hald , а не в директории /usr/var/run/hald .
—enable-policy-kit=no : Этот параметр является обязательным, если не установлен пакет PolicyKi. Удалите его, если пакет PolicyKit установлен
—enable-docbook-docs —docdir=/usr/share/doc/hal-0.5.14 : Если имеется пакет xmlto-0.0.23 , то эти параметры включают сборку документации по спецификациям HAL.
Зависимости времени выполнения
Есть еще несколько пакетов, которые расширяют функциональные возможности HAL в процессе его работы. К ним относятся пакеты Eject-2.1.5 , dmidecode , device-mapper-1.02.67, Cryptsetup-LUKS и pm-utils .
Конфигурирование пакета HAL
Конфигурационные файлы
/etc/dbus-1/system.d/hal.conf , /etc/dbus-1/system.d/halusers.conf и /etc/hal/*
Подробнее о конфигурировании
Разрешение пользователям вызывать методы HAL
Настройка HAL, используемая по умолчанию, позволяет вызывать методы, например, Mount(), только определенным пользователям. Это пользователь root и пользователь, который имеет доступ к активной консоли с помощью pam_console . Если у вас не установлены пакеты Linux-PAM-1.1.5 и pam_console , то с помощью следующих команд создайте группу, членам которой будет разрешено вызывать методы HAL:
Теперь в группу halusers добавьте пользователей, которым вы разрешите использовать HAL.
Заметьте, что этим пользователям по-прежнему необходимо иметь соответствующие разрешения для доступа к устройствам, к которым HAL будет выполнять обращение с помощью имеющихся у него методов.
После того, как приведенная выше конфигурации будет задействована, авторизованные пользователи получат возможность размонтировать разделы диска, смонтированного в нестандартных местах, таких как /pub . Если вы хотите ограничить эту политику только съемными дисками и дисками, поддерживающими горячую замену, то в роли пользователя root добавьте следующий конфигурационный файл:
Установка программ, помогающих выполнять монтирование
HAL предоставляет доступ только к тем методам, таким как, Mount(), которые взаимодействуют с аппаратным обеспечением. Чтобы воспользоваться этой возможностью, необходимо установить обработчик событий HAL, например, Ivman .
Изменение параметров монтирования, используемых по умолчанию
В некоторых случаях для файловых систем необходимо указать некоторые параметры монтирования, которые будут использоваться по умолчанию. Например, в неанглийских средах параметры iocharset и codepage необходимы для файловых систем, ведущих свое происхождение от Windows, для того, чтобы можно было правильно отображать национальные символы. Кроме того, в связи с ошибкой в версии ядра Linux в LFS (2.6.22.x), вам может потребоваться передать параметр usefree в файловую систему vfat с тем, чтобы сократить время, необходимое для определения в файловой системе объема имеющегося свободного места.
В результатах поиска Google по запросу «hal default mount options» («Параметры монтирования hal, используемые по умолчанию») по-прежнему много рекомендаций о том, что нужно создать файлы *.fdi , в которых следует указать либо ключи volume.policy , либо ключи storage.policy . Такие рекомендации работали только с HAL-0.4.x, но теперь они неработоспособны. Предполагается, что для HAL-0.5.14 с параметрами монтирования нужно обращаться следующим образом:
- Обработчик событий получает из среды рабочего стола описание события для только что подключенного устройства хранения данных
- Если устройство хранения данных еще не упомянуто в /etc/fstab , параметры монтирования устройства выбираются из базы данных настроек пользователя, которая специально предназначена для среды рабочего стола, а затем эти параметры передаются обратно в HAL. Этот процесс может зависеть от типа файловой системы и, возможно, от других свойств устройства, хранящихся в HAL.
- Если параметры попадают в список разрешенных параметров, то HAL монтирует том.
Важным моментом описания, приведенного выше, является то, что процедура конфигурирования фокусируется на особенностях, относящихся к рабочему столу. Однако, по состоянию на декабрь 2007 года, только в GNOME пользователю разрешается устанавливать используемые по умолчанию параметры монтирования файловой системы так, как это будет описано в следующем разделе. В KDE параметры монтирования можно устанавливать только для тома хранения данных, а не для файловой системы, что является ошибкой , поскольку, как отмечается в сообщении, «для каждого нового устройства (скажем, устройства USB вашего приятеля), вы не должны сразу его монтировать, сначала нужно изменить параметры, а затем — монтировать устройство». В Xfce, если он собран с поддержкой HAL, поддерживается работа с жестко заданными параметрами монтирования без какой-либо возможности их переопределения, что еще хуже. В KDE и в Xfce, если встроенные параметры монтирования, используемые по умолчанию, не подходят, в файле /etc/fstab нужно указывать каждое возможное съемное устройство хранения данных с указанием нужных параметров, отключив, таким образом, механизм установки, имеющийся в HAL
Чтобы настроить параметры монтирования, используемые по умолчанию, пользователи GNOME должны изменить ключ GConf /system/storage/default_options/[fs_type]/mount_options либо с помощью редактора GConf Editor-2.30.0, либо из командной строки так, как это показано в следующем примере:
Подробную информацию смотрите на странице руководства gnome-mount(1).
Добавление разрешенных параметров монтирования
Список параметров монтирования, разрешенных в конфигурации HAL, заданной по умолчанию, находится в файле /usr/share/hal/fdi/policy/10osvendor/20-storage-methods.fdi . Пользователи GNOME и KDE, возможно, захотят использовать параметры, которых нет в этом списке (в примере, приведенном выше, таким параметром является параметр usefree ). В этом случае в роли пользователя root создайте файл специальной политики, в котором укажите необходимые параметры монтирования:
Загрузочный скрипт
Чтобы при перезагрузке системы автоматически запускать демон hald, установите загрузочный скрипт /etc/rc.d/init.d/haldaemon , который находится в пакете blfs-bootscripts-20111226.
Важно
Если во время установки HAL работает общесистемный демон D-BUS, то перед тем, как делать попытку запуска демона hald, убедитесь, что вы остановили и перезапустили демон D-BUS.
Описание пакета
Установленные программы: hal-device, hal-disable-polling, hal-find-by-capability, hal-find-by-property, hal-get-property, hal-is-caller-locked-out, hal-lock, hal-set-property, hald и lshal
Установленные библиотеки: libhal.
Установленные директории: /etc/hal, /usr/include/hal, /usr/lib/hal, /usr/share/doc/hal-0.5.14, /usr/share/hal, /var/cache/hald, /var/lib/hal и /var/run/hald
используется для создания, удаления или отображения устройства HAL
можно использовать для отключения и включения режима обнаружения носителей в устройствах, предназначенных для работы со съемными носителями
выдает уникальные идентификаторы устройств для объектов устройств HAL, имеющих указанные возможности
выдает уникальные идентификаторы устройств для объектов устройств HAL, на котором указанное свойство имеет заданное значение
поиск на устройстве некоторого свойства
попытки задать для устройства некоторое свойство. Отметим, что по соображениям безопасности, свойство, возможно, задать не удастся
определяет, будет ли заблокировано конкретное обращение через конкретный интерфейс D-Bus к конкретному устройству
является программой-демоном HAL
показывает все устройства и их свойства. Если задан параметр —monitor, то в списке устройств указываются все устройства, за изменением которых осуществляется мониторинг
содержит функции API, необходимые программам HAL
содержит функции API, необходимые программам HAL, работающими с устройствами хранения данных и с томами
Перевод сделан с варианта оригинала, датированного 2011-11-08 16:57:34 +0000
Источник
HAL Introduction
HAL stands for Hardware Abstraction Layer. At the highest level, it is simply a way to allow a number of building blocks to be loaded and interconnected to assemble a complex system. The Hardware part is because HAL was originally designed to make it easier to configure LinuxCNC for a wide variety of hardware devices. Many of the building blocks are drivers for hardware devices. However, HAL can do more than just configure hardware drivers.
1. HAL is based on traditional system design techniques
HAL is based on the same principles that are used to design hardware circuits and systems, so it is useful to examine those principles first.
Any system (including a CNC machine), consists of interconnected components. For the CNC machine, those components might be the main controller, servo amps or stepper drives, motors, encoders, limit switches, pushbutton pendants, perhaps a VFD for the spindle drive, a PLC to run a toolchanger, etc. The machine builder must select, mount and wire these pieces together to make a complete system.
Figure one would be written in HAL code like this:
1.1. Part Selection
The machine builder does not need to worry about how each individual part works. He treats them as black boxes. During the design stage, he decides which parts he is going to use — steppers or servos, which brand of servo amp, what kind of limit switches and how many, etc. The integrator’s decisions about which specific components to use is based on what that component does and the specifications supplied by the manufacturer of the device. The size of a motor and the load it must drive will affect the choice of amplifier needed to run it. The choice of amplifier may affect the kinds of feedback needed by the amp and the velocity or position signals that must be sent to the amp from a control.
In the HAL world, the integrator must decide what HAL components are needed. Usually every interface card will require a driver. Additional components may be needed for software generation of step pulses, PLC functionality, and a wide variety of other tasks.
1.2. Interconnection Design
The designer of a hardware system not only selects the parts, he also decides how those parts will be interconnected. Each black box has terminals, perhaps only two for a simple switch, or dozens for a servo drive or PLC. They need to be wired together. The motors connect to the servo amps, the limit switches connect to the controller, and so on. As the machine builder works on the design, he creates a large wiring diagram that shows how all the parts should be interconnected.
When using HAL, components are interconnected by signals. The designer must decide which signals are needed, and what they should connect.
1.3. Implementation
Once the wiring diagram is complete it is time to build the machine. The pieces need to be acquired and mounted, and then they are interconnected according to the wiring diagram. In a physical system, each interconnection is a piece of wire that needs to be cut and connected to the appropriate terminals.
HAL provides a number of tools to help build a HAL system. Some of the tools allow you to connect (or disconnect) a single wire. Other tools allow you to save a complete list of all the parts, wires, and other information about the system, so that it can be rebuilt with a single command.
1.4. Testing
Very few machines work right the first time. While testing, the builder may use a meter to see whether a limit switch is working or to measure the DC voltage going to a servo motor. He may hook up an oscilloscope to check the tuning of a drive, or to look for electrical noise. He may find a problem that requires the wiring diagram to be changed; perhaps a part needs to be connected differently or replaced with something completely different.
HAL provides the software equivalents of a voltmeter, oscilloscope, signal generator, and other tools needed for testing and tuning a system. The same commands used to build the system can be used to make changes as needed.
1.5. Summary
This document is aimed at people who already know how to do this kind of hardware system integration, but who do not know how to connect the hardware to LinuxCNC. See the Remote Start Example section in the HAL UI Examples documentation.
The traditional hardware design as described above ends at the edge of the main control. Outside the control are a bunch of relatively simple boxes, connected together to do whatever is needed. Inside, the control is a big mystery — one huge black box that we hope works.
HAL extends this traditional hardware design method to the inside of the big black box. It makes device drivers and even some internal parts of the controller into smaller black boxes that can be interconnected and even replaced just like the external hardware. It allows the system wiring diagram to show part of the internal controller, rather than just a big black box. And most importantly, it allows the integrator to test and modify the controller using the same methods he would use on the rest of the hardware.
Terms like motors, amps, and encoders are familiar to most machine integrators. When we talk about using extra flexible eight conductor shielded cable to connect an encoder to the servo input board in the computer, the reader immediately understands what it is and is led to the question, what kinds of connectors will I need to make up each end. The same sort of thinking is essential for the HAL but the specific train of thought may take a bit to get on track. Using HAL words may seem a bit strange at first, but the concept of working from one connection to the next is the same.
This idea of extending the wiring diagram to the inside of the controller is what HAL is all about. If you are comfortable with the idea of interconnecting hardware black boxes, you will probably have little trouble using HAL to interconnect software black boxes.
2. HAL Concepts
This section is a glossary that defines key HAL terms but it is a bit different than a traditional glossary because these terms are not arranged in alphabetical order. They are arranged by their relationship or flow in the HAL way of things.
When we talked about hardware design, we referred to the individual pieces as parts, building blocks, black boxes, etc. The HAL equivalent is a component or HAL component. (This document uses HAL component when there is likely to be confusion with other kinds of components, but normally just uses component.) A HAL component is a piece of software with well-defined inputs, outputs, and behavior, that can be installed and interconnected as needed.
Many hardware components have adjustments that are not connected to any other components but still need to be accessed. For example, servo amps often have trim pots to allow for tuning adjustments, and test points where a meter or scope can be attached to view the tuning results. HAL components also can have such items, which are referred to as parameters. There are two types of parameters: Input parameters are equivalent to trim pots — they are values that can be adjusted by the user, and remain fixed once they are set. Output parameters cannot be adjusted by the user — they are equivalent to test points that allow internal signals to be monitored.
Hardware components have terminals which are used to interconnect them. The HAL equivalent is a pin or HAL pin. (HAL pin is used when needed to avoid confusion.) All HAL pins are named, and the pin names are used when interconnecting them. HAL pins are software entities that exist only inside the computer.
Many I/O devices have real physical pins or terminals that connect to external hardware, for example the pins of a parallel port connector. To avoid confusion, these are referred to as physical pins. These are the things that stick out into the real world.
In a physical machine, the terminals of real hardware components are interconnected by wires. The HAL equivalent of a wire is a signal or HAL signal. HAL signals connect HAL pins together as required by the machine builder. HAL signals can be disconnected and reconnected at will (even while the machine is running).
When using real hardware, you would not connect a 24 volt relay output to the +/-10V analog input of a servo amp. HAL pins have the same restrictions, which are based upon their type. Both pins and signals have types, and signals can only be connected to pins of the same type. Currently there are 4 types, as follows:
bit — a single TRUE/FALSE or ON/OFF value
float — a 64 bit floating point value, with approximately 53 bits of resolution and over 1000 bits of dynamic range.
u32 — a 32 bit unsigned integer, legal values are 0 to 4,294,967,295
s32 — a 32 bit signed integer, legal values are -2,147,483,647 to +2,147,483,647
Real hardware components tend to act immediately on their inputs. For example, if the input voltage to a servo amp changes, the output also changes automatically. However software components cannot act automatically. Each component has specific code that must be executed to do whatever that component is supposed to do. In some cases, that code simply runs as part of the component. However in most cases, especially in realtime components, the code must run in a specific sequence and at specific intervals. For example, inputs should be read before calculations are performed on the input data, and outputs should not be written until the calculations are done. In these cases, the code is made available to the system in the form of one or more functions. Each function is a block of code that performs a specific action. The system integrator can use threads to schedule a series of functions to be executed in a particular order and at specific time intervals.
A thread is a list of functions that runs at specific intervals as part of a realtime task. When a thread is first created, it has a specific time interval (period), but no functions. Functions can be added to the thread, and will be executed in order every time the thread runs.
As an example, suppose we have a parport component named hal_parport. That component defines one or more HAL pins for each physical pin. The pins are described in that component’s doc section: their names, how each pin relates to the physical pin, are they inverted, can you change polarity, etc. But that alone doesn’t get the data from the HAL pins to the physical pins. It takes code to do that, and that is where functions come into the picture. The parport component needs at least two functions: one to read the physical input pins and update the HAL pins, the other to take data from the HAL pins and write it to the physical output pins. Both of these functions are part of the parport driver.
3. HAL components
Each HAL component is a piece of software with well-defined inputs, outputs, and behavior, that can be installed and interconnected as needed. This section lists some of the available components and a brief description of what each does. Complete details for each component are available later in this document.
3.1. External Programs with HAL hooks
A realtime module that accepts NML
[Neutral Message Language provides a mechanism for handling multiple types of messages in the same buffer as well as simplifying the interface for encoding and decoding buffers in neutral format and the configuration mechanism.]
motion commands and interacts with HAL
A user space module that accepts NML I/O commands and interacts with HAL
A PLC using HAL for all I/O
A user space program that interacts with HAL and sends NML commands, it is intended to work as a full User Interface using external knobs & switches
3.2. Internal Components
Software step pulse generator with position loop. See section Stepgen
Software based encoder counter. See section Encoder
Proportional/Integral/Derivative control loops. See section PID
A sine/cosine/triangle/square wave generator for testing. See section Siggen
a simple source for testing
3.3. Hardware Drivers
A driver for the Axiom Measurement & Control AX5241H digital I/O board
General Mechatronics GM6-PCI board
Mesa Electronics 5i20 board
Vital Systems MOTENC-100 board
PC parallel port.
Pico Systems family of controllers (PPMC, USC and UPC)
Servo To Go card (version 1 & 2)
Vigilant Technologies PCI ENCDAC-4 controller
3.4. Tools and Utilities
Command line tool for configuration and tuning. See section Halcmd
A handy multimeter for HAL signals. See section Halmeter.
A full featured digital storage oscilloscope for HAL signals. See the Halscope section.
Each of these building blocks is described in detail in later chapters.
4. Timing Issues In HAL
Unlike the physical wiring models between black boxes that we have said that HAL is based upon, simply connecting two pins with a hal-signal falls far short of the action of the physical case.
True relay logic consists of relays connected together, and when a contact opens or closes, current flows (or stops) immediately. Other coils may change state, etc, and it all just happens. But in PLC style ladder logic, it doesn’t work that way. Usually in a single pass through the ladder, each rung is evaluated in the order in which it appears, and only once per pass. A perfect example is a single rung ladder, with a NC contact in series with a coil. The contact and coil belong to the same relay.
If this were a conventional relay, as soon as the coil is energized, the contacts begin to open and de-energize it. That means the contacts close again, etc, etc. The relay becomes a buzzer.
With a PLC, if the coil is OFF and the contact is closed when the PLC begins to evaluate the rung, then when it finishes that pass, the coil is ON. The fact that turning on the coil opens the contact feeding it is ignored until the next pass. On the next pass, the PLC sees that the contact is open, and de-energizes the coil. So the relay still switches rapidly between on and off, but at a rate determined by how often the PLC evaluates the rung.
In HAL, the function is the code that evaluates the rung(s). In fact, the HAL-aware realtime version of ClassicLadder exports a function to do exactly that. Meanwhile, a thread is the thing that runs the function at specific time intervals. Just like you can choose to have a PLC evaluate all its rungs every 10 ms, or every second, you can define HAL threads with different periods.
What distinguishes one thread from another is not what the thread does — that is determined by which functions are connected to it. The real distinction is simply how often a thread runs.
In LinuxCNC you might have a 50 us thread and a 1 ms thread. These would be created based on BASE_PERIOD and SERVO_PERIOD, the actual times depend on the values in your ini file.
The next step is to decide what each thread needs to do. Some of those decisions are the same in (nearly) any LinuxCNC system—For instance, motion-command-handler is always added to servo-thread.
Other connections would be made by the integrator. These might include hooking the STG driver’s encoder read and DAC write functions to the servo thread, or hooking stepgen’s function to the base-thread, along with the parport function(s) to write the steps to the port.
Источник