ZPL Программирование

Содержание
Введение
Простейший пример
Реальный пример
XA
PW
CI
RW
RS
RB
RF
FD
FN
HV
Python скрипты для печати ZPL
Похожие статьи

Введение

Zebra Programming Language это более новая версия Eltron Programming Language

В 1998 году компании Zebra и Eltron объединились

ZPL FAQ

Описание команд на официальном сайте Zebra: ZPL .

Для наглядности команды я буду выделять жирным шрифтом, параметры постараюсь сделать цветными. Введенный текст и передаваемые переменные оставлю обычными. FT Examples available here , A Examples available here

Простейший пример

^XA ^LH30, 100 ^FO20,10 ^AD^FDWWW.AskQA.RU^FS ^FO20, 60^B3^FDWWW.URN.SU^FS ^XZ

Пояснения

^XA - Начало этикетки

^LH30, 100 - Задаёт начальную позицию 30 точек вправо и 100 точек вниз

^FO20, 10 - Field Origin, отступает ещё на 20 точек вправо и 10 вниз от точки, которую мы определили предыдущей командой.

^A - Определяет шрифт.

В нашем случае ^AD выбран шрифт D. По умолчанию стоит A. Шрифты, которые соответсвуют этим буквам хранятся в EPROM принтера. ZPL II разрешает использовать буквы A - Z и цифры 1 - 9.

^FD - Field Data, объявляет начало поля с данными

WWW.AskQA.RU - обычные данные которые я ввёл. Они будут просто напечатаны на теге.

^FS - Field Separator

^FO20, 60 - Отступаем по-прежнему 20 точек вправо, но теперь, чтобы надписи не наложились друг на друга - 60 точек вниз.

^B3 - Этой командой мы показываем, что хотим распечатать баркод в формате Code 39 (USD-3 Code, Code 3 of 9).

^FDWWW.URN.SU^FS - здесь всё как в предыдущем примере, но мы помним, что теперь данные из поля будут не только распечатаны, но и изображены в виде баркода.

^XZ - Обозначает конец этикетки.

Результат

Наглядное изображение результата печати zpl кода

Пример файла для печати

На каждый параметр можно кликнуть чтобы перейти к подробному описанию. Любо просто пролистать вниз.

^XA ^PW366 ^CI28 ^RW24,24,A2 ^FS ^RS8,B10,200,3,E ^FS ^RB96,8,3,3,24,20,38 ^FS ^RFW,E ^FD48,0,5,6438092,0,#Serial# ^FS ^FN3^RFR,H ^FS ^HV3 ^FT8,24^A0N,26,26^FD#ProductCode# ^FS ^FO8,36^A0N,26,26^FB300,10,,100^FD#ProductName# ^FS ^FT8,105^A0N,26,26^FD#Quantity# ^FS ^FT130,105^A0N,26,26^FD#UnitOfQuantity# ^FS ^FT8,128^A0N,26,26^FDASK.QA ^FS ^FT134,128^A0N,26,26^FD#Serial# ^FS ^XZ

Пояснения

1) Параметры, помещённые между символами решётки # - это переменные, которые передаются с сервера. Для печати статичного изображения они не нужны, но на практике теги печатаются большими сериями и серийный номер меняется автоматически.

#Serial#

2)

🔝

^XA
^PW366
Print Width
^CI28
Change International Font
^RW24, 23, A2
Read and Write Power Levels

24 - Read Power
24 - Write Power
A2 - (a) - RFID antenna element selection. Note - This parameter is valid only on the R110Xi4 printer. This parameter selects an antenna element from the printer's antenna array.
Допустимые значения: A1, A2, A3, A4, B1, B2, B3, B4, C1, C2, C3, C4, D2, D3, D4, E2, E3, E4, F2, F3, F4 (combinations D1, E1 and F1 are invalid)
A1 - это нижний (ближний если смотреть на принтер) левый угол. F4 - верхний (дальний) правый угол.


Чтобы узнать правильное положение антенны и бэкфида, нужно выполнить RFID калибровку
Изображение баннера

🔝

^RS 8, B10, 200, 3, E ^FS
^RS - Задаёт RFID параметры

8 - (t) tag type тип тега. Gen 2 это единственный тип, поддерживаемый Zebra R110Xi4, RZ400, RZ600 и RP4T принтерами.

UHF Принтеры

Допустимые значения: 0 = None
1 = EPC Class 0
2 = EPC Class 0 Plus
3 = EPC Class 1 64-bit
4 = EPC Class 1 96-bit
5 = UCODE EPC 1.19
6 = Impinj Class 0 Plus
7 = ISO 18000-06A
8 = EPC Class 1, Generation 2 (Gen 2)
9 = ISO 18000-06B

Значение по умолчанию: 4
Because some countries restric the frequencies that can be used for RFID, not all tag types listed may be supported by your RFID printer. If you specify a tag type that is not supported, the printer will use the Значение по умолчанию.

B10 - (p) Sets the read/write position of the transponder in the vertical (Y axis) in dot rows from the top of the label. Set to 0 (no movement) if the transponder is already in the effective area without moving the media.

This parameter sets the read/write position of the transponder in one of two ways: absolute mode or relative mode. For more information about these modes, see Setting the Programming Position Manually on page 19 of RFID Programming Guide 2 Manual.

Important: If a label format specifies a value for the programming position, this value will be used for the programming position for all labels untill a new position is specified or until the transponder calibration procedure is run.

Допустимые значения:

Absolute Mode:
xxxx = 0 to label lenght (in dot rows). Move the media to the specified position xxxx on the label, measured in dot rows from the label top, before encoding. Set to 0 (no movement) if the transponder is already in the effective area without moving the media.

Relative Mode Forward:
Fxxx = F0 to Fxxx (where xxx is the label length in millimeters or 999), whichever is less). Move media forward, printing bitmap, for xxx millimeters before reading or encoding.

Relative Mode Backward:
Byy = B0 to B30 (in millimeters, 30 mm maximum). Move media backward for yy millimeters before reading or encoding. (Does not apply to the RP4T printer.)

Note: When using a backward program position, allow enough media or liner to ensure that the printer can back up the media wihout the leading edge disappearing under the printhead mechanism.

Значение по умолчанию:

F0 (which moves the leading edge of the label to the print line)

200 - (v) - length of void printout - не рекомендуется использовать 0, т.к. испорченный тэг в таком случае сложнее заметить. Если оставить поле пустым ,, длина void будет равняться длине label

3 - (n) - number of labels - The number of labels that will be attempted in case of read/encode failure. Допустимые значения: 1 to 10. Значение по умолчанию: 3

E - (e) - error handling - If an error persists after the specified number of labels are tried, perform this error handling action. Допустимые значения: N = No action (printer drops the label format causing the error and moves to the next queued label). P = Place printer in Pause mode (label format stays in the queue until the user cancels). E = Place printer in Error mode (label format stays in the queue until the user cancels). Значение по умолчанию: N

🔝

^RB96, 8,3,3,24,20,38
^RB - Define EPC Data Structure

96 - (n) total bit size of the field. Допустимые значения: 1 to n, where n is the bit size of the tag. Значение по умолчанию: 96

8,3,3,24,20,38 (p1 ... p15) - partition sizes - Specify each partition size. These must add up to the total bit size. Допустимые значения: 1 to 64 bit total bit size. Значение по умолчанию: 1.

Таким образом мы показали, что 96 бита раделены на шесть полей содержащих 8, 3, 3, 24, 20, 38


Разделение на поля происходит, естественно, не произвольным образом. В данном примере идёт печать тега в соответствии со стандартом SGTIN-96.

96 - длина EPC блока. 8 - Header. 3 - Filter. 3 - Partition. 24 - Company Prefix. 20 - Indicator / Item Reference. 38 - Serial Number.

🔝

^RFW, E
^RF - Read or Write RFID Format.

W - (o) - operation - The action to be performed. Accepted values: W = write to the tag. L = write with LOCK (if supported by tag type). R = read the tag. Значение по умолчанию: W.

E - (t) - type - Допустимые значения: A = ASCII, H = Hexadecimal, E = EPC (ensure proper setup with the ^RB command). Значение по умолчанию: H.

🔝

^FD 48,0,5,6438092,0,#Serial#

Что означают параметры 48,0,5,6438092,0,#Serial# после ^FD с первого взгляда непонятно. В описании у ^FD всего один параметр

(a) - data to be printed. Допустимые значения: any ASCII string up to 3072 characters
Значение по умолчанию: none - a string of characters must be entered.

Объяснение:

^FD у нас идёт не один, а в связке с ^RFW, E и определённым перед ним ^RB96, 8,3,3,24,20,38

То есть нужно рассматривать всю комбинацию команд.

^RB96,8,3,3,24,20,38 ^RFW,E^FD48,0,5,6438092,0,#Serial#

И при этом не забывать, что мы записываем теги в соответствии со стандартом SGTIN-96

Название поля→ Общая длина Header Filter Partition Company Prefix Indicator / Item Reference Серийный номер
Длина в битах → 96 8 3 3 24 20 38
Что мы туда записываем → N/A 48 0 5 6438092 0 #Serial#

🔝

^FN3 ^RFR, H^FS
^FN - Field Number Description the ^FN command numbers the data fields. This command is used in both ^DF (Store Format) and ^XF (Recall Format) commands.

In a stored format, use the ^FN command where you would normally use the ^FD (Field Data) command. In recalling the stored fromat, use ^FN in conjunction with the ^FD command.

Format ^FN#
ParametersDetails
# = number to be assigned to the field. Допустимые значения: 0 to 9999
Значение по умолчанию: 0
"a" = optional parameter* Values: 255 alphanumeric characters maximum (a-z, A-Z,1-9 and space)
Default: optional parameter

Comments
The same ^FN value can be stored with several different fields.
If a label format contains a field with ^FN and ^FD, the data in that field prints for any other field containing the same ^FN value
For the "a" parameter to function as a prompt the characters used in the "a" parameter must be surrounded by double quotes (see example).

Example: The ^FN1"Name" would result in "Name" being used as the prompt on the KDU unit.

3 - Это номер блока памяти в самом принтере. Мы можем записывать данные в один из 10 000 блоков и затем вызывать из них данные обратно.

В нашем примере, вместо 3 могло стоять любое число. Главное потом указать тот же блок памяти в команде ^HV


^RF - Read or Write RFID Format.
R - значит, что мы читаем тег.

This command allows you to read or write to an RFID tag.

Note: When using this command to read a tag, you may use a field variable to print the tag data on the label or to return the data to the host.

Printers That Support This Command: RXi, R110PAX4

Format ^RFo, t, b

o = operation - The action to be performed.
Допустимые значения: W = write to the tag, L = write with LOCK (if supported by tag type), R = read the tag
Значение по умолчанию: W

t = type - Допустимые значения: A = ASCII, H = Hexadecimal, E = EPC (ensure proper setup with the ^RB command)
Значение по умолчанию: H

b = starting block number - Допустимые значения: 0 to n, where n is the maximum number of blocks for the tag.
Значение по умолчанию: 0

🔝

^HV3
^HV - Host Verification

Description - This command is used to return data from specified fields, along with an optional ASCII header, to the host computer. The command can be used with any field that has been assigned a number with the ^RT command or the ^FN and ^RF commands.

Format ^HV#,n, h

# = field number specified with another command. The value assigned to this parameter should be the same as the one used in another command.

Допустимые значения: 0 to 9999
Значение по умолчанию: 0

В предыдущей команде (^FN3) у нас было значение 3. Поэтому и здесь у нас 3 (^HV3). Т.е. мы отсылаем обратно на сервер, то, что прочитали до этого с помощью ^RF


n = number of bytes to be returned

Допустимые значения: 1 to 256
Значение по умолчанию: 64

h = header - Header (in uppercase ASCII characters) to be returned with the data.

Acceptable values: 0 to 3072 characters
Значение по умолчанию: no header

🔝

^FT8 ,24^A0N,26,26^FD#ProductCode#
^FT - Field Typeset

The ^FT command sets the field position, relative to the home position of the label designated by the ^LH. The typesetting origin of the field is fixed with respect to the contents of the field and does not change with rotation.

Note: The ^FT command is capable of concantination of fields.

Format: ^FTx,y, z

ParametersDetails
x = x-axis location (in dots) Values: 0 to 32000
Default: position after last formatted text field
y = y-axis location (in dots) Values: 0 to 32000
Default: position after last formatted text field
z = justification

The z parameter is only supported in firmware version V60.14.x, V50.14.x, or later
Values:
0 = left justification
1 = right justification
2 = auto justification (script dependent)
Default: last accepted ^FW value or ^FW default

The auto justification option may cause unexpected results if variable fields or bidirectional text are used with ^FT. For best results with bidirectional text and/or variable fields, use either the left or right justification options.
^FT8, 24^A 0N, 26, 26^FD#ProductCode#
^FT8,24

8 - отступ слева
24 - отступ сверху Field Typeset

Description The ^FT command also sets the field position, relative to the home position of the label designated by the ^LH command. The typesetting origin of the field is fixed with respect to the contents of the field and does not change with rotation.

Format ^FTx,y

ParametersDetails
x = x-axis location (in dots)Допустимые значения: 0 to 32000
Значение по умолчанию: positiono after last formatted text field
y = y-axis location (in dots)Допустимые значения: 0 to 32000
Значение по умолчанию: position after last formatted text field

Text The origin is at the start of the character string, at the baseline of the font. Normally the baseline is the bottom of most characters, except for those with descenders, such as g, y et cetera.

Bar Codes The origin is at the base of the bar code, even when an interpretation is present below the bar code, or if the bar code has guard bars.

Graphic Boxes The origin is at the bottom-left corener of the box.

Images The origin is at the bottom-left corner of the rectangular image area.

Examples available here

When a coordinate is missing, the position following the last formatted field is assumed. This remembering simplifies field positioning with respect to other fields. Once the firest field is positioned, other fields follow automatically.

There are several instances where using the ^FT command without specifying x and y parameters is not recommended:
  • when positioning the first field in a label format
  • at any time with the ^FN (Field Number) command
  • following an ^SN (Serialization Data) command


^A0N,26,26^FD#ProductCode#

^A - Определяет шрифт.

В нашем случае ^A0 выбран шрифт 0 - parameter (f) - font name. По умолчанию стоит A. Шрифты, которые соответсвуют этим буквам хранятся в EPROM принтера. ZPL II разрешает использовать буквы A - Z и цифры 1 - 9.

N - parameter o = font orientation. Допустимые значения: N = normal, R = rotated 90 degrees (clockwise), I = Inverted 180 degrees, B = read from bottom up, 270 degrees
Значение по умолчанию: the last accepted ^FW value or the ^FW default

26,26 - это высота (h) и ширина (w), заданные в точках. Examples available here

^FS

^FO8,36^A0N,26,26 ^FB300,10,,100^FD#ProductName#
^FO8, 36 - Field Origin, отступает ещё на 8 точек вправо и 36 вниз от точки, которую мы определили командой ^LH (а точнее не определили).

^FB300,10, ,100

^FB - Field Block

Description The ^FB command allows you to print text into a defined block type format. This command formats an ^FD or ^SN string into a block of text using the origin, font, and rotation specified for the text string. The ^FB command also contains an automatic word-wrap function.

Format ^FBa,b, c,d, e

Параметры Подробности
a = width of text block line (in dots) Допустимые значения: 0 to the width of the label (or 9999)
Значение по умолчанию: 0
If this value is less than font width or not specified, text does not print
b = maximum number of lines in text block Допустимые значения: 1 to 9999
Значение по умолчанию: 1
Text exceeding the maximum number of lines overwrites the last line. Changing the font size automatically increases or decreases the size of the block
c = add or delete space between lines (in dots) Допустимые значения: -9999 to 9999
Значение по умолчанию: 0
Numbers are considered to be positive unless preceded by a minus sign. Positive values add space, negative values delete space.
d = text justificationДопустимые значения: L (left), C (center), R (right), J (justified)
Значение по умолчанию: L
Last line is left-justified if J is used
e = hanging indent (in dots) of the second and remaining lines Допустимые значения: 0 to 9999
Значение по умолчанию: 0

^FS
^FT8,105^A0N,26,26^FD#Quantity#^FS
^FT130,105^A0N,26,26^FD#UnitOfQuantity#^FS
^FT8,128^A0N,26,26^FDASK.QA^FS
^FT9,128^A0N,26,26^FDASK.QA^FS
^FT134,128^A0N,26,26^FD#Serial#^FS
^FT134,128^A0N,26,26^FD#Serial#^FS
^XZ

Основные команды

RFID калибровка

^XA
^HR
^XZ

start position=B9 MM,A2,25,25 leading edge B20, , ,A2,29,29 B19, , ,A2,29,29 B18,R, ,A2,29,29 B17, , ,A2,29,29 B16, , ,A2,29,29 B15,R,W,A2,17,21 B14,R,W,A2,11,15 B13,R,W,A2,7,11 B12,R,W,A2,5,9 B11,R,W,A2,5,7 B10,R,W,A2,5,9 B9,R,W,A2,5,11<---**** B9 MM,A2,25,25 B8,R,W,A2,11,15 B7,R,W,A2,23,23 B6, , ,A2,29,29 B5,R,W,A2,25,25 B4,R,W,A2,25,25 B3,R,W,A2,27,29 B2, , ,A2,29,29 trailing edge end

Предпросмотр ZPL

ZPL симулятор для просмотра layout файлов

Создание штрихкодов

sscc-18

^FO250,50

^BY3,3,10

^BCN,110,N,N,N,N

^FD{SERIAL}^FS

^BY 3,3,10
^BY - Bar Code Field Default

The ^BY command is used to change the Значение по умолчаниюs for the module width (in dots), the wide bar to narrow bar width ratio and the bar code height (in dots). It can be used as often as necessary within a label format.

Format: ^BYw ,r,h

Parameters Details
w = module width (in dots) Values: 1 to 10
Initial Value at Power Up: 2
r = wide bar to narrow bar width ratio Values: 2.0 to 3.0, in 0.1 increments This parameter has no effect on fixed-ratio bar codes. Default: 3.0
h = bar code height (in dots) Initial Value at Power Up: 10


For parameter r, the actual ratio generated is a function of the number of dots in parameter w, module width. See Table 12 on page 126. Module width and height (w and h) can be changed at anytime with the ^BY command, regardless of the symbology selected.

Example: Set module width (w) to 9 and the ratio (r) to 2.4. The width of the narrow bar is 9 dots wide and the wide bar is 9 by 2.4, or 21.6 dots. However, since the printer rounds out to the nearest dot, the wide bar is actually printed at 22 dots. This produces a bar code with a ratio of 2.44 (22 divided by 9). This ratio is as close to 2.4 as possible, since only full dots are printed.
^BCN ,110,N ,N ,N, N
The ^BC command creates the Code 128 bar code, a high-density, variable length, continuous, alphanumeric symbology. It was designed for complexly encoded product identification.

Code 128 has three subsets of characters. There are 106 encoded printing characters in each set, and each character can have up to three different meanings, depending on the character subset being used. Each Code 128 character consists of six elements: three bars and three spaces.

^BC supports a fixed print ratio. Field data (^FD) is limited to the width (or length, if rotated) of the label.

Format: ^BCo,h,f,g,e,m Important • If additional information about the Code 128 bar code is required, go to

Format: ^BCo ,h,f,g ,e, m

ParametersDetails
o = orientation Values:
N = normal
R = rotated 90 degrees (clockwise)
I = inverted 180 degrees
B = read from bottom up, 270 degrees
Default: current ^FW value
h = bar code height (in dots) ratio Values: 1 to 32000
Default: value set by ^BY
f = print interpretation line Values: Y (yes) or N (no)
Default: Y
The interpretation line can be printed in any font by placing the font command before the bar code command.
g = print interpretation line above code Values: Y (yes) or N (no)
Default: N
e = UCC check digit Values: Y (turns on) or N (turns off)
Mod 103 check digit is always there. It cannot be turned on or off. Mod 10
and 103 appear together with e turned on.
Default: N
m = mode Values:
N = no selected mode
U = UCC Case Mode

⋅ More than 19 digits in ^FD or ^SN are eliminated.
⋅ Fewer than 19 digits in ^FD or ^SN add zeros to the right to bring the
count to 19. This produces an invalid interpretation line.

A = Automatic Mode

This analyzes the data sent and automatically determines the best
packing method. The full ASCII character set can be used in the ^FD
statement — the printer determines when to shift subsets. A string of
four or more numeric digits causes an automatic shift to Subset C.

D = UCC/EAN Mode (x.11.x and newer firmware)

This allows dealing with UCC/EAN with and without chained
application identifiers. The code starts in the appropriate subset
followed by FNC1 to indicate a UCC/EAN 128 bar code. The printer
automatically strips out parentheses and spaces for encoding, but
prints them in the human-readable section. The printer automatically
determines if a check digit is required, calculate it, and print it.
Automatically sizes the human readable.

Default: N


Python скрипты для печати ZPL

Очень часто бывает нужно напечатать большое количество тэгов таким образом, чтобы серийный номер возрастал на 1 у каждого следующего тэга.

Предположим, что серийный номер должен быть напечатан как в память тэга так и на этикетку.

Формат пусть будет GIAI-96 , код компании помещается в 24 бита, для примера возьмём 1234567

Запишем сперва код для этикетки.

^XA ^CI28 ^PW500^FS ^RW24,26,A2^FS ^RS8,B13,100,1,E^FS ^RB96,8,3,3,24,58^FS ^RFW,E^FD52,0,5,1234567,${userID},^FS ^FN3^RFR,H^FS ^HV3 ^FWN^FO90, 15^AD,90,22^FDTVS^FS ^FT90,110^A0N,25,25^FH^FDUSER:${userID} ^FS ^XZ

Для создания скрипта нужно познакомиться с основами языка Python а также с сокетами , которые нужны для работы с сетью

import socket mysocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host = "10.6.1.123" port = 9100 try: mysocket.connect((host, port)) #connecting to host for i in range(100073,100100): userId = str(i) mysocket.send(b"^XA^CI28^PW500^FS") mysocket.send(b"^RW24,26,A2^FS") mysocket.send(b"^RS8,B13,100,1,E^FS") mysocket.send(b"^RB96,8,3,3,24,58^FS") mysocket.send(b"^RFW,E^FD52,0,5,1234567,") mysocket.send(bytes(userId,"utf-8")) mysocket.send(b",^FS") mysocket.send(b"^FN3^RFR,H^FS") mysocket.send(b"^HV3") mysocket.send(b"^FWN^FO90, 15^AD,90,22^FDCompanyName^FS") mysocket.send(b"^FT90,110^A0N,25,25^FH^FDUSER:") mysocket.send(bytes(userId,"utf-8")) mysocket.send(b"^FS^XZ") mysocket.close () #closing connection except: print("Error with the connection")

Можно не писать в каждой строчке mysocket.send , а использовать Heredoc и Python f-string

import socket mysocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host = "10.6.1.123" port = 9100 try: mysocket.connect((host, port)) #connecting to host for i in range(100073,100100): userId = str(i) layout = (f""" ^XA^CI28^PW500^FS ^RW24,26,A2^FS ^RS8,B13,100,1,E^FS ^RB96,8,3,3,24,58^FS ^RFW,E^FD52,0,5,1234567,{userId},^FS ^FN3^RFR,H^FS ^HV3 ^FWN^FO90, 15^AD,90,22^FDCompanyName^FS ^FT90,110^A0N,25,25^FH^FDUSER:{userId},^FS ^FS^XZ """) mysocket.send(bytes(layout,"utf-8")) mysocket.close () #closing connection except: print("Error with the connection")

Похожие статьи
RFID
ZPL FAQ
A пример
FT примеры

Поиск по сайту

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

Перейти на канал

@aofeed

Задать вопрос в Телеграм-группе

@aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: