I have this Raw ESC/POS command for LX-300+, and i want to print it through Print Server using Socket.
String escp = " '\x1B' + '\x40', // initialize the printer, reset printer to defaults " +
" '\x1B' + '\x78' + '\x31', // Set Print Quality NLQ " +
" '\x1B' + '\x6B' + '\x31', // Select typeface San serif " +
" '\x1B' + '\x43' + '\x00' + '\x06', // set Page Length to 6 Inch " +
" '\x1B' + '\x4D', // Select 12 cpi Spacing " +
" '\x1B' + '\x45', // SET Bold Font ";
Question is, can we parse that String of escp with Socket? i use this code,
Socket socket = null;
OutputStream output = null;
BufferedReader reader = null;
try {
socket = new Socket("10.0.5.30", 9100);
socket.setSoTimeout(5000);
output = socket.getOutputStream();
reader = new BufferedReader(new java.io.InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
// TODO: handle exception
}
if (socket != null && output != null) {
try
{
output.write(escp.getBytes());
output.flush();
socket.shutdownOutput();
output.close();
socket.close();
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
The result is, printer LX-300 is not converting the ESC/POS Command. Just print the String inside escp variable. Any solution to this? i'm using linux 18.04 FYI.
Related
I'm trying to make Multiple GET calls using the same client. I've tried multiple things. New Variables, New instances. Closing Clients. The second Stock Call doesnt go through ever. It fails at "while (client.connected())" on the second Call. It Doesnt get to returning headers.
Any Ideas?
Code look like this
void loop()
{
WiFiClientSecure client;
//Stock
String payload;
// Use WiFiClientSecure class to create TLS connection
Serial.print("connecting to ");
Serial.println(host);
Serial.printf("Using fingerprint '%s'\n", fingerprint);
client.setFingerprint(fingerprint);
if (!client.connect(host, httpsPort))
{
Serial.println("connection failed");
client.stop();
//return;
}
//AAPL
String url = "/api/v1/quote?symbol=AAPL&token=XXXX";
Serial.print("requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.0\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("request sent");
while (client.connected())
{
String line = client.readStringUntil('\n');
// String line = client.readStringUntil('\r');
Serial.println(line);
if (line == "\r")
{
Serial.println("headers received");
payload = client.readStringUntil('\r');
//break;
}
}
Serial.println("payload");
Serial.println(payload);
// String line = client.readString();
//JsonObject& obj = doc.parseObject(payload);
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, payload);
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
// return;
client.stop();
}
//{"c":23.35,"d":-0.73,"dp":-3.0316,"h":24.6986,"l":23.25,"o":24.54,"pc":24.08,"t":1627588802}
double currentprice = doc["c"];
double pctchg = doc["d"];
// Print values.
Serial.println(currentprice);
Serial.println(pctchg);
Serial.println("closing connection");
client.stop();
delay(20000);
//SPY
String spyurl = "/api/v1/quote?symbol=SPY&token=XXXX";
Serial.print("requesting URL: ");
Serial.println(spyurl);
client.print(String("GET ") + spyurl + " HTTP/1.0\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("request sent");
String spypayload;
while (client.connected())
{
String spyline = client.readStringUntil('\n');
// String line = client.readStringUntil('\r');
Serial.println(spyline);
if (spyline == "\r")
{
Serial.println("headers received");
spypayload = client.readStringUntil('\r');
//break;
}
}
Serial.println("spypayload");
Serial.println(spypayload);
// String line = client.readString();
//JsonObject& obj = doc.parseObject(payload);
StaticJsonDocument<200> spydoc;
DeserializationError spyerror = deserializeJson(spydoc, spypayload);
// Test if parsing succeeds.
if (spyerror) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(spyerror.f_str());
// return;
client.stop();
}
//{"c":23.35,"d":-0.73,"dp":-3.0316,"h":24.6986,"l":23.25,"o":24.54,"pc":24.08,"t":1627588802}
double SPYcurrentprice = spydoc["c"];
double SPYpctchg = spydoc["d"];
// Print values.
Serial.println(SPYcurrentprice);
Serial.println(SPYpctchg);
Serial.println("closing connection");
client.stop();
I'm an idiot.
Needed to keep the connection open on the first call
"Connection: Keep-Alive\r\n\r\n");
I'm working on a project using a google script to publish images from an ESP32-CAM to google drive.
I keep getting the error "no response", no matter how long I set the wait peroid to. I tried using http and https(wificlient and wificlientsecure) but it doesn't work no matter what.
What could be the issue?
WiFiClientSecure clienthttps;
Serial.println("Connect to " + String(myDomain));
if (clienthttps.connect(myDomain, 443)) {
Serial.println("Connection successful");
camera_fb_t * fb = NULL;
fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
delay(1000);
ESP.restart();
return;
}
char *input = (char *)fb->buf;
char output[base64_enc_len(3)];
String imageFile = "";
for (int i = 0; i < fb->len; i++) {
base64_encode(output, (input++), 3);
if (i % 3 == 0) imageFile += urlencode(String(output));
}
String Data = myFilename + mimeType + myImage;
esp_camera_fb_return(fb);
Serial.println("Send a captured image to Google Drive.");
Serial.println("POST " + myScript + " HTTP/1.1");
Serial.println("Host: " + String(myDomain));
Serial.println("Content-Length: " + String(Data.length() + imageFile.length()));
Serial.println("Content-Type: application/x-www-form-urlencoded");
Serial.println(Data);
Serial.println();
clienthttps.println("POST " + myScript + " HTTP/1.1");
clienthttps.println("Host: " + String(myDomain));
clienthttps.println("Content-Length: " + String(Data.length() + imageFile.length()));
clienthttps.println("Content-Type: application/x-www-form-urlencoded");
clienthttps.println();
clienthttps.print(Data);
int Index;
for (Index = 0; Index < imageFile.length(); Index = Index + 1000) {
clienthttps.print(imageFile.substring(Index, Index + 1000));
}
Serial.println("Waiting for response.");
long int StartTime = millis();
while (!clienthttps.available()) {
Serial.print(".");
delay(100);
if ((StartTime + waitingTime) < millis()) {
Serial.println();
Serial.println("No response.");
//If you have no response, maybe need a greater value of waitingTime
break;
}
}
Serial.println();
while (clienthttps.available()) {
Serial.print(char(clienthttps.read()));
}
} else {
Serial.println("Connected to " + String(myDomain) + " failed.");
}
clienthttps.stop();
Note that in the latest "github.com/espressif/arduino-esp32" (as at 17Jan23) the command
"WiFiClientSecure.println();" (your "clienthttps.println()") seems to corrupt the SSL-buffer somehow, and although the command returns after a bit, the SSL-connection fails at that point (this didn't happen in earlier versions of the software).
The solution which worked for me was to ensure I at very least sent "WiFiClientSecure.println(" ");" (ie. " \r\n") as this seems to work.
(This solution appears also often necessary if sending data over a GPRS connection because in that instance a ".println()" seems to be ingored!)
I am using BaseX (XML based datastore) for its performance benchmarking. For testing it with ,
TestBeds
I) 10,000 users, 10 friends, 10 resources
II) 100,000 users , 10 friends, 10 resources
I faced below issues:
1) Loading of data is too slow. Gets slowed with eh increase in the number of threads.
2) Plus point - Reading/retriving values from BaseX is faster (17k operation per second)
3) Updating the data in BaseX is very slow. Throughput is ~10 operations per second.
Am I correct to say BaseX is 'TOO' slow for write/update operations (20/sec) compared to read/retrieve (10k/sec)?
Please advice me to make it more efficient for the write and update :
I have a function insertEntity (update or insert function) in to the BaseX datastore as follows -
public int insertEntity(String entitySet, String entityPK,
HashMap<String, ByteIterator> values, boolean insertImage) {
String parentTag ="",childTag ="", key="", entryTag="";
StringBuffer insertData = new StringBuffer();
Set<String> keys = values.keySet();
Iterator<String> iterator = keys.iterator();
while(iterator.hasNext()) {
String entryKey = iterator.next();
if(!(entryKey.equalsIgnoreCase("pic") || entryKey.equalsIgnoreCase("tpic")))
insertData.append("element " + entryKey + " {\"" + StringEscapeUtils.escapeXml(values.get(entryKey).toString()) + "\"},");
}
if(entitySet.equalsIgnoreCase("users")&& insertImage){
byte[] profileImage = ((ObjectByteIterator)values.get("pic")).toArray();
String encodedpImage = DatatypeConverter.printBase64Binary(profileImage);
insertData.append(" element pic {\"" + encodedpImage + "\"},");
profileImage = ((ObjectByteIterator)values.get("tpic")).toArray();
encodedpImage = DatatypeConverter.printBase64Binary(profileImage);
insertData.append(" element tpic {\"" + encodedpImage + "\"},");
}
if(entitySet.equalsIgnoreCase("users"))
{
parentTag = "users";
childTag = "members";
entryTag = "member";
key = "mem_id";
insertData.append("element confirmed_friends {}, element pending_friends {}");
}
if(entitySet.equalsIgnoreCase("resources"))
{
parentTag = "resources";
childTag = "resources";
entryTag = "resource";
key = "rid";
insertData.append("element manipulations {}");
}
try {
session.execute(new XQuery(
"insert node element " + entryTag
+ "{ attribute " + key + "{"
+ entityPK + "}, "
+ insertData.toString()
+ "} "
+ "into doc('" + databaseName + "/" + parentTag +".xml')/" + childTag
));
String q1 = "insert node element " + entryTag
+ "{ attribute " + key + "{"
+ entityPK + "}, "
+ insertData.toString()
+ "} "
+ "into doc('" + databaseName + "/" + parentTag +".xml')/" + childTag;
System.out.println(q1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
And the below function is acceptFriendship (update function)
public int acceptFriend(int inviterID, int inviteeID) {
// TODO Auto-generated method stub
String acceptFriendQuery1 = "insert node <confirmed_friend id = '"
+ inviterID + "'>"
+ " </confirmed_friend>"
+ "into doc('"+databaseName+"/users.xml')/members/member[#mem_id = '"+inviteeID+"']/confirmed_friends";
String acceptFriendQuery2 = "insert node <confirmed_friend id = '"
+ inviteeID + "'>"
+ " </confirmed_friend>"
+ "into doc('"+databaseName+"/users.xml')/members/member[#mem_id = '"+inviterID+"']/confirmed_friends";
String acceptFriendQuery3 = "delete node doc('"+databaseName+"/users.xml')/members/member[#mem_id = '"
+ inviteeID + "']/pending_friends/pending_friend[#id = '"+ inviterID +"']";
try {
session.execute(new XQuery(acceptFriendQuery1));
session.execute(new XQuery(acceptFriendQuery2));
session.execute(new XQuery(acceptFriendQuery3));
System.out.println("Inviter: "+inviterID +" AND Invitee: "+inviteeID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
Okay, I guess I'm stuck here. Can't get the values from the file to show in JOptionPane's message dialog box where it's enclosed within a while loop.
Right now I don't know which method of Input/Output stream to use to display all the data on this file which I believed to be serialized as UTF8??
Please tell me what to do and what things I missed since I'm new to java.io classes.
Also, the file StudentData.feu was just given to me. It's not that I don't want to research on my own because I already did, I'm just stuck. I read the Javadoc but I'm clueless right now.
import java.io.*;
import javax.swing.JOptionPane;
public class MyProj {
public void showMenu() {
String choice = JOptionPane.showInputDialog
(null, "Please enter a number: " + "\n[1] All Students" + "\n[2] BSCS Students" + "\n[3] BSIT Students"
+ "\n[4] BSA Students" + "\n[5] First Year Students" + "\n[6] Second Year Students" + "\n[7] Third Year Students"
+ "\n[8] Passed Students" + "\n[9] Failed Students" + "\n[0] Exit");
int choiceConvertedString = Integer.parseInt(choice);
switch(choiceConvertedString){
case 0:
JOptionPane.showMessageDialog(null, "Program closed!");
System.exit(1);
break;
}
}
DataInputStream myInputStream;
OutputStream myOutputStream;
int endOfFile = -1;
double grades;
int studentNo;
int counter;
String studentName;
String studentCourse;
public void readFile()
{
try
{
myInputStream = new DataInputStream
(new FileInputStream("C:\\Users\\Jordan's Pc\\Documents\\NetBeansProjects\\MyProj\\StudentData.feu"));
try{
while((counter=myInputStream.read()) != endOfFile)
{
studentName = myInputStream.readUTF();
studentCourse = myInputStream.readUTF();
grades = myInputStream.readDouble();
JOptionPane.showMessageDialog
(null, "StdNo: " + studentNo + "\n"
+ "Student Name: " + studentName + "\n"
+ "Student Course: " + studentCourse + "\n"
+ "Grades: " + grades);
}
}
catch(FileNotFoundException fnf){
JOptionPane.showMessageDialog(null, "File Not Found");
}
}/* end of try */
catch(EOFException ex)
{
JOptionPane.showMessageDialog(null, "Processing Complete");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "An error occured");
}
}
}
while((counter=myInputStream.read()) != endOfFile)
The problem is probably here. You're reading a byte and then throwing it away. It isn't likely that the file contains extra bytes like this that are intended to be thrown away. The correct loop would go like this:
try
{
for (;;)
{
// .... readUTF() etc
}
}
catch (EOFException exc)
{
// You've read to end of file.
}
// catch IOException etc.
I am using below function to call EAR_Encrypt_FTP.bat in C#. Is there any way to trace the echo messages dispayed in cmd.exe while running the batch file??
I need to process echo messages displayed on command prompt screen log the process.
private static short batchfileInvoke(string ftpFileName, string headerFile)
{
short value = 0;
Process p = null;
try
{
p = new Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "cmd.exe";
string argument1 = "EAR_Encrypt_FTP.bat";
string test = "\"" + ftpFileName + "\"";
string argument2 = test;
string test1 = "\"" + headerFile + "\"";
string argument3 = test1;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(argument1);
startInfo.Arguments = "/C EAREncryptFTP.bat " + argument2 + " " + argument3;
p.StartInfo = startInfo;
p.Start();
p.WaitForExit();
int value2 = p.ExitCode;
value = (short)value2;
if(value==0)
{
Console.WriteLine("Encryption process is done");
}
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred :{0},{1}",
ex.Message, ex.StackTrace.ToString());
value = -4;
}
return value;
}