Brother Printer SDK cannot print label ERROR_WRONG_LABEL_ IOS - nativescript

I am trying to print a label from my Nativescript+Vue application for IOS. I can successfully connect to printer, however when I try to print an image, it will give me an Error. The printer I am using is the "QL-810W". The label that I have loaded is the 62mm roll (no set length) and can support both red and black.
Here is the surrounding code:
exports.BrotherPrinterClass = BrotherPrinterClass;
var BrotherPrinter = (function () {
function BrotherPrinter() {
}
BrotherPrinter.prototype.print_image = function (PrinterName, ipAddress, image) {
try {
let printer = new BRPtouchPrinter()
printer.printerName = PrinterName
printer.interface = CONNECTION_TYPE_WLAN
printer.setIPAddress(ipAddress)
let settings = new BRPtouchPrintInfo()
settings.strPaperName = "62mmRB"
settings.nPrintMode = 0x03 //PRINT_FIT_TO_PAGE
settings.nAutoCutFlag = 0x00000001 //OPTION_AUTOCUT
settings.nOrientation = 0x00 //ORI_LANDSCAPE
settings.nHorizontalAlign = 0x01 //ALIGN_CENTER
settings.nVerticalAlign = 0x01 //ALIGN_MIDDLE
printer.setPrintInfo(settings)
if (printer.startCommunication()) {
//Print to the printer
let errorCode = printer.printImageCopy(image.ios.CGImage, 1);
if (errorCode != 0)
console.log("ERROR - ", errorCode)
}
printer.endCommunication()
}
else{
console.log("Failed to connect")
}
}
catch(e) {
console.log("Error - ", e);
}
};
This then returns the error "-41" which correlates to ERROR_WRONG_LABEL_. I've tried adjusting all properties, I've also tried settings.strPaperName = "62mm" and that didn't return anything different.
The image that is been passed in is of an ImageSource type, and I've also tried the following line, let errorCode = printer.printImageCopy(image.ios, 1);. This returns an error code of 0 which correlates to ERROR_NONE_ But nothing gets printed out. And as far as I know, this isn't a CGImage like the SDK wants.
I can print from an iPad using the "iPrint&Label" app. Just not from the SDK
EDIT:
I have tried to print from a file using printFilesCopy(). This returns no error when I go to print, but nothing gets printed. Additionally, I can set the settings incorrectly (eg, change '62mmRB' for '102mm') or I can outright not set the settings by commenting out the printer.setPrintInfo(settings) line. These changes do not impact the result.
Furthermore, I have purchased a 62mm black only roll, and tried that, only to find that I have the exact same issue.

Related

Small font print command for Bluetooth printer

I'm working on the Bluetooth thermal printer implementation in Xamarin android,
Where i'm able to reset the printer and add the three additional lines using the print commands, but facing problem in reset the fonts to smallest size.
I'm resetting the printer using command "btInitialise"then trying to set small fonts using command "btFontB" and then adding 3 blank additional lines using "btAdvance3Lines".
The command in "btFontB" is not working properly or the command is wrong or the way i'm trying to achieve is wrong. A help will be appreciated here.
using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
{
BluetoothDevice device = (from bd in bluetoothAdapter?.BondedDevices where bd?.Name == deviceName
select bd).FirstOrDefault();
try
{
using (BluetoothSocket bluetoothSocket = device?.
CreateRfcommSocketToServiceRecord(
UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")))
{
if (bluetoothSocket == null)
return;
string btInitialise = "\x001b\x0040\n";
string btFontB = "\x001b\x0021\x0000\n";
string btAdvance3Lines = "\x001b\x0064\x0003\n";
await bluetoothSocket.ConnectAsync();
byte[] resetPrinter = Encoding.ASCII.GetBytes(btInitialise);
await bluetoothSocket.OutputStream.WriteAsync(resetPrinter, 0, resetPrinter.Length);
byte[] setFont = Encoding.ASCII.GetBytes(btFontB);
await bluetoothSocket.OutputStream.WriteAsync(setFont, 0, setFont.Length);
byte[] buffer = Encoding.UTF8.GetBytes(text);
await bluetoothSocket.OutputStream.WriteAsync(buffer, 0, buffer.Length);
byte[] addLines = Encoding.ASCII.GetBytes(btAdvance3Lines);
await bluetoothSocket.OutputStream.WriteAsync(addLines, 0, addLines.Length);
}
}
catch (Exception exp)
{
throw exp;
}
}

libXm get display number from widget

I'm using libXm4.0.3. I want to get the display number that the widget is being displayed on from the widget.
Going directly to xlib causes a segfault. Xt seems to also segfault.
I started using some of the XmGetXmDisplay or XmGetXmScreen functions, but I'm seeing "Could not find per display information" and I don't know how to overcome this.
How can I get the current display number from a libXm widget?
This is my current code:
int get_disp_num_from_widget(Widget w) {
Screen* xs = w->core.screen; //Xlib screen
if (xs) {
Display* xd = w->core.screen->display; //Xlib display
if (xd) {
XmDisplay d = XmGetXmDisplay(xd); // causes "Couldn't find per display information"
if (d) {
char* string = d->display.bindingsString;
if (string) {
printf("Display binding string: %s", string);
}
}
}
}
return -1;
}
You can get the Display * of any widget using the XtDisplay(Widget *) function.

Print labels via a redirected printer

My task is to print labels via a thermal printer. To this purpose a string of tspl(programming language that the printer understands) commands is generated and sent to the printer. The latter is done in C# with the following method taken from the microsoft example "How to send raw data to a printer by using Visual C# .NET"
public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "My C#.NET RAW Document";
di.pDataType = "RAW";
// Open the printer.
if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
{
// Start a document.
if (StartDocPrinter(hPrinter, 1, di))
{
// Start a page.
if (StartPagePrinter(hPrinter))
{
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if (bSuccess == false)
{
dwError = Marshal.GetLastWin32Error();
MessageBox.Show("Error " + dwError);
}
return bSuccess;
}
The actual printer is selected in a PrintDialog
private void button2_Click(object sender, EventArgs e)
{
string s = "CLS\nPRINT 1\n"; // device-dependent string, need a FormFeed?
// Allow the user to select a printer.
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new PrinterSettings();
if (DialogResult.OK == pd.ShowDialog(this))
{
// Send a printer-specific to the printer.
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s);
}
}
In my working environment everything works fine. The environment is a LAN consisting of 3 computers and 1 shared thermal printer:
PC_with_printer - it runs on Windows 7 and has the printer connected to it via USB
PC_aware - it runs on Win 8 and knows about the shared printer
PC_unaware - it runs on WinXP and doens't have the shared printer installed
From PC_aware I connect to PC_unaware via rdp and the printer appears in the list of printers as redirected. Then I run my application , choose the redirected printer and get my empty label printed. So far so good.
Problems begin when I replace PC_unaware with another computer. It runs on Windows Server 2008 R2 and is not in our LAN. Let's call it SERVER. So I carry out the same experiment:
From PC_aware I connect to SERVER via rdp using its public ip address
My thermal printer appears in "Printers and Devices" as "TSC_TDP-244 (redirected 20)"
I go to the printer's properties and click Print Test Page, and it gets printed
I run my app and the printer doesn't print anything.
I have checked return values of all winapi functions that are used in SendBytesToPrinter method (OpenPrinter,StartDocPrinter, StartPagePrinter, WritePrinter,EndPagePrinter,EndDocPrinter, ClosePrinter), and none of them indicates an error. Any idea why it happens and how it may be fixed?
PRINTER_DEFAULTS pd;
pd.DesiredAccess = PRINTER_ACCESS_USE;
pd.pDatatype = NULL;
pd.pDevMode = NULL;
if (!OpenPrinter(szPrinterName, &hPrinter, &pd))
return false;

Emulators Providing Different Results

I am developing an application on windows phone with version 7.1 set as my target build. The problem i am having is that one of the listviews in on of my pages refus to display.
I have debugged to ensure the list gets parsed with contents inside of it . Also the application runs fine when i use a windows 8 emulator. But the same technique used in populating other listviews in other pages of the application work fine on all emulators aprt from this single page that does not display.
I even tried to set the colour of the binding stack panel to see if it will show up and it does but without any content.
I am really confused and my code is very perfect. I wonder if any one has seem this issue before with windows phone emulators?
private void countdownClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
HtmlDocument doc = new HtmlDocument();
if (e.Error != null)
{
//MessageBox.Show(e.Error.InnerException.Message + "\n Ensure You Have A Working Internet Connection");
return;
}
doc.LoadHtml(e.Result);
String noCountdown = "<div><span>Sorry no buses are expected within 30 minutes of this stop. Please try again later or go to www.tfl.gov.uk</span></div>";
if (e.Result.Contains(noCountdown))
{
//No Buses Expected;
return;
}
else
{
HtmlNode stopCountdownNode;
try
{
stopCountdownNode = doc.DocumentNode.SelectSingleNode("//*[contains(#id, 'stopBoard')]").SelectSingleNode("tbody");
}
catch (Exception)
{
MessageBox.Show("Error Responce From Server");
return;
}
if (stopCountdownNode != null)
{
HtmlNodeCollection countdownNodeList = stopCountdownNode.SelectNodes("tr");
CountDownListBox.ItemsSource = GetCountdownList(countdownNodeList);
}
}
}
private ObservableCollection<BusCountdown> GetCountdownList(HtmlNodeCollection countdownNodeList)
{
ObservableCollection<BusCountdown> countdownList = new ObservableCollection<BusCountdown>();
foreach (HtmlNode countDown in countdownNodeList)
{
String busName = HttpUtility.HtmlDecode(countDown.SelectSingleNode("*[contains(#class, 'resRoute')]").InnerHtml);
String busDestination = HttpUtility.HtmlDecode(countDown.SelectSingleNode("*[contains(#class, 'resDir')]").InnerHtml);
String countDownTime = HttpUtility.HtmlDecode(countDown.SelectSingleNode("*[contains(#class, 'resDue')]").InnerHtml);
countdownList.Add(new BusCountdown(busName, busDestination, countDownTime));
}
return countdownList;
}
public string GetRandomSlash()
{
Random r = new Random();
String slash = "";
int rand = r.Next(1, 20);
for (int i = 0; i < rand; i++)
{
slash += "/";
}
return slash;
}
Try setting your class access specifier which you use to bind to public and give it a try. Let me know if it works.
For ex:
public class Bindingclass
{
public string Name{get;set;}
}
Try using Expression Blend and also delete your previous solution file and build a new solution.
Also set the build action property properly for all pages.
Update your SDK to 7.8 version. You will get multiple choices for Emulators - Emulator 7.1 (256 MB), Emulator 7.1 (512 MB), Emulator 7.8 (256 MB), Emulator 7.8 (512 MB). Test it on all these versions and check output on each Emulator type.
I hope at least one of these helps you get things get working. Let us know.

Using sockets (nsIServerSocket) in XPCOM component (Firefox Extension) (sockets + new window = seg faults)

PLEASE READ THE UPDATE #2 BELOW IF YOU ARE INTERESTED IN THIS PROBLEM ;)
Say I put this code into the JS of my extension.
var reader = {
onInputStreamReady : function(input) {
var sin = Cc["#mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
sin.init(input);
sin.available();
var request = '';
while (sin.available()) {
request = request + sin.read(512);
}
console.log('Received: ' + request);
input.asyncWait(reader,0,0,null);
}
}
var listener = {
onSocketAccepted: function(serverSocket, clientSocket) {
console.log("Accepted connection on "+clientSocket.host+":"+clientSocket.port);
input = clientSocket.openInputStream(0, 0, 0).QueryInterface(Ci.nsIAsyncInputStream);
output = clientSocket.openOutputStream(Ci.nsITransport.OPEN_BLOCKING, 0, 0);
input.asyncWait(reader,0,0,null);
}
}
var serverSocket = Cc["#mozilla.org/network/server-socket;1"].
createInstance(Ci.nsIServerSocket);
serverSocket.init(-1, true, 5);
console.log("Opened socket on " + serverSocket.port);
serverSocket.asyncListen(listener);
Then I run Firefox and connect to the socket via telnet
telnet localhost PORT
I send 5 messages and they get printed out, but when I try to send 6th message I get
firefox-bin: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.0.
Even worse, when I try to put this same code into an XPCOM component (because that's where I actually need it), after I try sending a message via telnet I get
Segmentation fault
or sometimes
GLib-ERROR **: /build/buildd/glib2.0-2.24.1/glib/gmem.c:137: failed to allocate 32 bytes
aborting...
Aborted
printed to the terminal from which I launched firefox.
This is really weird stuff.. Can you spot something wrong with the code I've pasted or is smth wrong with my firefox/system or is the nsIServerSocket interface deprecated?
I'm testing with Firefox 3.6.6.
I would really appreciate some answer. Perhaps you could point me to a good example of using Sockets within an XPCOM component. I haven't seen many of those around.
UPDATE
I just realised that it used to work so now I think that my Console
component breaks it. I have no idea how this is related. But if I
don't use this component the sockets are working fine.
Here is the code of my Console component. I will try to figure out
what's wrong and why it interferes and I'll post my findings later.
Likely I'm doing something terribly wrong here to cause Segmentation
faults with my javascript =)
Voodoo..
components/Console.js:
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
Console.prototype = (function() {
var win;
var initialized = false;
var ready = false;
var _log = function(m, level, location) {
if (initialized&&ready) {
var prefix = "INFO: ";
switch (level) {
case "empty":
prefix = ""
break;
case "error":
prefix = "ERORR: "
break;
case "warning":
prefix = "WARNING: "
break;
}
win.document.getElementById(location).value =
win.document.getElementById(location).value + prefix + m + "\n";
win.focus();
} else if (initialized&&!ready) {
// Now it is time to create the timer...
var timer = Components.classes["#mozilla.org/timer;1"]
.createInstance(Components.interfaces.nsITimer);
// ... and to initialize it, we want to call
event.notify() ...
// ... one time after exactly ten second.
timer.initWithCallback(
{ notify: function() { log(m); } },
10,
Components.interfaces.nsITimer.TYPE_ONE_SHOT
);
} else {
init();
log(m);
}
}
var log = function(m, level) {
_log(m, level, 'debug');
}
var poly = function(m, level) {
_log(m, "empty", 'polyml');
}
var close = function() {
win.close();
}
var setReady = function() {
ready = true;
}
var init = function() {
initialized = true;
var ww = Components.classes["#mozilla.org/embedcomp/window-
watcher;1"]
.getService(Components.interfaces.nsIWindowWatcher);
win = ww.openWindow(null, "chrome://polymlext/content/
console.xul",
"console", "chrome,centerscreen,
resizable=no", null);
win.onload = setReady;
return win;
}
return {
init: init,
log : log,
poly : poly,
}
}());
// turning Console Class into an XPCOM component
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
function Console() {
this.wrappedJSObject = this;
}
prototype2 = {
classDescription: "A special Console for PolyML extension",
classID: Components.ID("{483aecbc-42e7-456e-b5b3-2197ea7e1fb4}"),
contractID: "#ed.ac.uk/poly/console;1",
QueryInterface: XPCOMUtils.generateQI(),
}
//add the required XPCOM glue into the Poly class
for (attr in prototype2) {
Console.prototype[attr] = prototype2[attr];
}
var components = [Console];
function NSGetModule(compMgr, fileSpec) {
return XPCOMUtils.generateModule(components);
}
I'm using this component like this:
console = Cc["#ed.ac.uk/poly/console;1"].getService().wrappedJSObject;
console.log("something");
And this breaks the sockets :-S =)
UPDATE #2
Ok, if anyone is interested in checking this thing out I would really
appreciate it + I think this is likely some kind of bug (Seg fault
from javascript shouldn't happen)
I've made a minimal version of the extension that causes the problem,
you can install it from here:
http://dl.dropbox.com/u/645579/segfault.xpi
The important part is chrome/content/main.js:
http://pastebin.com/zV0e73Na
The way my friend and me can reproduce the error is by launching the
firefox, then a new window should appear saying "Opened socket on
9999". Connect using "telnet localhost 9999" and send a few messages.
After 2-6 messages you get one of the following printed out in the
terminal where firefox was launched:
1 (most common)
Segmentation fault
2 (saw multiple times)
firefox-bin: Fatal IO error 11 (Resource temporarily unavailable) on
X
server :0.0.
3 (saw a couple of times)
GLib-ERROR **: /build/buildd/glib2.0-2.24.1/glib/gmem.c:137: failed
to
allocate 32 bytes
aborting...
Aborted
4 (saw once)
firefox-bin: ../../src/xcb_io.c:249: process_responses: Assertion
`(((long) (dpy->last_request_read) - (long) (dpy->request)) <= 0)'
failed.
Aborted
If you need any more info or could point me to where to post a bug
report :-/ I'll be glad to do that.
I know this is just one of the many bugs... but perhaps you have an
idea of what should I do differently to avoid this? I would like to
use that "console" of mine in such way.
I'll try doing it with buffer/flushing/try/catch as people are suggesting, but I wonder whether try/catch will catch the Seg fault...
This is a thread problem. The callback onInputStreamReady happened to be executed in a different thread and accessing UI / DOM is only allowed from the main thread.
Solution is really simple:
change
input.asyncWait(reader,0,0,null);
to
var tm = Cc["#mozilla.org/thread-manager;1"].getService();
input.asyncWait(reader,0,0,tm.mainThread);

Resources