HPJetDirectTransport.cpp revision b12b2a60a74fd0f9e4d047dfac6bf0a248751c48
1/*
2 * Copyright 2001-2010 Haiku Inc. All rights reserved.
3 * Distributed under the terms of the MIT License.
4 *
5 * Authors:
6 *		Philippe Houdoin,
7 */
8
9
10#include "HPJetDirectTransport.h"
11
12#include <stdio.h>
13
14#include <Alert.h>
15#include <Message.h>
16#include <Directory.h>
17#include <SupportKit.h>
18#include <String.h>
19#include <NetEndpoint.h>
20
21#include "SetupWindow.h"
22
23
24HPJetDirectPort::HPJetDirectPort(BDirectory* printer, BMessage *msg)
25	: fHost(""),
26	fPort(9100),
27	fEndpoint(NULL),
28	fReady(B_ERROR)
29{
30	BString address;
31
32	if (printer->ReadAttrString("transport_address", &address) < 0
33		|| address.Length() == 0) {
34		SetupWindow *setup = new SetupWindow(printer);
35		if (setup->Go() == B_ERROR)
36			return;
37	}
38
39	if (printer->ReadAttrString("transport_address", &address) < 0)
40		return;
41
42	printf("address = %s\n", address.String());
43
44	int32 index = address.FindLast(':');
45	if (index >= 0) {
46		fPort = atoi(address.String() + index);
47		address.MoveInto(fHost, 0, index);
48	} else
49		fHost = address;
50
51	printf("fHost = %s\n", fHost.String());
52	printf("fPort = %d\n", fPort);
53
54
55	fEndpoint = new BNetEndpoint(SOCK_STREAM);
56	if ((fReady = fEndpoint->InitCheck()) != B_OK) {
57		BAlert *alert = new BAlert("", "Fail to create the NetEndpoint!", "OK");
58		alert->Go();
59		return;
60	}
61
62	if (fEndpoint->Connect(fHost, fPort) == B_OK) {
63		printf("Connected to HP JetDirect printer port at %s:%d\n",
64			fHost.String(), fPort);
65		fReady = B_OK;
66	} else {
67		BAlert *alert = new BAlert("",
68			"Can't connect to HP JetDirect printer port!", "OK");
69		alert->Go();
70		fReady = B_ERROR;
71	}
72}
73
74
75HPJetDirectPort::~HPJetDirectPort()
76{
77	if (fEndpoint) {
78		shutdown(fEndpoint->Socket(), SHUT_WR);
79		fEndpoint->Close();
80	}
81	delete fEndpoint;
82}
83
84
85ssize_t
86HPJetDirectPort::Read(void* buffer, size_t size)
87{
88	// printf("HPJetDirectPort::Read(%ld bytes)\n", size);
89	if (fEndpoint)
90		return (ssize_t) fEndpoint->Receive(buffer, size);
91	return 0;
92}
93
94
95ssize_t
96HPJetDirectPort::Write(const void* buffer, size_t size)
97{
98	// printf("HPJetDirectPort::Write(%ld bytes)\n", size);
99	if (fEndpoint)
100		return (ssize_t) fEndpoint->Send(buffer, size);
101	return 0;
102}
103
104