19
Fri, Apr
5 New Articles

Sending a Program Message in RPG

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

(Author's Note: This week's article is an excerpt from my upcoming book RPG TNT: 101 Dynamite Tips and Techniques for RPG IV Programmers.)

The CL language offers some easy commands to send program messages. To accomplish this in RPG IV requires either calling an API or using a CL program wrapper with the SNDPGMMSG command. The complexity of the APIs often keeps people away from using them, particularly since IBM put a level between the API caller and the previous program/procedure queue.

The solution is the Call-Stack Entry parameter of the QMHSNDPM API combined with the Relative Invocation parameter. The Call-Stack Entry parameter can be set to *, *CTLBDY or *EXT. The relative invocation parameter is normally set to one higher than you think it should be.

The API is a bit complex, but we can wrap in a subprocedure to perform a basic SNDPGMMSG to *PRV.

Here’s the QMHSNDPM API Pprototype:

        //  SEND Program Message API

      /include QSYSINC/QRPGLESRC,QUSEC
     D QMHSNDPM        PR                  ExtPgm('QMHSNDPM')
     D  szMsgID                       7A   Const
     D  szMsgFile                    20A   Const
     D  szMsgData                  6000A   Const OPTIONS(*varsize)
     D  nMsgDataLen                  10I 0 Const

      **  Message Type may be one of the following:
      **  *COMP    - Completion
      **  *DIAG    - Diagnostic
      **  *ESCAPE  - Escape
      **  *INFO    - Informational
      **  *INQ     - Inquiry. 
      **             (Only used when ToPgmQ(*EXT) is specified).
      **  *NOTIFY  - Notify
      **  *RQS     - Request
      **  *STATUS  - Status
     D  szMsgType                    10A   Const

      **  Call Stack Entry may be one of the following:
      **  *        - *SAME
      **  *EXT     - The external message queue
      **  *CTLBDY  - Control Boundary
     D  szCallStkEntry...
     D                               10A   Const
     D  nRelativeCallStkEntry...
     D                               10I 0 Const
     D  szRtnMsgKey                   4A
     D  apiErrorDS                         LikeDS(QUSEC)
     D                                     OPTIONS(*VARSIZE)

A simple subprocedure wrapper for this API can be a bit daunting. With programs consisting of modules and subprocedures, setting the correct parameter values can be challenging.

The subprocedure wrapping I want would allow me to send an impromptu message from within RPG IV, using parameters similar to those of the SNDMSG CL command. Here is the syntax for this subprocedure:

SNDMSG( 'message text' [ : msgtype [ : topgmq ] ] )

The message text parameter can be any text up to 1024 bytes in length and is required.

The msgtype (message type) parameter may be any of the available message types (in all uppercase), such as *INFO, *COMP, *DIAG, *ESCAPE, or *STATUS. The default, if not specified, is *INFO.

The topgmq (to program queue) parameter identifies the relative program queue to which the message is sent. If unspecified, its default is *SAME (which is represented internally as '*').

The following call to SNDMSG displays a status message on the screen until it is cleared or another status message is displayed.

sndmsg('Searching customer for past due invoices':'*STATUS');

Unlike native RPG IV built-in functions, subprocedures don't have the luxury of being able to specify user-written special values for parameters. When '*STATUS' is needed for this subprocedure, the value must be enclosed in quotes and specified in all uppercase.

One thing I like to use this routine for is to write information to the joblog at runtime, thus eliminating some debugging. For example:

Chain custno custmast;
if NOT %Found();
  sndmsg('Customer ' + %char(custno) + ' Not found.');
endif;

This code logs the message to the joblog at the same invocation level as the caller of the SNDMSG procedure.

There are a couple of additional features. The TOPGMQ parameter allows you to specify *PRV or *PRVPGM. Specifying *PRV sends the message to the caller of the procedure that is running SNDMSG. When *PRVPGM is specified, the message is sent to the previous program. This is important when using RPG IV with modules and procedures, as using SNDMSG('hellow' : '*INFO' : '*PRV') from within the mainline calculations of an RPG IV program will cause the message to be sent to the current program's program entry procedure (PEP), not to the previous program. Use *PRV PGM to send it to the previous program.

The source code for the sndmsg() example subprocedure is shown below. It will also be in RPG TNT: 101 Dynamite Tips and Techniques for RPG IV Programmers and will be posted within a few weeks on rpgiv.com/downloads.

     H OPTION(*NODEBUGIO:*SRCSTMT)
        // © 2001 by Robert Cozzi, Jr. All Rights reserved.
        //  Origin: RPG xTools
        //  Permission to use is hereby granted provided this
        //  notice is included in its entirety. 
      /IF DEFINED(*CRTBNDRPG)
     H  DFTACTGRP(*NO)
      /ELSE
     H  NOMAIN
      /ENDIF

      // TODO: Include the QMHSNDPM API Prototype here

     D SndMsg          PR             4A
     D  szMsg                      1024A   Const Varying
     D  szMsgType                    10A   Const 
     D                                     OPTIONS(*NOPASS)
     D  szToPgmQ                     10A   Const 
     D                                     OPTIONS(*NOPASS)

      /IF DEFINED(*CRTBNDRPG)
      /free
        sndmsg('Hello World!' );
        eval *INLR = *ON;
        return;
      /end-free
      /ENDIF

     P SndMsg          B                   Export
      *******************************************
      **  Send an impromptu message to a pgmq
      *******************************************
        // © 2006 by Robert Cozzi, Jr. All Rights reserved.
        //  Origin: RPG xTools
        //  Permission to use is hereby granted provided this
        //  notice is included in its entirety. 
     D SndMsg          PI             4A
     D  msg                        1024A   Const Varying
     D  szMsgType                    10A   Const 
     D                                     OPTIONS(*NOPASS)
     D  szToPgmQ                     10A   Const 
     D                                     OPTIONS(*NOPASS)

      *******************************************
      /include qsysinc/qrpglesrc,qusec
      *******************************************
      **  Local variables.
     D  msgType        S                   Like(szMsgType) Inz('*INFO')
     D  toPgmQ         S                   Like(szToPgmQ)  Inz('*')

     D msgid           S              7A   Inz('CPF9897')
     D msgf            DS            21
     D  MsgFile                      10A   Inz('QCPFMSG')
     D  MsgLib                       10A   Inz('*LIBL')
     D
     D msgData         S           1024A
     D nDataLen        S             10I 0 Inz(0)
     D nRelInv         S             10I 0 Inz(1)
     D nIncInv         S             10I 0 Inz(1)
     D RtnMsgKey       S              4A
     D myAPIErrorDS    DS                  LikeDS(QUSEC)

     C                   eval      myApiErrorDS = *ALLX'00'

     C                   if        %Parms()>=2
     C                   eval      msgType = szMsgType
     C                   if        %subst(msgType:1:1)<>'*'
     C                   eval      msgType = '*' + %TrimL(msgType)
     C                   endif
     C                   endif

     C                   if        %Parms()>= 3
     C                   if        szToPgmQ <> *BLANKS
     C                   eval      toPgmQ=  szToPgmQ
     C                   endif
     C                   if        toPgmQ = '*SAME'
     C                   eval      toPgmQ = '*'
     C                   endif
     C                   endif

         // Status messages always go ToPgmQ(*EXT)
     C                   if        msgType = '*STATUS'
     C                   eval      toPgmQ = '*EXT'
     C                   endif

     C                   if        msgType = '*'
     C                   eval      msgType = '*INFO'
     C                   endif

        // Get the length of the message to be sent.
     C                   eval      msgData = %Trim(msg)
     C                   eval      nDataLen = %len(%Trim(msg))

     C                   Select
      **  *SAME
     C                   when      toPgmQ  = ' '
     C                             or toPgmQ = '*SAME'
     C                             or toPgmQ = '*'
     C                   eval      toPgmQ = '*'
     C                   eval      nRelInv = 0
     C                   eval      nIncInv = 1
      **  *PRV, *PRVPRC or *PRVPROC
     C                   when      toPgmQ = '*PRVPRC'
     C                             or toPgmQ = '*PRVPROC'
     C                             or toPgmQ = '*PRV'
     C                   eval      toPgmQ = '*'
     C                   eval      nRelInv = 1
     C                   eval      nIncInv = 1
      **  *PRVPGM
     C                   When      toPgmQ = '*PRVPGM'
     C                   eval      toPgmQ = '*CTLBDY'
     C                   eval      nRelInv = 0
     C                   eval      nIncInv = 1
      **  *CTLBDY
     C                   when      toPgmQ = '*CTLBDY'
     C                   eval      nIncInv = 2
      **  *EXT
     C                   when      toPgmQ = '*EXT'
     C                   eval      nRelInv = 0
     C                   endsl

      **  Since we're a relative invocation, and we are
      **  one-level deep, we need to bump up the relative
      **  invocation by the calculated increment.
     C                   eval      nRelInv = nRelInv + nIncInv

     C                   callp(e)  QMHSNDPM(msgid   : msgf :
     C                                      msgData : nDataLen :
     C                                      msgType   :
     C                                      toPgmQ    :
     C                                      nRelInv   :
     C                                      rtnMsgKey :
     C                                      myAPIErrorDS)

     C                   return    rtnMsgKey
     P SndMsg          E

Bob Cozzi is a programmer/consultant, writer/author, and software developer of the RPG xTools, a popular add-on subprocedure library for RPG IV. His book The Modern RPG Language has been the most widely used RPG programming book for nearly two decades. He, along with others, speaks at and runs the highly-popular RPG World conference for RPG programmers.

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: