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;
}
}
Related
when playing trying to play audio in a chat application that I'm making I got the exception {"Source sample provider must be mono"} in this line var panProvider = new PanningSampleProvider(volumeProvider);
Code:
private void ReceiveUdpMessage(IAsyncResult ar)
{
try
{
byte[] bytesRead = UDPc.EndReceive(ar, ref ep);
var waveProvider = new BufferedWaveProvider(new WaveFormat(44100, 16, 2));
waveProvider.DiscardOnBufferOverflow = true;
waveProvider.AddSamples(bytesRead, 0, bytesRead.Length);
var volumeProvider = new VolumeSampleProvider(waveProvider.ToSampleProvider());
var panProvider = new PanningSampleProvider(volumeProvider);
mixer.AddMixerInput(panProvider);
UDPc.BeginReceive(new AsyncCallback(ReceiveUdpMessage), null);
}
catch(Exception ex)
{
}
UDPc.BeginReceive(new AsyncCallback(ReceiveUdpMessage), null);
}
I saw this answer Implementing Output audio panning with Naudio
but when mark answered in the comments:"I'd make a very simple alternative to VolumeSampleProvider that had a left and right volume property in that case".
he didn't elaborate and I'm new to this so have no idea what to do from here.
Does someone know what I'm supposed to do?
Thx
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.
Problem Description
I am a .NET Core developer and I have recently been asked to transcribe mp3 audio files that are approximately 20 minutes long into text. Thus, the file is about 30.5mb. The issue is that speech is sparse in this file, varying anywhere between 2 minutes between a spoken sentence or 4 minutes of length.
I've written a small service based on the google speech documentation that sends 32kb of streaming data to be processed from the file at a time. All was progressing well until I hit this error that I share below as follows:
I have searched via google-fu, google forums, and other sources and I have not encountered documentation on this error. Suffice it to say, I think this is due to the sparsity of spoken words in my file? I am wondering if there is a programmatical centric workaround?
Code
I have used some code that is a slight modification of the google .net sample for 32kb streaming. You can find it here.
public async void Run()
{
var speech = SpeechClient.Create();
var streamingCall = speech.StreamingRecognize();
// Write the initial request with the config.
await streamingCall.WriteAsync(
new StreamingRecognizeRequest()
{
StreamingConfig = new StreamingRecognitionConfig()
{
Config = new RecognitionConfig()
{
Encoding =
RecognitionConfig.Types.AudioEncoding.Flac,
SampleRateHertz = 22050,
LanguageCode = "en",
},
InterimResults = true,
}
});
// Helper Function: Print responses as they arrive.
Task printResponses = Task.Run(async () =>
{
while (await streamingCall.ResponseStream.MoveNext(
default(CancellationToken)))
{
foreach (var result in streamingCall.ResponseStream.Current.Results)
{
//foreach (var alternative in result.Alternatives)
//{
// Console.WriteLine(alternative.Transcript);
//}
if(result.IsFinal)
{
Console.WriteLine(result.Alternatives.ToString());
}
}
}
});
string filePath = "mono_1.flac";
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
//var buffer = new byte[32 * 1024];
var buffer = new byte[64 * 1024]; //Trying 64kb buffer
int bytesRead;
while ((bytesRead = await fileStream.ReadAsync(
buffer, 0, buffer.Length)) > 0)
{
await streamingCall.WriteAsync(
new StreamingRecognizeRequest()
{
AudioContent = Google.Protobuf.ByteString
.CopyFrom(buffer, 0, bytesRead),
});
await Task.Delay(500);
};
}
await streamingCall.WriteCompleteAsync();
await printResponses;
}//End of Run
Attempts
I've increased the stream to 64kb of streaming data to be processed and then I received the following error as can be seen below:
Which, I believe, means the actual api timed out. Which is decidely a step in the wrong direction. Has anybody encountered a problem such as mine with the Google Speech Api when dealing with a audio file with sparse speech? Is there a method in which I can filter the audio down to only spoken words progamatically and then process that? I'm open to suggestions, but my research and attempts have only lead me to further breaking my code.
There is to way for recognize audio in Google Speech API:
normal recognize
long running recognize
Your sample is uses the normal recognize, which has a limit for 15 minutes.
Try to use the long recognize method:
{
var speech = SpeechClient.Create();
var longOperation = speech.LongRunningRecognize( new RecognitionConfig()
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRateHertz = 16000,
LanguageCode = "hu",
}, RecognitionAudio.FromFile( filePath ) );
longOperation = longOperation.PollUntilCompleted();
var response = longOperation.Result;
foreach ( var result in response.Results )
{
foreach ( var alternative in result.Alternatives )
{
Console.WriteLine( alternative.Transcript );
}
}
return 0;
}
I hope it helps for you.
Pretty simple code to launch SaveFileDialog and then save data.
Opens prompt, I can select where I save, it saves file and then whole tab/app freezes. Obviously works fine on Windows/IE. Any suggestions?
private void SavePDFFile()
{
var saveFileDialog = new SaveFileDialog
{
DefaultExt = "pdf",
Filter = string.Format("Document(.{0})|*.{0}", "pdf"),
FilterIndex = 1,
DefaultFileName = DateTime.Now.ToString("HHmmMMddyyyy")
};
var saveClicked = saveFileDialog.ShowDialog();
if (!saveClicked.HasValue || !saveClicked.Value) return;
var fileStream = saveFileDialog.OpenFile();
try
{
this.IsBusy = true;
fileStream.Write(this.PDFData, 0, this.PDFData.Length);
fileStream.Close();
}
catch (Exception ex)
{
this.DisplayErrorMessage("Error saving PDF file", ex);
}
finally
{
this.IsBusy = false;
}
}
Answering my own question. This is nothing to do with code itself. It is security issue. In order to allow this code to execute on Mac (and it seems new versions of IE as well) you need to give it more permissions.
On IE you need to add website to list of Trusted sites.
On Mac - you need to set Silverlight to run in "Unsafe" mode. This is in Preferences/Security/Silverlight and need to select website, hold "Option" key and then open dropdown to see that option. Took a while to find it..
#katit I also faced this issue while working on a Silverlight OOB application.. my app was working fine in Windows but in Mac it got freezed and I have to force quit to use it again.
I was actually reading a PDF (stored in field type - 'varbinary') from server and storing it to user's local machine.
The solution worked for me is to download file chunks in parts (I used buffer size - 1 MB).
Not sure what file size you are using when your application gets freeze.. but I think, writing 'PDFData' to filestream in small parts may help you.
Also, add filestream.Flush(); (see highlighted in below code) in your code and see if this helps:
private void SavePDFFile()
{
var saveFileDialog = new SaveFileDialog
{
DefaultExt = "pdf",
Filter = string.Format("Document(.{0})|*.{0}", "pdf"),
FilterIndex = 1,
DefaultFileName = DateTime.Now.ToString("HHmmMMddyyyy")
};
var saveClicked = saveFileDialog.ShowDialog();
if (!saveClicked.HasValue || !saveClicked.Value) return;
var fileStream = saveFileDialog.OpenFile();
try
{
this.IsBusy = true;
fileStream.Write(this.PDFData, 0, this.PDFData.Length);
**filestream.Flush();**
fileStream.Close();
}
catch (Exception ex)
{
this.DisplayErrorMessage("Error saving PDF file", ex);
}
finally
{
this.IsBusy = false;
}
}
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.