summaryrefslogtreecommitdiff
path: root/branches/sm-unittesting/src/org/reprap/devices/GenericExtruder.java
blob: 1ac25b3068f7606e7305d2667495bb1e9fe59cdf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package org.reprap.devices;

import java.io.IOException;

import org.reprap.Device;
import org.reprap.comms.Address;
import org.reprap.comms.Communicator;
import org.reprap.comms.IncomingContext;
import org.reprap.comms.IncomingMessage;
import org.reprap.comms.OutgoingMessage;
import org.reprap.comms.IncomingMessage.InvalidPayloadException;
import org.reprap.comms.messages.OutgoingBlankMessage;
import org.reprap.comms.messages.OutgoingByteMessage;

public class GenericExtruder extends Device {

	public static final byte MSG_SetActive = 1;
	public static final byte MSG_IsEmpty = 8;
	public static final byte MSG_SetHeat = 9;
	public static final byte MSG_GetTemp = 10;
	public static final byte MSG_SetVRef = 52;
	public static final byte MSG_SetTempScaler = 53;
	
	/// Offset of 0 degrees centigrade from absolute zero
	private static final double absZero = 273.15;
	
	/// The temperature to maintain
	private double requestedTemperature = 0;
	
	/// The temperature most recently read from the device
	private double currentTemperature = 0;
	
	private boolean currentMaterialOutSensor = false;
	
	/// Indicates when polled values are first ready
	private boolean sensorsInitialised = false;
	
	private Thread pollThread = null;
	private boolean pollThreadExiting = false;

	private int vRefFactor = 3;  ///< Default firmware value
	private int tempScaler = 7;  ///< Default firmware value
	
	private double beta;  ///< Thermistor beta
	private double rz;    ///< Thermistor resistance at 0C
	
	/// Flag indicating if initialisation succeeded.  Usually this
	/// indicates if the extruder is present in the network.
	private boolean isCommsAvailable = false;
	
	public GenericExtruder(Communicator communicator, Address address, double beta, double rz) {
		super(communicator, address);

		this.beta = beta;
		this.rz = rz;

		//setVref(3);
		//setTempScaler(7);
		
		// Check Extruder is available
		try {
			getVersion();
		} catch (Exception ex) {
			isCommsAvailable = false;
			return;
		}
		
		isCommsAvailable = true;
		
		pollThread = new Thread() {
			public void run() {
				Thread.currentThread().setName("Extruder poll");
				boolean first = true;
				while(!pollThreadExiting) {
					try {
						// Sleep is beforehand to prevent runaway on exception
						if (!first) Thread.sleep(2000);
						RefreshTemperature();
						RefreshEmptySensor();
						sensorsInitialised = true;
						first = false;
					}
					catch (InterruptedException ex) {
						// This is normal when shutting down, so ignore
					}
					catch (Exception ex) {
						System.out.println("Exception during temperature poll");
						ex.printStackTrace();
					}
				}
			}
		};
		pollThread.start();

	
	}

	public void dispose() {
		if (pollThread != null) {
			pollThreadExiting = true;
			pollThread.interrupt();
		}
	}
	
	/**
	 * Start the extruder motor at a given speed
	 * @param speed The speed to drive the motor at (0-255)
	 * @throws IOException
	 */
	public void setExtrusion(int speed) throws IOException {
		lock();
		try {
			OutgoingMessage request =
				new OutgoingByteMessage(MSG_SetActive, (byte)speed);
			sendMessage(request);
		}
		finally {
			unlock();
		}
	}

	/**
	 * Set extruder temperature
	 * @param temperature
	 * @throws Exception
	 */
	public void setTemperature(int temperature) throws Exception {
		// Currently just implemented as a chop-chop heater by
		// setting safety cutoff temperature to desired
		// temperature.  This can be improved by modelling
		// the thermal characteristics and directly setting
		// the appropriate heat output, rather than full-on/full off
		
		requestedTemperature = temperature;
		
		// safety margin
		double safetyTemperature = temperature;
		
		// Now convert safety level to equivalent raw PIC temperature value
		double safetyResistance = calculateResistanceForTemperature(safetyTemperature);
		// Determine equivalent raw value
		int safetyPICTemp = calculatePicTempForResistance(safetyResistance);
		if (safetyPICTemp < 0) safetyPICTemp = 0;
		if (safetyPICTemp > 255) safetyPICTemp = 255;
		
		if (temperature == 0)
			setHeater(0, 0);
		else
			setHeater(255, safetyPICTemp);
			
	}
	
	/**
	 * Set the raw heater output value and safety cutoff.  A specific
	 * temperature can be reached by setting a suitable output power.
	 * A limit temperature can also be specified.  If reached, the
	 * heater will be automatically turned off until the temperature
	 * drops below the limit.
	 * @param heat A heater power output
	 * @param safetyCutoff A temperature at which to cut off the heater
	 * @throws IOException
	 */
	private void setHeater(int heat, int safetyCutoff) throws IOException {
		//System.out.println("Set heater to " + heat + " limit " + safetyCutoff);
		lock();
		try {
			sendMessage(new RequestSetHeat((byte)heat, (byte)safetyCutoff));
		}
		finally {
			unlock();
		}
	}

	/**
	 * Check if the extruder is out of feedstock
	 * @return true if there is no material remaining
	 */
	public boolean isEmpty() {
		awaitSensorsInitialised();
		return currentMaterialOutSensor;
	}
	
	private void awaitSensorsInitialised() {
		// Simple minded wait to let sensors become valid
		while(!sensorsInitialised) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
	}
	
	/**
	 * Called internally to refresh the empty sensor.  This is
	 * called periodically in the background by another thread.
	 * @throws IOException
	 */
	private void RefreshEmptySensor() throws IOException {
		// TODO in future, this should use the notification mechanism rather than polling (when fully working)
		//System.out.println("Refreshing sensor");
		lock();
		try {
			IncomingContext replyContext = sendMessage(new OutgoingBlankMessage(MSG_IsEmpty));
			RequestIsEmptyResponse reply = new RequestIsEmptyResponse(replyContext);
			currentMaterialOutSensor = reply.getValue() == 0 ? false : true; 
		} catch (InvalidPayloadException e) {
			throw new IOException();
		} finally {
			unlock();
		}
	}

	public double getTemperatureTarget() {
		return requestedTemperature;
	}

	public double getTemperature() {
		awaitSensorsInitialised();
		return currentTemperature;
	}
	
	private void RefreshTemperature() throws Exception {
		//System.out.println("Refreshing temperature");
		getDeviceTemperature();
	}
	
	private void getDeviceTemperature() throws Exception {
		lock();
		try {
			OutgoingMessage request = new OutgoingBlankMessage(MSG_GetTemp);
			IncomingContext replyContext = sendMessage(request);
			RequestTemperatureResponse reply = new RequestTemperatureResponse(replyContext);
			
			//System.out.println("Raw temp " + reply.getHeat());
	
			double resistance = calculateResistance(reply.getHeat(), reply.getCalibration());
			
			currentTemperature = calculateTemperature(resistance);
		}
		finally {
			unlock();
		}
	}

	/**
	 * Calculates the actual resistance of the thermistor
	 * from the raw timer values received from the PIC. 
	 * @param picTemp
	 * @param calibrationPicTemp
	 * @return
	 */
	private double calculateResistance(int picTemp, int calibrationPicTemp) {
		// TODO remove hard coded constants
		// TODO should use calibration value instead of first principles
		
		//double resistor = 10000;                   // ohms
		double c = 1e-6;                           // farads
		double scale = 1 << (tempScaler+1);
		double clock = 4000000.0 / (4.0 * scale);  // hertz		
		double vdd = 5.0;                          // volts
		
		double vRef = 0.25 * vdd + vdd * vRefFactor / 32.0;  // volts
		
		double T = picTemp / clock; // seconds
		
		double resistance =	-T / (Math.log(1 - vRef / vdd) * c);  // ohms
		
		return resistance;
	}

	/**
	 * Calculate temperature in celsius given resistance in ohms
	 * @param resistance
	 * @return
	 */
	private double calculateTemperature(double resistance) {
		return (1.0 / (1.0 / absZero + Math.log(resistance/rz) / beta)) - absZero;
	}
	
	private double calculateResistanceForTemperature(double temperature) {
		return rz * Math.exp(beta * (1/(temperature + absZero) - 1/absZero));
	}
	
	/**
	 * Calculates an expected PIC Temperature expected for a
	 * given resistance 
	 * @param resistance
	 * @return
	 */
	private int calculatePicTempForResistance(double resistance) {
		double c = 1e-6;                           // farads
		double scale = 1 << (tempScaler+1);
		double clock = 4000000.0 / (4.0 * scale);  // hertz		
		double vdd = 5.0;                          // volts
		
		double vRef = 0.25 * vdd + vdd * vRefFactor / 32.0;  // volts
		
		double T = -resistance * (Math.log(1 - vRef / vdd) * c);

		double picTemp = T * clock;
		return (int)Math.round(picTemp);
		
	}
	
	/**
	 * Set raw voltage reference used for analogue to digital converter
	 * @param ref Set reference voltage (0-63)
	 * @throws IOException
	 */
	protected void setVref(int ref) throws IOException {
		lock();
		try {
			sendMessage(new OutgoingByteMessage(MSG_SetVRef, (byte)ref));		
			vRefFactor = ref;
		}
		finally {
			unlock();
		}
	}

	/**
	 * Set the scale factor used on the temperature timer used
	 * for analogue to digital conversion
	 * @param scale
	 * @throws IOException
	 */
	protected void setTempScaler(int scale) throws IOException {
		lock();
		try {
			sendMessage(new OutgoingByteMessage(MSG_SetTempScaler, (byte)scale));		
			tempScaler = scale;
		}
		finally {
			unlock();
		}
	}
	
	public boolean isAvailable() {
		return isCommsAvailable;
	}

	
	protected class RequestTemperatureResponse extends IncomingMessage {
		public RequestTemperatureResponse(IncomingContext incomingContext) throws IOException {
			super(incomingContext);
		}
		
		protected boolean isExpectedPacketType(byte packetType) {
			return packetType == MSG_GetTemp; 
		}
		
		public int getHeat() throws InvalidPayloadException {
		    byte [] reply = getPayload();
		    if (reply == null || reply.length != 3)
		    		throw new InvalidPayloadException();
		    return reply[1] < 0 ? reply[1] + 256 : reply[1];
		}

		public int getCalibration() throws InvalidPayloadException {
		    byte [] reply = getPayload();
		    if (reply == null || reply.length != 3)
		    		throw new InvalidPayloadException();
		    return reply[2] < 0 ? reply[2] + 256 : reply[2];
		}
		
	}

	protected class RequestSetHeat extends OutgoingMessage {
		byte [] message;
		
		RequestSetHeat(byte heat, byte cutoff) {
			message = new byte [] { MSG_SetHeat, heat, cutoff }; 
		}
		
		public byte[] getBinary() {
			return message;
		}
		
	}
	
	protected class RequestIsEmptyResponse extends IncomingMessage {

		public RequestIsEmptyResponse(IncomingContext incomingContext)
		throws IOException {
			super(incomingContext);
		}
		
		public byte getValue() throws InvalidPayloadException {
			byte [] reply = getPayload();
			if (reply == null || reply.length != 2)
				throw new InvalidPayloadException();
			return reply[1];
		}
		
		protected boolean isExpectedPacketType(byte packetType) {
			return packetType == MSG_IsEmpty;
		}
		
	}


}