### Make HTTP Request for Scales Data Source: https://github.com/printnode/printnode-js/blob/master/example.html Demonstrates how to make an HTTP GET request to retrieve scales data using the PrintNode.js HTTP client. It shows how to configure success, error, complete, and timeout callbacks, and how to handle responses using both callbacks and Promises. ```javascript var httpOptions = { success: function (responseBody, repsonse) { console.log("success", response); }, error: function (responseBody, repsonse) { console.log(response); }, complete: function (response) { console.log( "%d %s %s returned %db in %dms", response.xhr.status, response.reqMethod, response.reqUrl, response.xhr.responseText.length, response.getDuration() ); }, timeout: function (url, duration) { console.log("%s timeout %d", url, duration); } }; var http = new PrintNode.HTTP( new PrintNode.HTTP.ApiKey(API_KEY), httpOptions ); http.scales( { success: function (response) { console.log("success from callback", response); } }, { computerId: 0 } ).then( function (response, info ) { console.log("success from promise", response); }, function (err) { throw "simulated exception in a promise callback"; // If your promise callbacks start throw[ing] you can 'catch' this in the returned // promise from .then() but this is getting pretty meta right here. // Callbacks really shouldn't throw exceptions in async code like this. } ).then(null, console.log.bind(console, "promise callbacks threw error;")); ``` -------------------------------- ### Connect and Authenticate via WebSocket Source: https://github.com/printnode/printnode-js/blob/master/example.html Establishes a WebSocket connection to PrintNode, handles authentication, and registers callbacks for successful authentication and errors. It also shows how to subscribe to various events like computer events, scales events, and system state changes. ```javascript var API_KEY = ''; // got websocket if (!PrintNode.WebSocket.isSupported()) { // once a websocket is authenticated you can register function authenticated (authData) { if (authData.error) { // most likely not authenticated, see authData.error for more detail return; } // authData will contain information about accountId, permissions, and maxSubscriptions // ok, now make some requests to the server to get data you're interested in // pass in optional second argument to have this called when server publishes a event // but you can also use the event emitter this.getScales({}, function (measurement) { // this is only meaningful if the websocket is running on the same machine // as the running PrintNode client console.log("scales data by subscription callback", measurement); console.log("scales latency %dms", measurement.getLatency()); }); } // error callback fired if anything goes wrong including // - exceptions thrown by subscription callbacks // - network issues which cause socket to fail or any timeouts // - errors in printnode server or client libs function errorCallback (err, data) { console.log("Error!", err, data); } // instantiate a new var ws = new PrintNode.WebSocket( { apiKey: API_KEY }, authenticated, errorCallback ); // subscribe to all computer events ws.subscribe("computer", function computerEvent (something, info) { // lots of things could come in on this event // for now we're only interested in scalesMeasurements if (something instanceof PrintNode.ScalesMeasurement) { console.log("scales data by computer subscription", something); } }); // subscribe to all scales events ws.subscribe("scales", function computerEvent (measurement) { console.log("scales data by scales subscription", measurement); }); // debugging ws.subscribe('system.state', function stateChange (newState) { console.log("newState", newState); }); } else { // TODO fallback to polling } ``` -------------------------------- ### PrintNode.js HTTP Client Promise Example Source: https://github.com/printnode/printnode-js/blob/master/README.md Illustrates how to use the PrintNode.js HTTP client with Promises for handling asynchronous API responses. It shows how to chain `.then()` to handle successful responses and provide an error callback for failed requests. ```javascript api.whoami(options).then( function success (response, info) { console.log(response, info); }, function error (err) { console.error(err); } ); ``` -------------------------------- ### Close WebSocket Connection with PrintNode.js Source: https://github.com/printnode/printnode-js/blob/master/README.md Provides an example of how to properly close a WebSocket connection managed by the PrintNode.js library. This is useful for applications that no longer require an active connection to the PrintNode server. ```javascript var pN_WebSocket = new PrintNode.WebSocket( options, function (auth) { # some code in here } ); // close a websocket after 5s setTimeout(function () { pN_WebSocket.closeSocket(); }, 5000); ``` -------------------------------- ### Manage and Remove WebSocket Subscriptions Source: https://github.com/printnode/printnode-js/blob/master/README.md Illustrates how to manage active WebSocket subscriptions in PrintNode.js. It shows how to get a subscription ID when subscribing to data and how to remove specific subscriptions or all subscriptions using their IDs. ```javascript var pN_WebSocket = new PrintNode.WebSocket( options, function (auth) { // fetch test scale data var scalesSub = this.getScales({computerId: 0}); // stop fetching after 5 seconds setTimeout( function stopSendingMeStuff() { pN_WebSocket.removeServerSubscription(scalesSub); }, 5000 ); } ); var messageCnt = 0; pN_WebSocket.subscribe('scales', function (measurement) { console.log(++messageCnt, measurement); }); ``` -------------------------------- ### PrintNode.js HTTP Client Configuration and Usage Source: https://github.com/printnode/printnode-js/blob/master/README.md Demonstrates how to configure and use the PrintNode.js HTTP client. It includes setting up an options object with callbacks for success, error, completion, and timeouts, initializing the API with an API key, and making various API calls such as 'whoami', 'computers', and 'printers' with filtering options. ```javascript var options = { // changes the value of 'this' in the success, error, timeout and complete // handlers. The default value of 'this' is the instance of the PrintNodeApi // object used to make the api call context: null, // called if the api call was a 2xx success success: function (response, headers, xhrObject) { console.log(this); console.log("success", response, headers); }, // called if the api call failed in any way error: function (response, headers, xhrObject) { console.log("error", response, headers); }, // called afer the api call has completed after success or error callback complete: function (response) { console.log( "%d %s %s returned %db in %dms", response.xhr.status, response.reqMethod, response.reqUrl, response.xhr.responseText.length, response.getDuration() ); }, // called if the api call timed out timeout: function (url, duration) { console.log("timeout", url, duration) }, // the timeout duration in ms timeoutDuration: 3000 }; var api = new PrintNode.HTTP( new PrintNode.HTTP.ApiKey('your_api_key_here'), options ); // whoami - https://www.printnode.com/docs/api/curl/#whoami api.whoami(options); // computers - https://www.printnode.com/docs/api/curl/#computers api.computers(options); // with filtering api.computers(options, {computerSet: '-400'}); // printers - https://www.printnode.com/docs/api/curl/#printers api.printers(options); // with filtering by computer api.printers(options, {computerSet: '-400'}); // with filtering by computer and printer api.printers(options, {computerSet: '-400', printerSet: '100-'}); // creating a printjob - http://website2.printnode.com/docs/api/curl/#printjob-creating var printJobPayload = { "printerId": 8075, "title": "test printjob", "contentType": "pdf_uri", "content": "https://app.printnode.com/testpdfs/a4_portrait.pdf", "source": "javascript api client" } api.createPrintjob(options, printJobPayload); // scales HTTP REST - https://www.printnode.com/docs/api/curl/#scales-http api.scales(options, {computerId: 12}); // with device name api.scales(options, {computerId: 12, deviceName: 'foo_scales'}); // with device name and device id api.scales(options, {computerId: 12, deviceName: 'foo_scales', deviceId: 34}); // generate fake output from the scales for debug - https://www.printnode.com/docs/test-scales-api/ // (default timeout is extended to 15,000ms) api.scales(options, {computerId: 12, deviceName: 'foo_scales', deviceId: 34}); ``` -------------------------------- ### Subscribe to Scales Data with PrintNode.js Source: https://github.com/printnode/printnode-js/blob/master/README.md Demonstrates how to establish a WebSocket connection, authenticate, and subscribe to scales data using the PrintNode.js library. It shows how to handle authentication success and errors, and process incoming scales measurements. ```javascript function authenticate (authData) { if (authData.error) { // handle the error return; } // ok, we're authenticated - now let's get some scales data var scalesSub = this.getScales({computerId: 0}, function subCallback (scalesMeasurement) { console.log(scalesMeasurement); }); } function error () { console.error.apply(console, arguments); } var ws = new PrintNode.WebSocket({apiKey: 'insert apikey here'}, authenticate, error); ws.subscribe("authenticate", authenticate); ws.subscribe("error", error); ``` -------------------------------- ### Track Computer Connections with PrintNode JS Source: https://github.com/printnode/printnode-js/blob/master/README.md This snippet demonstrates how to establish a WebSocket connection to PrintNode, authenticate, and subscribe to computer connection and disconnection events. It includes a callback function to process the received connection data. ```javascript function authenticate (authData) { if (authData.error) { // handle the error return; } // ok, we're authenticated - now get some computer connection data var subscriptionId = this.getComputerConnections( {}, function subCallback (computerConnections) { // this === context, if we specify it below // do work here console.log(computerConnections); }//, context ); } function error () { console.error.apply(console, arguments); } var ws = new PrintNode.WebSocket( {apiKey: 'insert apikey here'}, authenticate, error ); ``` -------------------------------- ### Connect to PrintNode WebSocket Source: https://github.com/printnode/printnode-js/blob/master/README.md Establishes a WebSocket connection to the PrintNode API. Requires an API key and accepts optional callbacks for authentication and error handling. The authenticated callback receives account details upon successful connection. ```JavaScript function authenticate (authData) { console.log(authData); } function error (err) { console.error(err); } var ws = new PrintNode.WebSocket({apiKey: 'insert apikey here'}, authenticate, error); ``` -------------------------------- ### Subscribe using Array Syntax for Event Hierarchy Source: https://github.com/printnode/printnode-js/blob/master/README.md Shows an alternative method for subscribing to events in PrintNode.js using an array of strings to represent the event hierarchy. This method avoids the need for escaping dots in event names and is equivalent to the dot-separated string syntax. ```javascript // the following two lines are equivalent. ws.subscribe(['a','b','c'], callback); ws.subscribe('a.b.c', callback) ``` -------------------------------- ### Subscribe with Context and Data Source: https://github.com/printnode/printnode-js/blob/master/README.md Demonstrates how to subscribe to an event in PrintNode.js, passing custom context and data to the callback function. The 'context' option allows setting the 'this' value within the callback, while 'data' passes additional information. ```javascript ws.subscribe( "authenticate", function (payload, sub) { // this === objectThatWillResolveToThis // sub.data === myCustomData }, {context: objectThatWillResolveToThis, data: myCustomData} ); ``` -------------------------------- ### Subscribe to PrintNode WebSocket Events Source: https://github.com/printnode/printnode-js/blob/master/README.md Demonstrates subscribing to and unsubscribing from events published by the PrintNode WebSocket client. Events like 'authenticate' and 'error' can be handled using callback functions. Subscriptions can be removed by event name or by the callback function itself. ```JavaScript function error() { console.error(arguments); } var ws = new PrintNode.WebSocket({apiKey: 'insert apikey here'}) ws.subscribe("authenticate", function (authData) { console.log(authData); }); ws.subscribe("error", error) ; ws.unsubscribe("authenticate"); //by name ws.unsubscribe(error); //by function ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.