Friday, June 01, 2007

Get printer state using SNMP

Nothing easier on windows: there's a very useful library called OLEPRN.DLL sitting in system folder.

You may use VBS like follows:

dim o

' create an COM object to communicate to network printer

set o = createobject("oleprn.olesnmp")

' open a snmp session to printer using its IP address, public interface, retry count 1 and 6000 msecs as timeout

o.open "192.168.1.18","public",1,6000

' get printer state by state OID

x = o.GetAsByte("25.3.2.1.5.1") '

' output the state: 2 is OK, all others are warning/error codes '

' change MsgBox to desired notification method '

MsgBox x


 

You may want to write a C++ code:

#include
"stdafx.h"

#import
"d:\\windows\\system32\\oleprn.dll" no_namespace

#define USAGE _T("usage: %s <printer IP address>\nsample: %s 10.10.10.10")


 

int _tmain(int argc, _TCHAR* argv[])

{

    if(argc < 2)

    {

        wprintf(USAGE,argv[0],argv[0]);

        return -1;

    }

    CoInitialize(NULL);

    ISNMPPtr aPtr;

    _bstr_t bstrHost(argv[1]);

    _bstr_t bstrCommunity("public");

    _bstr_t bstrOID("25.3.2.1.5.1");

    HRESULT hr = S_OK;

    try

    {

        hr = aPtr.CreateInstance(__uuidof(SNMP));

        hr = aPtr->Open(bstrHost,bstrCommunity);

        int iStatus = aPtr->GetAsByte(bstrOID);

        printf("Status %d\n",iStatus);

        aPtr.Release();

    }

    catch(_com_error *e)

    {

        wprintf(e->ErrorMessage());

    }

    catch(...)

    {        

        wprintf(_T("Unknown error occured\n"));

    }

    CoUninitialize();

    return 0;

}


 

Or you may want to get it working in managed code:

http://blog.crowe.co.nz/archive/2005/08/08/182.aspx


 

Enjoy!

3 comments:

Anonymous said...

Hey how what are the other status codes, and how we can get them,
For my printer i only get 2 as status even if it is out of paper.
So I have changed OID to 25.3.5.1.2.1 so i started getting other status code like 64,68,14,4.
Do u have any idea about these codes?

winmike said...

The codes may contain different state bits set - depending on Printer model.
For example, HP defines following bits:
# Condition Bit #
#
# lowPaper 0
#
# noPaper 1
# lowToner 2
# noToner 3
# doorOpen 4
# jammed 5
# offline 6
# serviceRequested 7
# inputTrayMissing 8
# outputTrayMissing 9
# markerSupplyMissing 10
# outputNearFull 11
# outputFull 12
# inputTrayEmpty 13
# overduePreventMaint 14

http://h30499.www3.hp.com/t5/Printers-LaserJet/SNMP-Laserjet-600/td-p/5860725#.U6qYCfmSzUU

Anonymous said...

Thanks for this sample code, it's clear, concise and actually works!