code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#!/bin/bash echo Read serial port echo Usage $0 [BaudRate] \(default 9600\) echo Try 2400, 4800, 9600, 19200, 38400, 57600, 115200, ... CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP readserialport.SerialReader $*
12nosanshiro-pi4j-sample
ReadSerialPort/run
Shell
mit
228
package readserialport; import com.pi4j.io.serial.Serial; import com.pi4j.io.serial.SerialDataEvent; import com.pi4j.io.serial.SerialDataListener; import com.pi4j.io.serial.SerialFactory; import com.pi4j.io.serial.SerialPortException; import java.util.Date; public class SerialReader { public static void main(String args[]) throws InterruptedException, NumberFormatException { int br = Integer.parseInt(System.getProperty("baud.rate", "9600")); if (args.length > 0) { try { br = Integer.parseInt(args[0]); } catch (Exception ex) { System.err.println(ex.getMessage()); } } System.out.println("Serial Communication."); System.out.println(" ... connect using settings: " + Integer.toString(br) + ", N, 8, 1."); System.out.println(" ... data received on serial port should be displayed below."); // create an instance of the serial communications class final Serial serial = SerialFactory.createInstance(); // create and register the serial data listener serial.addListener(new SerialDataListener() { @Override public void dataReceived(SerialDataEvent event) { // print out the data received to the console System.out.print(/*"Read:\n" + */ event.getData()); } }); try { // open the default serial port provided on the GPIO header System.out.println("Opening port [" + Serial.DEFAULT_COM_PORT + ":" + Integer.toString(br) + "]"); serial.open(Serial.DEFAULT_COM_PORT, br); System.out.println("Port is opened."); // continuous loop to keep the program running until the user terminates the program while (true) { if (serial.isOpen()) { System.out.println("Writing to the serial port..."); try { // write a formatted string to the serial transmit buffer serial.write("CURRENT TIME: %s", new Date().toString()); // write a individual bytes to the serial transmit buffer serial.write((byte) 13); serial.write((byte) 10); // write a simple string to the serial transmit buffer serial.write("Second Line"); // write a individual characters to the serial transmit buffer serial.write('\r'); serial.write('\n'); // write a string terminating with CR+LF to the serial transmit buffer serial.writeln("Third Line"); } catch (IllegalStateException ex) { ex.printStackTrace(); } } else { System.out.println("Not open yet..."); } // wait 1 second before continuing Thread.sleep(1000); } } catch (SerialPortException ex) { System.out.println(" ==>> SERIAL SETUP FAILED : " + ex.getMessage()); return; } } }
12nosanshiro-pi4j-sample
ReadSerialPort/src/readserialport/SerialReader.java
Java
mit
2,951
#!/bin/bash echo Driving a relay, pin 00 CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP relay.Relay01
12nosanshiro-pi4j-sample
Relay/run
Shell
mit
115
package relay; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * 5v are required to drive the relay * The GPIO pins deliver 3.3v * To drive a relay, a relay board is required. * (it may contain what's needed to drive the relay with 3.3v) */ public class Relay01 { public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - pin 00/#17 and 01/#18 ... started."); System.out.println("(Labelled #17 an #18 on the cobbler.)"); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // For a relay it seems that HIGH means NC (Normally Closed)... final GpioPinDigitalOutput pin17 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "Relay1", PinState.HIGH); final GpioPinDigitalOutput pin18 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "Relay2", PinState.HIGH); System.out.println("--> GPIO state should be: OFF, and it is "); Thread.sleep(1000); pin17.low(); System.out.println("--> pin 17 should be: ON, and it is " + (pin17.isHigh()?"OFF":"ON")); Thread.sleep(1000); pin17.high(); System.out.println("--> pin 17 should be: OFF"); Thread.sleep(1000); pin18.low(); System.out.println("--> pin 18 should be: ON"); Thread.sleep(1000); pin18.high(); System.out.println("--> pin 18 should be: OFF"); gpio.shutdown(); } }
12nosanshiro-pi4j-sample
Relay/src/relay/Relay01.java
Java
mit
1,544
#!/bin/bash echo Read an ADC # CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adc.sample.SampleMain $*
12nosanshiro-pi4j-sample
ADC/run.cli
Shell
mit
116
#!/usr/bin/env python import time import os import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) DEBUG = 0 # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7) def readadc(adcnum, clockpin, mosipin, misopin, cspin): if ((adcnum > 7) or (adcnum < 0)): return -1 GPIO.output(cspin, True) GPIO.output(clockpin, False) # start clock low GPIO.output(cspin, False) # bring CS low commandout = adcnum print "---------------------------" displayNumber("Base:", adcnum) commandout |= 0x18 # start bit + single-ended bit displayNumber("0x18:", adcnum) commandout <<= 3 # we only need to send 5 bits here for i in range(5): displayNumber(("i:%i" % i), adcnum) if (commandout & 0x80): # 0x80 = 10000000 GPIO.output(mosipin, True) else: GPIO.output(mosipin, False) commandout <<= 1 GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout = 0 # read in one empty bit, one null bit and 10 ADC bits for i in range(12): GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout <<= 1 if (GPIO.input(misopin)): adcout |= 0x1 displayNumber(("ADCOUT i:%i" % i), adcout) GPIO.output(cspin, True) adcout >>= 1 # first bit is 'null' so drop it displayNumber("final ADCOUT:", adcout) return adcout def displayNumber(prefix, num): print prefix, num, "\t", hex(num), "\t", bin(num) # change these as desired - they're the pins connected from the # SPI port on the ADC to the Cobbler SPICLK = 18 SPIMISO = 23 SPIMOSI = 24 SPICS = 25 # set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) # 10k trim pot connected to adc #0 potentiometer_adc = 0; last_read = 0 # this keeps track of the last potentiometer value tolerance = 5 # to keep from being jittery we'll only change # volume when the pot has moved more than 5 'counts' while True: # we'll assume that the pot didn't move trim_pot_changed = False # read the analog pin trim_pot = readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS) # how much has it changed since the last read? pot_adjust = abs(trim_pot - last_read) if DEBUG: print "trim_pot :", trim_pot print "pot_adjust:", pot_adjust print "last_read :", last_read if ( pot_adjust > tolerance ): trim_pot_changed = True if DEBUG: print "trim_pot_changed", trim_pot_changed if ( trim_pot_changed ): set_volume = trim_pot / 10.24 # convert 10bit adc0 (0-1024) trim pot read into 0-100 volume level set_volume = round(set_volume) # round out decimal value set_volume = int(set_volume) # cast volume as integer print 'Volume = {volume}%' .format(volume = set_volume) # set_vol_cmd = 'sudo amixer cset numid=1 -- {volume}% > /dev/null' .format(volume = set_volume) # os.system(set_vol_cmd) # set volume if DEBUG: print "set_volume", set_volume print "tri_pot_changed", set_volume # save the potentiometer reading for the next loop last_read = trim_pot # hang out and do nothing for a half second time.sleep(0.5)
12nosanshiro-pi4j-sample
ADC/raspi-adc-pot.py
Python
mit
3,801
#!/bin/bash JAVAC_OPTIONS="-sourcepath ./src" JAVAC_OPTIONS="$JAVAC_OPTIONS -d ./classes" echo $JAVAC_OPTIONS CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/jansi-1.9.jar CP=$CP:./lib/orasocket-client-12.1.3.jar # JAVAC_OPTIONS="-verbose $JAVAC_OPTIONS" JAVAC_OPTIONS="$JAVAC_OPTIONS -cp $CP" COMMAND="javac $JAVAC_OPTIONS `find ./src -name '*.java' -print`" echo Compiling: $COMMAND $COMMAND echo Done
12nosanshiro-pi4j-sample
ADC/compile
Shell
mit
419
#!/bin/bash CP=./classes CP=$CP:./lib/jansi-1.9.jar CP=$CP:$PI4J_HOME/lib/pi4j-core.jar java -cp $CP adc.sample.FiveChannelListener
12nosanshiro-pi4j-sample
ADC/five.channels
Shell
mit
133
#!/bin/bash echo Monitoring the batteries on the boat, for real \(see coeffs\) # CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/jansi-1.9.jar # sudo java -client -agentlib:jdwp=transport=dt_socket,server=y,address=1044 -cp $CP adc.sample.BatteryMonitor $* sudo java -cp $CP adc.sample.BatteryMonitor -min=695:9.1 -max=973:12.6 $*
12nosanshiro-pi4j-sample
ADC/real.battery.monitor
Shell
mit
345
#!/bin/bash echo Read an ADC # CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP analogdigitalconverter.ADCReader
12nosanshiro-pi4j-sample
ADC/run
Shell
mit
124
"use strict"; var connection; (function () { // if user is running mozilla then use it's built-in WebSocket // window.WebSocket = window.WebSocket || window.MozWebSocket; // TODO otherwise, fall back var ws = window.WebSocket || window.MozWebSocket; // TODO otherwise, fall back // if browser doesn't support WebSocket, just show some notification and exit // if (!window.WebSocket) if (!ws) { displayMessage('Sorry, but your browser does not support WebSockets.'); // TODO Fallback return; } // open connection var rootUri = "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" + (document.location.port === "" ? "8080" : document.location.port); console.log(rootUri); connection = new WebSocket(rootUri); // 'ws://localhost:9876'); connection.onopen = function () { displayMessage('Connected.') }; connection.onerror = function (error) { // just in there were some problems with connection... displayMessage('Sorry, but there is some problem with your connection or the server is down.'); }; // most important part - incoming messages connection.onmessage = function (message) { // console.log('onmessage:' + message); // try to parse JSON message. try { var json = JSON.parse(message.data); } catch (e) { displayMessage('This doesn\'t look like a valid JSON: ' + message.data); return; } // NOTE: if you're not sure about the JSON structure // check the server source code above if (json.type === 'message') // TODO Get rid of the other types above { // it's a single message var value = parseInt(json.data.text); // console.log('Setting value to ' + value); displayValue.setValue(value); } else { displayMessage('Hmm..., I\'ve never seen JSON like this: ' + json); } }; /** * This method is optional. If the server wasn't able to respond to the * in 3 seconds then show some error message to notify the user that * something is wrong. */ setInterval(function() { if (connection.readyState !== 1) { displayMessage('Unable to communicate with the WebSocket server. Try again.'); } }, 3000); // Ping })(); var sendMessage = function(msg) { if (!msg) { return; } // send the message as an ordinary text connection.send(msg); }; var displayMessage = function(mess) { var messList = statusFld.innerHTML; messList = (((messList !== undefined && messList.length) > 0 ? messList + '<br>' : '') + mess); statusFld.innerHTML = messList; }; var resetStatus = function() { statusFld.innerHTML = ""; };
12nosanshiro-pi4j-sample
ADC/node/client.js
JavaScript
mit
2,723
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ADC / WebSockets</title> <script type="text/javascript" src="widgets/AnalogDisplay.js"></script> <style> * { font-family:tahoma; font-size:12px; padding:0px; margin:0px; } p { line-height:18px; } </style> <script type="text/javascript"> /** * Warning: there is a first HTTP HandShake going on, that must follow the orasocket.js protocol. * See the request header: * "tyrus-ws-attempt" = "Hand-Shake" * * Response headers will contain: * "tyrus-fallback-transports" * "tyrus-connection-id" * * FYI, tyrus is the name of the RI for JSR356. */ var response = {}; var displayValue; var statusFld; window.onload = function() { displayValue = new AnalogDisplay('valueCanvas', 100, 100, 10, 1, true, 40); statusFld = document.getElementById("status"); console.log("Sending first (POST) request..."); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { response = JSON.parse(xhr.responseText); console.log(response); var headers = xhr.getAllResponseHeaders(); console.log("All headers:\n" + headers); var supportedTransports = xhr.getResponseHeader("tyrus-fallback-transports"); console.log("Transports:" + supportedTransports); var transports = supportedTransports.split(","); var preferredProtocol = ""; for (var i=0; i<transports.length; i++) { console.log("Transport : " + transports[i] + " " + (transports[i] in window ? "": "NOT ") + "supported."); if (transports[i] in window) { preferredProtocol = transports[i]; break; } } if (preferredProtocol.length == 0) console.log("No protocol can be used..."); else console.log("Preferred Protocol is " + preferredProtocol); var clientID = xhr.getResponseHeader("tyrus-connection-id"); console.log("Client ID:" + clientID); } }; xhr.open("POST", "/", true); xhr.setRequestHeader("tyrus-ws-attempt", "Hand-Shake"); // Means return the transport list, and my unique ID xhr.send(); }; </script> </head> <body> <table width="100%"> <tr> <td valign="top"><h2>ADC on WebSocket</h2></td> </tr> <tr> <td align="left"> <div id="status" style="padding:5px; background:#ddd; border-radius:5px; overflow-y: scroll; border:1px solid #CCC; margin-top:10px; height: 80px;"> <!--i>Status will go here when needed...</i--> </div> </td> </tr> <tr> <td valign="top" align="right"><a href="" onclick="javascript:resetStatus(); return false;" title="Clear status board"><small>Reset Status</small></a></td> </tr> <tr> <td align="center" valign="top"> <canvas id="valueCanvas" width="240" height="220" title="Potentiometer value"></canvas> </td> </tr> </table> <hr> <script src="./client.js"></script> </body> </html>
12nosanshiro-pi4j-sample
ADC/node/display.html
HTML
mit
3,631
/* * @author Olivier Le Diouris */ // TODO This config in CSS // We wait for the var- custom properties to be implemented in CSS... // @see http://www.w3.org/TR/css-variables-1/ /* * For now: * Themes are applied based on a css class: * .display-scheme * { * color: black; * } * * if color is black, analogDisplayColorConfigBlack is applied * if color is white, analogDisplayColorConfigWhite is applied, etc */ var analogDisplayColorConfigWhite = { bgColor: 'white', digitColor: 'black', withGradient: true, displayBackgroundGradient: { from: 'LightGrey', to: 'white' }, withDisplayShadow: true, shadowColor: 'rgba(0, 0, 0, 0.75)', outlineColor: 'DarkGrey', majorTickColor: 'black', minorTickColor: 'black', valueColor: 'grey', valueOutlineColor: 'black', valueNbDecimal: 0, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'black', withHandShadow: true, knobColor: 'DarkGrey', knobOutlineColor: 'black', font: 'Arial' /* 'Source Code Pro' */ }; var analogDisplayColorConfigBlack = { bgColor: 'black', digitColor: 'LightBlue', withGradient: true, displayBackgroundGradient: { from: 'black', to: 'LightGrey' }, shadowColor: 'black', outlineColor: 'DarkGrey', majorTickColor: 'LightGreen', minorTickColor: 'LightGreen', valueColor: 'LightGreen', valueOutlineColor: 'black', valueNbDecimal: 1, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'blue', withHandShadow: true, knobColor: '#8ED6FF', // Kind of blue knobOutlineColor: 'blue', font: 'Arial' }; var analogDisplayColorConfig = analogDisplayColorConfigWhite; // White is the default function AnalogDisplay(cName, // Canvas Name dSize, // Display radius maxValue, // default 10 majorTicks, // default 1 minorTicks, // default 0 withDigits, // default true, boolean overlapOver180InDegree, // default 0, beyond horizontal, in degrees, before 0, after 180 startValue) // default 0, In case it is not 0 { if (maxValue === undefined) maxValue = 10; if (majorTicks === undefined) majorTicks = 1; if (minorTicks === undefined) minorTicks = 0; if (withDigits === undefined) withDigits = true; if (overlapOver180InDegree === undefined) overlapOver180InDegree = 0; if (startValue === undefined) startValue = 0; var scale = dSize / 100; var canvasName = cName; var displaySize = dSize; var running = false; var previousValue = startValue; var intervalID; var valueToDisplay = 0; var incr = 1; var instance = this; //try { console.log('in the AnalogDisplay constructor for ' + cName + " (" + dSize + ")"); } catch (e) {} (function(){ drawDisplay(canvasName, displaySize, previousValue); })(); // Invoked automatically this.repaint = function() { drawDisplay(canvasName, displaySize, previousValue); }; this.setDisplaySize = function(ds) { scale = ds / 100; displaySize = ds; drawDisplay(canvasName, displaySize, previousValue); }; this.startStop = function (buttonName) { // console.log('StartStop requested on ' + buttonName); var button = document.getElementById(buttonName); running = !running; button.value = (running ? "Stop" : "Start"); if (running) this.animate(); else { window.clearInterval(intervalID); previousValue = valueToDisplay; } }; this.animate = function() { var value; if (arguments.length === 1) value = arguments[0]; else { // console.log("Generating random value"); value = maxValue * Math.random(); } value = Math.max(value, startValue); value = Math.min(value, maxValue); //console.log("Reaching Value :" + value + " from " + previousValue); diff = value - previousValue; valueToDisplay = previousValue; // console.log(canvasName + " going from " + previousValue + " to " + value); // if (diff > 0) // incr = 0.01 * maxValue; // else // incr = -0.01 * maxValue; incr = diff / 10; if (intervalID) window.clearInterval(intervalID); intervalID = window.setInterval(function () { displayAndIncrement(value); }, 10); }; var displayAndIncrement = function(finalValue) { //console.log('Tic ' + inc + ', ' + finalValue); drawDisplay(canvasName, displaySize, valueToDisplay); valueToDisplay += incr; if ((incr > 0 && valueToDisplay > finalValue) || (incr < 0 && valueToDisplay < finalValue)) { // console.log('Stop, ' + finalValue + ' reached, steps were ' + incr); window.clearInterval(intervalID); previousValue = finalValue; if (running) instance.animate(); else drawDisplay(canvasName, displaySize, finalValue); // Final display } }; function drawDisplay(displayCanvasName, displayRadius, displayValue) { var schemeColor; try { schemeColor = getCSSClass(".display-scheme"); } catch (err) { /* not there */ } if (schemeColor !== undefined && schemeColor !== null) { var styleElements = schemeColor.split(";"); for (var i=0; i<styleElements.length; i++) { var nv = styleElements[i].split(":"); if ("color" === nv[0]) { // console.log("Scheme Color:[" + nv[1].trim() + "]"); if (nv[1].trim() === 'black') analogDisplayColorConfig = analogDisplayColorConfigBlack; else if (nv[1].trim() === 'white') analogDisplayColorConfig = analogDisplayColorConfigWhite; } } } var digitColor = analogDisplayColorConfig.digitColor; var canvas = document.getElementById(displayCanvasName); var context = canvas.getContext('2d'); var radius = displayRadius; // Cleanup //context.fillStyle = "#ffffff"; context.fillStyle = analogDisplayColorConfig.bgColor; //context.fillStyle = "transparent"; context.fillRect(0, 0, canvas.width, canvas.height); //context.fillStyle = 'rgba(255, 255, 255, 0.0)'; //context.fillRect(0, 0, canvas.width, canvas.height); context.beginPath(); //context.arc(x, y, radius, startAngle, startAngle + Math.PI, antiClockwise); // context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree), (2 * Math.PI) + toRadians(overlapOver180InDegree), false); context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree > 0?90:0), (2 * Math.PI) + toRadians(overlapOver180InDegree > 0?90:0), false); context.lineWidth = 5; if (analogDisplayColorConfig.withGradient) { var grd = context.createLinearGradient(0, 5, 0, radius); grd.addColorStop(0, analogDisplayColorConfig.displayBackgroundGradient.from);// 0 Beginning grd.addColorStop(1, analogDisplayColorConfig.displayBackgroundGradient.to); // 1 End context.fillStyle = grd; } else context.fillStyle = analogDisplayColorConfig.displayBackgroundGradient.to; if (analogDisplayColorConfig.withDisplayShadow) { context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; context.shadowColor = analogDisplayColorConfig.shadowColor; } context.lineJoin = "round"; context.fill(); context.strokeStyle = analogDisplayColorConfig.outlineColor; context.stroke(); context.closePath(); var totalAngle = (Math.PI + (2 * (toRadians(overlapOver180InDegree)))); // Major Ticks context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { var currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.85) * Math.cos(currentAngle)); yTo = (radius + 10) - ((radius * 0.85) * Math.sin(currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 3; context.strokeStyle = analogDisplayColorConfig.majorTickColor; context.stroke(); context.closePath(); // Minor Ticks if (minorTicks > 0) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=minorTicks) { var _currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(_currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(_currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.90) * Math.cos(_currentAngle)); yTo = (radius + 10) - ((radius * 0.90) * Math.sin(_currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.minorTickColor; context.stroke(); context.closePath(); } // Numbers if (withDigits) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { context.save(); context.translate(canvas.width/2, (radius + 10)); // canvas.height); var __currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // context.rotate((Math.PI * (i / maxValue)) - (Math.PI / 2)); context.rotate(__currentAngle - (Math.PI / 2)); context.font = "bold " + Math.round(scale * 15) + "px " + analogDisplayColorConfig.font; // Like "bold 15px Arial" context.fillStyle = digitColor; str = (i + startValue).toString(); len = context.measureText(str).width; context.fillText(str, - len / 2, (-(radius * .8) + 10)); context.restore(); } context.closePath(); } // Value text = displayValue.toFixed(analogDisplayColorConfig.valueNbDecimal); len = 0; context.font = "bold " + Math.round(scale * 40) + "px " + analogDisplayColorConfig.font; // "bold 40px Arial" var metrics = context.measureText(text); len = metrics.width; context.beginPath(); context.fillStyle = analogDisplayColorConfig.valueColor; context.fillText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.valueOutlineColor; context.strokeText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); // Outlined context.closePath(); // Hand context.beginPath(); if (analogDisplayColorConfig.withHandShadow) { context.shadowColor = analogDisplayColorConfig.shadowColor; context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; } // Center context.moveTo(canvas.width / 2, radius + 10); var ___currentAngle = (totalAngle * ((displayValue - startValue) / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // Left x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle - (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle - (Math.PI / 2)))); context.lineTo(x, y); // Tip x = (canvas.width / 2) - ((radius * 0.90) * Math.cos(___currentAngle)); y = (radius + 10) - ((radius * 0.90) * Math.sin(___currentAngle)); context.lineTo(x, y); // Right x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle + (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle + (Math.PI / 2)))); context.lineTo(x, y); context.closePath(); context.fillStyle = analogDisplayColorConfig.handColor; context.fill(); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.handOutlineColor; context.stroke(); // Knob context.beginPath(); context.arc((canvas.width / 2), (radius + 10), 7, 0, 2 * Math.PI, false); context.closePath(); context.fillStyle = analogDisplayColorConfig.knobColor; context.fill(); context.strokeStyle = analogDisplayColorConfig.knobOutlineColor; context.stroke(); }; this.setValue = function(val) { drawDisplay(canvasName, displaySize, val); }; function toDegrees(rad) { return rad * (180 / Math.PI); } function toRadians(deg) { return deg * (Math.PI / 180); } }
12nosanshiro-pi4j-sample
ADC/node/widgets/AnalogDisplay.js
JavaScript
mit
12,851
// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ "use strict"; /** * Warning: there is a first HTTP HandShake going on, that must follow the orasocket.js protocol. * See the request header: * "tyrus-ws-attempt" = "Hand-Shake" * * Response headers will contain: * "tyrus-fallback-transports" * "tyrus-connection-id" * * FYI, tyrus is the name of the RI for JSR356. * * Static requests must be prefixed with /data/, like in http://machine:9876/data/chat.html */ // Optional. You will see this name in eg. 'ps' or 'top' command process.title = 'node-chat'; // Port where we'll run the websocket server var port = 9876; // websocket and http servers var webSocketServer = require('websocket').server; var http = require('http'); var fs = require('fs'); var verbose = false; if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str) { return this.indexOf(str) == 0; }; } if (typeof String.prototype.endsWith != 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } function handler (req, res) { var respContent = ""; if (verbose) { console.log("Speaking HTTP from " + __dirname); console.log("Server received an HTTP Request:\n" + req.method + "\n" + req.url + "\n-------------"); console.log("ReqHeaders:" + JSON.stringify(req.headers, null, '\t')); console.log('Request:' + req.url); var prms = require('url').parse(req.url, true); console.log(prms); console.log("Search: [" + prms.search + "]"); console.log("-------------------------------"); } if (req.url.startsWith("/data/")) // Static resource { var resource = req.url.substring("/data/".length); console.log('Loading static ' + req.url + " (" + resource + ")"); fs.readFile(__dirname + '/' + resource, function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading ' + resource); } if (verbose) console.log("Read resource content:\n---------------\n" + data + "\n--------------"); var contentType = "text/html"; if (resource.endsWith(".css")) contentType = "text/css"; else if (resource.endsWith(".html")) contentType = "text/html"; else if (resource.endsWith(".xml")) contentType = "text/xml"; else if (resource.endsWith(".js")) contentType = "text/javascript"; else if (resource.endsWith(".jpg")) contentType = "image/jpg"; else if (resource.endsWith(".gif")) contentType = "image/gif"; else if (resource.endsWith(".png")) contentType = "image/png"; res.writeHead(200, {'Content-Type': contentType}); // console.log('Data is ' + typeof(data)); if (resource.endsWith(".jpg") || resource.endsWith(".gif") || resource.endsWith(".png")) { // res.writeHead(200, {'Content-Type': 'image/gif' }); res.end(data, 'binary'); } else res.end(data.toString().replace('$PORT$', port.toString())); // Replace $PORT$ with the actual port value. }); } else if (req.url == "/") { if (req.method === "POST") { var data = ""; console.log("---- Headers ----"); for(var item in req.headers) console.log(item + ": " + req.headers[item]); console.log("-----------------"); req.on("data", function(chunk) { data += chunk; }); req.on("end", function() { console.log("POST request: [" + data + "]"); if (req.headers["tyrus-ws-attempt"] !== "undefined" && req.headers["tyrus-ws-attempt"] === "Hand-Shake") // List of the supoprted protocols { console.log(" ... writing headers..."); res.writeHead(200, {'Content-Type': 'application/json', 'tyrus-fallback-transports': 'WebSocket,MozWebSocket,XMLHttpRequest,FedEx,UPS', 'tyrus-connection-id': guid() }); } else res.writeHead(200, {'Content-Type': 'application/json'}); var status = {'status':'OK'}; res.end(JSON.stringify(status)); }); } } else { console.log("Unmanaged request: [" + req.url + "]"); respContent = "Response from " + req.url; res.writeHead(404, {'Content-Type': 'text/plain'}); res.end(); // respContent); } } // HTTP Handler /** * Global variables */ // list of currently connected clients (users) var clients = [ ]; /** * Helper function for escaping input strings */ function htmlEntities(str) { return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;') .replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } /** * HTTP server */ var server = http.createServer(handler); server.listen(port, function() { console.log((new Date()) + " Server is listening on port " + port); }); /** * WebSocket server */ var wsServer = new webSocketServer({ // WebSocket server is tied to a HTTP server. WebSocket request is just // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6 httpServer: server }); // This callback function is called every time someone // tries to connect to the WebSocket server wsServer.on('request', function(request) { console.log((new Date()) + ' Connection from origin ' + request.origin + '.'); // accept connection - you should check 'request.origin' to make sure that // client is connecting from your website // (http://en.wikipedia.org/wiki/Same_origin_policy) var connection = request.accept(null, request.origin); clients.push(connection); console.log((new Date()) + ' Connection accepted.'); // user sent some message connection.on('message', function(message) { if (message.type === 'utf8') { // accept only text console.log((new Date()) + ' Received Message: ' + message.utf8Data); var obj = { time: (new Date()).getTime(), text: htmlEntities(message.utf8Data) }; // broadcast message to all connected clients. That's what this app is doing. var json = JSON.stringify({ type:'message', data: obj }); for (var i=0; i < clients.length; i++) { clients[i].sendUTF(json); } } }); // user disconnected connection.on('close', function(connection) { // Close }); }); function s4() { return (Math.floor((1 + Math.random()) * 0x10000) & 0xffff) .toString(16); // .substring(1); }; function guid() { return s4() + "." + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + "." + s4() + "." + s4(); }
12nosanshiro-pi4j-sample
ADC/node/server.js
JavaScript
mit
7,263
#!/bin/bash echo Read an ADC # CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adc.gui.AnalogDisplayApp
12nosanshiro-pi4j-sample
ADC/run.gui
Shell
mit
116
package adc.gui; import adc.ADCObserver; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class AnalogDisplayApp { private ADCObserver.MCP3008_input_channels channel = null; private final ADCObserver obs; public AnalogDisplayApp(int ch) { channel = findChannel(ch); obs = new ADCObserver(channel); // Note: We could instantiate more than one observer (on several channels). JFrame frame = new AnalogDisplayFrame(channel, this); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } frame.setLocation( ( screenSize.width - frameSize.width ) / 2, ( screenSize.height - frameSize.height ) / 2 ); // frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { close(); System.exit(0); } }); frame.setVisible(true); if (true) // For Dev... { try { obs.start(); } catch (Exception ioe) { System.err.println("Oops"); ioe.printStackTrace(); } } } public static void main(String[] args) { try { if (System.getProperty("swing.defaultlaf") == null) UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } int channel = 0; if (args.length > 0) channel = Integer.parseInt(args[0]); new AnalogDisplayApp(channel); // swingWait(1L); } public void close() { System.out.println("Exiting."); if (obs != null) obs.stop(); } private static ADCObserver.MCP3008_input_channels findChannel(int ch) throws IllegalArgumentException { ADCObserver.MCP3008_input_channels channel = null; switch (ch) { case 0: channel = ADCObserver.MCP3008_input_channels.CH0; break; case 1: channel = ADCObserver.MCP3008_input_channels.CH1; break; case 2: channel = ADCObserver.MCP3008_input_channels.CH2; break; case 3: channel = ADCObserver.MCP3008_input_channels.CH3; break; case 4: channel = ADCObserver.MCP3008_input_channels.CH4; break; case 5: channel = ADCObserver.MCP3008_input_channels.CH5; break; case 6: channel = ADCObserver.MCP3008_input_channels.CH6; break; case 7: channel = ADCObserver.MCP3008_input_channels.CH7; break; default: throw new IllegalArgumentException("No channel " + Integer.toString(ch)); } return channel; } private static void swingWait(final long w) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { try { Thread.sleep(w); } catch (Exception ex) {} } }); } catch (Exception ex) { ex.printStackTrace(); } } }
12nosanshiro-pi4j-sample
ADC/src/adc/gui/AnalogDisplayApp.java
Java
mit
3,376
package adc.gui; import adc.ADCObserver; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class AnalogDisplayFrame extends JFrame { private JMenuBar menuBar = new JMenuBar(); private JMenu menuFile = new JMenu(); private JMenuItem menuFileExit = new JMenuItem(); private AnalogDisplayPanel displayPanel = null; private transient AnalogDisplayApp caller; public AnalogDisplayFrame(ADCObserver.MCP3008_input_channels channel, AnalogDisplayApp parent) { this.caller = parent; displayPanel = new AnalogDisplayPanel(channel, 100); try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setJMenuBar(menuBar); this.getContentPane().setLayout(new BorderLayout()); this.setSize(new Dimension(400, 275)); this.setTitle("Volume"); menuFile.setText("File"); menuFileExit.setText("Exit"); menuFileExit.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { fileExit_ActionPerformed( ae ); } } ); menuFile.add( menuFileExit ); menuBar.add( menuFile ); this.getContentPane().add(displayPanel, BorderLayout.CENTER); } void fileExit_ActionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); this.caller.close(); System.exit(0); } }
12nosanshiro-pi4j-sample
ADC/src/adc/gui/AnalogDisplayFrame.java
Java
mit
1,572
package adc; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * Read an Analog to Digital Converter */ public class ADCObserver { private final static boolean DISPLAY_DIGIT = false; // Note: "Mismatch" 23-24. The wiring says DOUT->#23, DIN->#24 // 23: DOUT on the ADC is IN on the GPIO. ADC:Slave, GPIO:Master // 24: DIN on the ADC, OUT on the GPIO. Same reason as above. // SPI: Serial Peripheral Interface private static Pin spiClk = RaspiPin.GPIO_01; // Pin #18, clock private static Pin spiMiso = RaspiPin.GPIO_04; // Pin #23, data in. MISO: Master In Slave Out private static Pin spiMosi = RaspiPin.GPIO_05; // Pin #24, data out. MOSI: Master Out Slave In private static Pin spiCs = RaspiPin.GPIO_06; // Pin #25, Chip Select public static enum MCP3008_input_channels { CH0(0), CH1(1), CH2(2), CH3(3), CH4(4), CH5(5), CH6(6), CH7(7); private int ch; MCP3008_input_channels(int chNum) { this.ch = chNum; } public int ch() { return this.ch; } } private MCP3008_input_channels[] adcChannel; // Between 0 and 7, 8 channels on the MCP3008 private static GpioPinDigitalInput misoInput = null; private static GpioPinDigitalOutput mosiOutput = null; private static GpioPinDigitalOutput clockOutput = null; private static GpioPinDigitalOutput chipSelectOutput = null; private boolean go = true; public ADCObserver(MCP3008_input_channels channel) { this(new MCP3008_input_channels[] { channel }) ; } public ADCObserver(MCP3008_input_channels[] channel) { adcChannel = channel; } public void start() { GpioController gpio = GpioFactory.getInstance(); mosiOutput = gpio.provisionDigitalOutputPin(spiMosi, "MOSI", PinState.LOW); clockOutput = gpio.provisionDigitalOutputPin(spiClk, "CLK", PinState.LOW); chipSelectOutput = gpio.provisionDigitalOutputPin(spiCs, "CS", PinState.LOW); misoInput = gpio.provisionDigitalInputPin(spiMiso, "MISO"); int lastRead[] = new int[adcChannel.length]; for (int i=0; i<lastRead.length; i++) lastRead[i] = 0; int tolerance = 5; while (go) { for (int i=0; i<adcChannel.length; i++) { int adc = readAdc(adcChannel[i]); // System.out.println("ADC:" + adc); int postAdjust = Math.abs(adc - lastRead[i]); if (postAdjust > tolerance) { ADCContext.getInstance().fireValueChanged(adcChannel[i], adc); lastRead[i] = adc; } } try { Thread.sleep(100L); } catch (InterruptedException ie) { ie.printStackTrace(); } } System.out.println("Shutting down..."); gpio.shutdown(); } public void stop() { go = false; } private int readAdc(MCP3008_input_channels channel) { chipSelectOutput.high(); clockOutput.low(); chipSelectOutput.low(); int adccommand = channel.ch(); adccommand |= 0x18; // 0x18: 00011000 adccommand <<= 3; // Send 5 bits: 8 - 3. 8 input channels on the MCP3008. for (int i=0; i<5; i++) // { if ((adccommand & 0x80) != 0x0) // 0x80 = 0&10000000 mosiOutput.high(); else mosiOutput.low(); adccommand <<= 1; clockOutput.high(); clockOutput.low(); } int adcOut = 0; for (int i=0; i<12; i++) // Read in one empty bit, one null bit and 10 ADC bits { clockOutput.high(); clockOutput.low(); adcOut <<= 1; if (misoInput.isHigh()) { // System.out.println(" " + misoInput.getName() + " is high (i:" + i + ")"); // Shift one bit on the adcOut adcOut |= 0x1; } if (DISPLAY_DIGIT) System.out.println("ADCOUT: 0x" + Integer.toString(adcOut, 16).toUpperCase() + ", 0&" + Integer.toString(adcOut, 2).toUpperCase()); } chipSelectOutput.high(); adcOut >>= 1; // Drop first bit return adcOut; } }
12nosanshiro-pi4j-sample
ADC/src/adc/ADCObserver.java
Java
mit
4,263
package adc; import java.util.ArrayList; import java.util.List; public class ADCContext { private static ADCContext instance = null; private List<ADCListener> listeners = null; private ADCContext() { listeners = new ArrayList<ADCListener>(); } public synchronized static ADCContext getInstance() { if (instance == null) instance = new ADCContext(); return instance; } public void addListener(ADCListener listener) { if (!listeners.contains(listener)) listeners.add(listener); } public void removeListener(ADCListener listener) { if (listeners.contains(listener)) listeners.remove(listener); } public List<ADCListener> getListeners() { return this.listeners; } public void fireValueChanged(ADCObserver.MCP3008_input_channels channel, int newValue) { for (ADCListener listener : listeners) listener.valueUpdated(channel, newValue); } }
12nosanshiro-pi4j-sample
ADC/src/adc/ADCContext.java
Java
mit
946
package adc; public class ADCListener { public void valueUpdated(ADCObserver.MCP3008_input_channels channel, int newValue) {}; }
12nosanshiro-pi4j-sample
ADC/src/adc/ADCListener.java
Java
mit
132
package adc.sample; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; import adc.utils.EscapeSeq; import org.fusesource.jansi.AnsiConsole; public class SampleMain { private final static boolean DEBUG = false; private final static String STR100 = " "; private final static int DIGITAL_OPTION = 0; private final static int ANALOG_OPTION = 1; private static int displayOption = ANALOG_OPTION; final String[] channelColors = new String[] { EscapeSeq.ANSI_RED, EscapeSeq.ANSI_BLUE, EscapeSeq.ANSI_YELLOW, EscapeSeq.ANSI_GREEN, EscapeSeq.ANSI_WHITE }; private ADCObserver.MCP3008_input_channels channel = null; public SampleMain(int ch) throws Exception { channel = findChannel(ch); final ADCObserver obs = new ADCObserver(channel); // Note: We could instantiate more than one observer (on several channels). ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { if (inputChannel.equals(channel)) { int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (DEBUG) System.out.println("readAdc:" + Integer.toString(newValue) + " (0x" + lpad(Integer.toString(newValue, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(newValue, 2), "0", 8) + ")"); if (displayOption == DIGITAL_OPTION) System.out.println("Volume:" + volume + "% (" + newValue + ")"); else if (displayOption == ANALOG_OPTION) { String str = ""; for (int i=0; i<volume; i++) str += "."; try { str = EscapeSeq.superpose(str, "Ch " + Integer.toString(inputChannel.ch()) + ": " + Integer.toString(volume) + "%"); AnsiConsole.out.println(EscapeSeq.ansiLocate(1, 1) + EscapeSeq.ANSI_NORMAL + EscapeSeq.ANSI_DEFAULT_BACKGROUND + EscapeSeq.ANSI_DEFAULT_TEXT + STR100); AnsiConsole.out.println(EscapeSeq.ansiLocate(1, 1) + EscapeSeq.ansiSetTextAndBackgroundColor(EscapeSeq.ANSI_WHITE, channelColors[inputChannel.ch()]) + EscapeSeq.ANSI_BOLD + str + EscapeSeq.ANSI_NORMAL + EscapeSeq.ANSI_DEFAULT_BACKGROUND + EscapeSeq.ANSI_DEFAULT_TEXT); } catch (Exception ex) { System.out.println(str); } } } } }); obs.start(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (obs != null) obs.stop(); } }); } public static void main(String[] args) throws Exception { if (displayOption == ANALOG_OPTION) { AnsiConsole.systemInstall(); AnsiConsole.out.println(EscapeSeq.ANSI_CLS); } int channel = 0; if (args.length > 0) channel = Integer.parseInt(args[0]); new SampleMain(channel); } private static ADCObserver.MCP3008_input_channels findChannel(int ch) throws IllegalArgumentException { ADCObserver.MCP3008_input_channels channel = null; switch (ch) { case 0: channel = ADCObserver.MCP3008_input_channels.CH0; break; case 1: channel = ADCObserver.MCP3008_input_channels.CH1; break; case 2: channel = ADCObserver.MCP3008_input_channels.CH2; break; case 3: channel = ADCObserver.MCP3008_input_channels.CH3; break; case 4: channel = ADCObserver.MCP3008_input_channels.CH4; break; case 5: channel = ADCObserver.MCP3008_input_channels.CH5; break; case 6: channel = ADCObserver.MCP3008_input_channels.CH6; break; case 7: channel = ADCObserver.MCP3008_input_channels.CH7; break; default: throw new IllegalArgumentException("No channel " + Integer.toString(ch)); } return channel; } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
12nosanshiro-pi4j-sample
ADC/src/adc/sample/SampleMain.java
Java
mit
4,485
package adc.sample; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; import java.io.FileOutputStream; import oracle.generic.ws.client.ClientFacade; import oracle.generic.ws.client.ServerListenerAdapter; import oracle.generic.ws.client.ServerListenerInterface; public class WebSocketFeeder { private final static boolean DEBUG = false; private ADCObserver.MCP3008_input_channels channel = null; private boolean keepWorking = true; private ClientFacade webSocketClient = null; public WebSocketFeeder(int ch) throws Exception { channel = findChannel(ch); String wsUri = System.getProperty("ws.uri", "ws://localhost:9876/"); initWebSocketConnection(wsUri); final ADCObserver obs = new ADCObserver(channel); // Note: We could instantiate more than one observer (on several channels). ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { if (inputChannel.equals(channel)) { int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (DEBUG) System.out.println("readAdc:" + Integer.toString(newValue) + " (0x" + lpad(Integer.toString(newValue, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(newValue, 2), "0", 8) + ")"); System.out.println("Volume:" + volume + "% (" + newValue + ")"); webSocketClient.send(Integer.toString(volume)); } } }); obs.start(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (obs != null) obs.stop(); keepWorking = false; webSocketClient.bye(); } }); } private void initWebSocketConnection(String serverURI) { String[] targetedTransports = new String[] {"WebSocket", "XMLHttpRequest"}; ServerListenerInterface serverListener = new ServerListenerAdapter() { @Override public void onMessage(String mess) { // System.out.println(" . Text message :[" + mess + "]"); // JSONObject json = new JSONObject(mess); // System.out.println(" . Mess content:[" + ((JSONObject)json.get("data")).get("text") + "]"); } @Override public void onMessage(byte[] bb) { System.out.println(" . Message for you (ByteBuffer) ..."); System.out.println("Length:" + bb.length); try { FileOutputStream fos = new FileOutputStream("binary.xxx"); for (int i=0; i<bb.length; i++) fos.write(bb[i]); fos.close(); System.out.println("... was written in binary.xxx"); } catch (Exception ex) { ex.printStackTrace(); } } @Override public void onConnect() { System.out.println(" .You're in!"); keepWorking = true; } @Override public void onClose() { System.out.println(" .Connection has been closed..."); keepWorking = false; } @Override public void onError(String error) { System.out.println(" .Oops! error [" + error + "]"); keepWorking = false; // Careful with that one..., in case of a fallback, use the value returned by the init method. } @Override public void setStatus(String status) { System.out.println(" .Your status is now [" + status + "]"); } @Override public void onPong(String s) { if (DEBUG) System.out.println("WS Pong"); } @Override public void onPing(String s) { if (DEBUG) System.out.println("WS Ping"); } @Override public void onHandShakeSentAsClient() { System.out.println("WS-HS sent as client"); } @Override public void onHandShakeReceivedAsServer() { if (DEBUG) System.out.println("WS-HS received as server"); } @Override public void onHandShakeReceivedAsClient() { if (DEBUG) System.out.println("WS-HS received as client"); } }; try { webSocketClient = new ClientFacade(serverURI, targetedTransports, serverListener); keepWorking = webSocketClient.init(); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) throws Exception { int channel = 0; if (args.length > 0) channel = Integer.parseInt(args[0]); new WebSocketFeeder(channel); } private static ADCObserver.MCP3008_input_channels findChannel(int ch) throws IllegalArgumentException { ADCObserver.MCP3008_input_channels channel = null; switch (ch) { case 0: channel = ADCObserver.MCP3008_input_channels.CH0; break; case 1: channel = ADCObserver.MCP3008_input_channels.CH1; break; case 2: channel = ADCObserver.MCP3008_input_channels.CH2; break; case 3: channel = ADCObserver.MCP3008_input_channels.CH3; break; case 4: channel = ADCObserver.MCP3008_input_channels.CH4; break; case 5: channel = ADCObserver.MCP3008_input_channels.CH5; break; case 6: channel = ADCObserver.MCP3008_input_channels.CH6; break; case 7: channel = ADCObserver.MCP3008_input_channels.CH7; break; default: throw new IllegalArgumentException("No channel " + Integer.toString(ch)); } return channel; } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
12nosanshiro-pi4j-sample
ADC/src/adc/sample/WebSocketFeeder.java
Java
mit
6,190
package adc.sample; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; import java.io.BufferedWriter; import java.io.FileWriter; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.TimeZone; public class BatteryMonitor { private static boolean debug = false; private static boolean calib = false; private ADCObserver.MCP3008_input_channels channel = null; private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private final static TimeZone HERE = TimeZone.getTimeZone("America/Los_Angeles"); static { SDF.setTimeZone(HERE); } private final static NumberFormat VF = new DecimalFormat("00.00"); private static BufferedWriter bw = null; private static ADCObserver obs; private long lastLogTimeStamp = 0; private int lastVolumeLogged = 0; private static String logFileName = "battery.log"; public BatteryMonitor(int ch) throws Exception { channel = findChannel(ch); if (tuning) { minADC = 0; minVolt = 0f; maxADC = tuningADC; maxVolt = tuningVolt; } final int deltaADC = maxADC - minADC; final float deltaVolt = maxVolt - minVolt; final float b = ((maxVolt * minADC) - (minVolt * maxADC)) / deltaADC; final float a = (maxVolt - b) / maxADC; if (debug) { System.out.println("Volt [" + minVolt + ", " + maxVolt + "]"); System.out.println("ADC [" + minADC + ", " + maxADC + "]"); System.out.println("a=" + a+ ", b=" + b); } System.out.println("Value range: ADC=0 => V=" + b + ", ADC=1023 => V=" + ((a * 1023) + b)); obs = new ADCObserver(channel); // Note: We could instantiate more than one observer (on several channels). bw = new BufferedWriter(new FileWriter(logFileName)); ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { if (inputChannel.equals(channel)) { long now = System.currentTimeMillis(); if (calib || Math.abs(now - lastLogTimeStamp) > 1000) { int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (Math.abs(volume - lastVolumeLogged) > 1) // 1 % { float voltage = 0; if (false) { if (newValue < minADC) { voltage = /* 0 + */ minVolt * ((float)newValue / (float)minADC); } else if (newValue >= minADC && newValue <= maxADC) { voltage = minVolt + (deltaVolt * (float)(newValue - minADC) / (float)deltaADC); } else // value > maxADC { voltage = maxVolt + ((15 - maxVolt) * (float)(newValue - maxADC) / (float)(1023 - maxADC)); } } else { voltage = (a * newValue) + b; } if (debug) { System.out.print("readAdc:" + Integer.toString(newValue) + " (0x" + lpad(Integer.toString(newValue, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(newValue, 2), "0", 8) + ") "); System.out.println("Volume:" + volume + "% (" + newValue + ") Volt:" + VF.format(voltage)); } // Log the voltage, along with the date and ADC val. String line = SDF.format(GregorianCalendar.getInstance(HERE).getTime()) + ";" + newValue + ";" + volume + ";" + VF.format(voltage); // System.out.println(line); try { bw.write(line + "\n"); bw.flush(); } catch (Exception ex) { ex.printStackTrace(); } lastLogTimeStamp = now; lastVolumeLogged = volume; } } } } }); obs.start(); } private final static String DEBUG_PRM = "-debug="; private final static String CALIBRATION_PRM = "-calibration"; private final static String CAL_PRM = "-cal"; private final static String CHANNEL_PRM = "-ch="; private final static String MIN_VALUE = "-min="; private final static String MAX_VALUE = "-max="; private final static String TUNE_VALUE = "-tune="; private final static String SCALE_PRM = "-scale="; private final static String LOG_PRM = "-log="; private static int minADC = 0; private static int maxADC = 1023; private static float minVolt = 0f; private static float maxVolt = 15f; private static float tuningVolt = 15f; private static int tuningADC = 1023; private static boolean scale = false; private static boolean tuning = false; public static void main(String[] args) throws Exception { System.out.println("Parameters are:"); System.out.println(" -calibration or -cal"); System.out.println(" -debug=y|n|yes|no|true|false - example -debug=y (default is n)"); System.out.println(" -ch=[0-7] - example -ch=0 (default is 0)"); System.out.println(" -min=minADC:minVolt - example -min=280:3.75 (default is 0:0.0)"); System.out.println(" -max=maxADC:maxVolt - example -min=879:11.25 (default is 1023:15.0)"); System.out.println(" -tune=ADC:volt - example -tune=973:12.6 (default is 1023:15.0)"); System.out.println(" -scale=y|n - example -scale=y (default is n)"); System.out.println(" -log=[log-file-name] - example -log=[batt.csv] (default is battery.log)"); System.out.println(""); System.out.println(" -min & -max are required if -tune is not here, and vice versa."); int channel = 0; for (String prm : args) { if (prm.startsWith(CHANNEL_PRM)) channel = Integer.parseInt(prm.substring(CHANNEL_PRM.length())); else if (prm.startsWith(CALIBRATION_PRM) || prm.startsWith(CAL_PRM)) { debug = true; calib = true; } else if (!debug && prm.startsWith(DEBUG_PRM)) debug = ("y".equals(prm.substring(DEBUG_PRM.length())) || "yes".equals(prm.substring(DEBUG_PRM.length())) || "true".equals(prm.substring(DEBUG_PRM.length()))); else if (prm.startsWith(SCALE_PRM)) scale = ("y".equals(prm.substring(SCALE_PRM.length()))); else if (prm.startsWith(LOG_PRM)) logFileName = prm.substring(LOG_PRM.length()); else if (prm.startsWith(TUNE_VALUE)) { tuning = true; String val = prm.substring(TUNE_VALUE.length()); tuningADC = Integer.parseInt(val.substring(0, val.indexOf(":"))); tuningVolt = Float.parseFloat(val.substring(val.indexOf(":") + 1)); } else if (prm.startsWith(MIN_VALUE)) { String val = prm.substring(MIN_VALUE.length()); minADC = Integer.parseInt(val.substring(0, val.indexOf(":"))); minVolt = Float.parseFloat(val.substring(val.indexOf(":") + 1)); } else if (prm.startsWith(MAX_VALUE)) { String val = prm.substring(MAX_VALUE.length()); maxADC = Integer.parseInt(val.substring(0, val.indexOf(":"))); maxVolt = Float.parseFloat(val.substring(val.indexOf(":") + 1)); } } String prms = "Prms: ADC Channel:" + channel; if (tuning) prms += ", tuningADC:" + tuningADC + ", tuningVolt:" + tuningVolt; else prms += ", MinADC:" + minADC + ", MinVolt:" + minVolt + ", MaxADC:" + maxADC + ", maxVolt:" + maxVolt; System.out.println(prms); if (scale) { if (tuning) { minADC = 0; minVolt = 0f; maxADC = tuningADC; maxVolt = tuningVolt; } final int deltaADC = maxADC - minADC; final float deltaVolt = maxVolt - minVolt; float b = ((maxVolt * minADC) - (minVolt * maxADC)) / deltaADC; float a = (maxVolt - b) / maxADC; // System.out.println("a=" + a + "(" + ((maxVolt - b) / maxADC) + "), b=" + b); System.out.println("=== Scale ==="); System.out.println("Value range: ADC:0 => V:" + b + ", ADC:1023 => V:" + ((a * 1023) + b)); System.out.println("Coeff A:" + a + ", coeff B:" + b); for (int i=0; i<1024; i++) System.out.println(i + ";" + ((a * i) + b)); System.out.println("============="); System.exit(0); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("\nShutting down"); if (bw != null) { System.out.println("Closing log file"); try { bw.flush(); bw.close(); } catch (Exception ex) { ex.printStackTrace(); } } if (obs != null) obs.stop(); } }); new BatteryMonitor(channel); } private static ADCObserver.MCP3008_input_channels findChannel(int ch) throws IllegalArgumentException { ADCObserver.MCP3008_input_channels channel = null; switch (ch) { case 0: channel = ADCObserver.MCP3008_input_channels.CH0; break; case 1: channel = ADCObserver.MCP3008_input_channels.CH1; break; case 2: channel = ADCObserver.MCP3008_input_channels.CH2; break; case 3: channel = ADCObserver.MCP3008_input_channels.CH3; break; case 4: channel = ADCObserver.MCP3008_input_channels.CH4; break; case 5: channel = ADCObserver.MCP3008_input_channels.CH5; break; case 6: channel = ADCObserver.MCP3008_input_channels.CH6; break; case 7: channel = ADCObserver.MCP3008_input_channels.CH7; break; default: throw new IllegalArgumentException("No channel " + Integer.toString(ch)); } return channel; } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
12nosanshiro-pi4j-sample
ADC/src/adc/sample/BatteryMonitor.java
Java
mit
10,643
package adc.sample.log; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.swing.JOptionPane; import javax.swing.UIManager; public class LogAnalysis { private static float voltageCoeff = 1.0f; // MULTIPLYING VOLTAGE by this one ! private static int hourOffset = 0; private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private final Map<Date, LogData> logdata = new HashMap<Date, LogData>(); public LogAnalysis(String fName) throws IOException, ParseException { LogAnalysisFrame frame = new LogAnalysisFrame(this); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } frame.setLocation( ( screenSize.width - frameSize.width ) / 2, ( screenSize.height - frameSize.height ) / 2 ); // frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setVisible(true); BufferedReader br = new BufferedReader(new FileReader(fName)); String line = ""; boolean keepReading = true; Date minDate = null, maxDate = null; long smallestTimeInterval = Long.MAX_VALUE; long previousDate = -1L; int prevAdc = 0; int prevVolume = 0; float prevVoltage = 0; float minVolt = Float.MAX_VALUE, maxVolt = Float.MIN_VALUE; int nbl = 0; boolean withSmoothing = "true".equals(System.getProperty("with.smoothing", "true")); while (keepReading) { line = br.readLine(); if (line == null) keepReading = false; else { nbl++; if (nbl % 100 == 0) System.out.println("Read " + nbl + " lines"); String[] data = line.split(";"); try { Date logDate = SDF.parse(data[0]); logDate = new Date(logDate.getTime() + (hourOffset * 3600 * 1000)); // TODO Make sure the gap is not too big (like > 1 day) int adc = Integer.parseInt(data[1]); int volume = Integer.parseInt(data[2]); float voltage = Float.parseFloat(data[3]) * voltageCoeff; if (withSmoothing && previousDate != -1) { // Smooth... long deltaT = (logDate.getTime() - previousDate) / 1000; // in seconds int deltaADC = (adc - prevAdc); int deltaVolume = (volume - prevVolume); float deltaVolt = (voltage - prevVoltage); for (int i=0; i<deltaT; i++) { Date smoothDate = new Date(previousDate + (i * 1000)); int smoothADC = prevAdc + (int)((double)deltaADC * ((double)i / (double)deltaT)); int smoothVolume = prevVolume + (int)((double)deltaVolume * ((double)i / (double)deltaT)); float smoothVolt = prevVoltage + (float)((double)deltaVolt * ((double)i / (double)deltaT)); logdata.put(smoothDate, new LogData(smoothDate, smoothADC, smoothVolume, smoothVolt)); } } else { logdata.put(logDate, new LogData(logDate, adc, volume, voltage)); } if (minDate == null) minDate = logDate; else { long interval = logDate.getTime() - previousDate; smallestTimeInterval = Math.min(smallestTimeInterval, interval); if (logDate.before(minDate)) minDate = logDate; } prevAdc = adc; prevVolume = volume; prevVoltage = voltage; previousDate = logDate.getTime(); if (maxDate == null) maxDate = logDate; else { if (logDate.after(maxDate)) maxDate = logDate; } minVolt = Math.min(minVolt, voltage); maxVolt = Math.max(maxVolt, voltage); } catch (NumberFormatException nfe) { System.err.println("For line [" + line + "], (" + nbl + ") " + nfe.toString()); } catch (ParseException pe) { System.err.println("For line [" + line + "], (" + nbl + ") " + pe.toString()); } catch (Exception ex) { System.err.println("For line [" + line + "], (" + nbl + ")"); ex.printStackTrace(); } } } br.close(); System.out.println("Read " + nbl + " lines."); // Sort // SortedSet<Date> keys = new TreeSet<Date>(logdata.keySet()); // for (Date key : keys) // { // LogData value = logdata.get(key); // // do something // System.out.println(value.getDate() + ": " + value.getVoltage() + " V"); // } if (nbl == 0) { JOptionPane.showMessageDialog(null, "LogFile [" + fName + "] is empty, aborting.", "Battery Log", JOptionPane.WARNING_MESSAGE); System.exit(1); } else { System.out.println("From [" + minDate + "] to [" + maxDate + "] (" + Long.toString((maxDate.getTime() - minDate.getTime()) / 1000) + " s)"); System.out.println("Volts [" + minVolt + ", " + maxVolt + "]"); System.out.println("Smallest interval:" + (smallestTimeInterval / 1000) + " s."); System.out.println("LogData has " + logdata.size() + " element(s)"); frame.setLogData(logdata); } } public static void main(String[] args) throws Exception { try { if (System.getProperty("swing.defaultlaf") == null) UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } try { voltageCoeff = Float.parseFloat(System.getProperty("voltage.coeff", Float.toString(voltageCoeff))); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } try { hourOffset = Integer.parseInt(System.getProperty("hour.offset", Integer.toString(hourOffset))); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } System.setProperty("hour.offset", Integer.toString(hourOffset)); String dataFName = "battery.log"; if (args.length > 0) dataFName = args[0]; new LogAnalysis(dataFName); } public static class LogData { private Date date; private int adc; private int volume; public Date getDate() { return date; } public int getAdc() { return adc; } public int getVolume() { return volume; } public float getVoltage() { return voltage; } private float voltage; public LogData(Date d, int a, int v, float volt) { this.date = d; this.adc = a; this.volume = v; this.voltage = volt; } } }
12nosanshiro-pi4j-sample
ADC/src/adc/sample/log/LogAnalysis.java
Java
mit
7,281
package adc.sample.log; import adc.sample.log.LogAnalysis.LogData; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.JPanel; public class LogAnalysisPanel extends JPanel implements MouseListener, MouseMotionListener { @SuppressWarnings("compatibility:5644286187611665244") public final static long serialVersionUID = 1L; private transient Map<Date, LogData> logdata = null; private Date minDate = null, maxDate = null; private float minVolt = Float.MAX_VALUE, maxVolt = Float.MIN_VALUE; private final static NumberFormat VOLT_FMT = new DecimalFormat("#0.00"); private final static DateFormat DATE_FMT = new SimpleDateFormat("dd-MMM-yy HH:mm"); protected transient Stroke thick = new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); private boolean withSmoothing = "true".equals(System.getProperty("with.smoothing", "true")); public LogAnalysisPanel() { try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setLayout(null); this.setOpaque(false); this.setBackground(new Color(0, 0, 0, 0)); this.addMouseListener(this); this.addMouseMotionListener(this); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (logdata != null) { // Smooth Voltage Map<Date, Float> smoothVoltage = new HashMap<Date, Float>(); final int SMOOTH_WIDTH = 1000; SortedSet<Date> keys = new TreeSet<Date>(logdata.keySet()); if (withSmoothing) { List<LogData> ld = new ArrayList<LogData>(); for (Date d : keys) ld.add(logdata.get(d)); for (int i=0; i<ld.size(); i++) { float yAccu = 0f; for (int acc=i-(SMOOTH_WIDTH / 2); acc<i+(SMOOTH_WIDTH/2); acc++) { double y; if (acc < 0) y = ld.get(0).getVoltage(); else if (acc > (ld.size() - 1)) y = ld.get(ld.size() - 1).getVoltage(); else y = ld.get(acc).getVoltage(); yAccu += y; } yAccu = yAccu / SMOOTH_WIDTH; // System.out.println("Smooth Voltage:" + yAccu); smoothVoltage.put(ld.get(i).getDate(), yAccu); } } // Sort, mini maxi. boolean narrow = "y".equals(System.getProperty("narrow", "n")); /* SortedSet<Date> */ keys = new TreeSet<Date>(logdata.keySet()); for (Date key : keys) { LogData value = logdata.get(key); // System.out.println(value.getDate() + ": " + value.getVoltage() + " V"); if (minDate == null) minDate = value.getDate(); else { if (value.getDate().before(minDate)) minDate = value.getDate(); } if (maxDate == null) maxDate = value.getDate(); else { if (value.getDate().after(maxDate)) maxDate = value.getDate(); } if (narrow) { minVolt = Math.min(minVolt, value.getVoltage()); maxVolt = Math.max(maxVolt, value.getVoltage()); } } if (!narrow) { minVolt = 0; // Math.min(minVolt, value.getVoltage()); maxVolt = 15; // Math.max(maxVolt, value.getVoltage()); } long timespan = maxDate.getTime() - minDate.getTime(); float voltspan = maxVolt - minVolt; g2d.setColor(Color.white); g2d.fillRect(0, 0, this.getWidth(), this.getHeight()); // Volt grid int minVoltGrid = (int)Math.floor(minVolt); int maxVoltGrid = (int)Math.ceil(maxVolt); g2d.setColor(Color.lightGray); for (int v=minVoltGrid; v<maxVoltGrid; v++) { float voltoffset = v - minVolt; int y = this.getHeight() - (int)(this.getHeight() * ((float)voltoffset / (float)voltspan)); g2d.drawLine(0, y, this.getWidth(), y); } g2d.setColor(Color.red); Point previous = null; // Raw Data for (Date key : keys) { LogData value = logdata.get(key); Date date = key; float volt = value.getVoltage(); long timeoffset = date.getTime() - minDate.getTime(); float voltoffset = volt - minVolt; int x = (int)(this.getWidth() * ((float)timeoffset / (float)timespan)); int y = this.getHeight() - (int)(this.getHeight() * ((float)voltoffset / (float)voltspan)); Point current = new Point(x, y); // System.out.println("x:" + x + ", y:" + y); if (previous != null) g2d.drawLine(previous.x, previous.y, current.x, current.y); previous = current; } if (withSmoothing) { // Smooth Data g2d.setColor(Color.blue); Stroke orig = g2d.getStroke(); g2d.setStroke(thick); previous = null; for (Date key : keys) { float volt = smoothVoltage.get(key).floatValue(); long timeoffset = key.getTime() - minDate.getTime(); float voltoffset = volt - minVolt; int x = (int)(this.getWidth() * ((float)timeoffset / (float)timespan)); int y = this.getHeight() - (int)(this.getHeight() * ((float)voltoffset / (float)voltspan)); Point current = new Point(x, y); //System.out.println("x:" + x + ", y:" + y); if (previous != null) g2d.drawLine(previous.x, previous.y, current.x, current.y); previous = current; } g2d.setStroke(orig); } } } public void setLogData(Map<Date, LogData> logdata) { this.logdata = logdata; this.repaint(); } @Override public void mouseClicked(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mousePressed(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mouseReleased(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mouseEntered(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mouseExited(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mouseDragged(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mouseMoved(MouseEvent mouseEvent) { int x = mouseEvent.getPoint().x; int y = mouseEvent.getPoint().y; // Voltage try { float voltspan = maxVolt - minVolt; long timespan = maxDate.getTime() - minDate.getTime(); float voltage = minVolt + (voltspan * (float)(this.getHeight() - y) / (float)this.getHeight()); long minTime = minDate.getTime(); long time = minTime + (long)(timespan * ((float)x / (float)this.getWidth())); Date date = new Date(time); String mess = "<html><center><b>" + VOLT_FMT.format(voltage) + " V</b><br>" + DATE_FMT.format(date) + "</center></html>"; // System.out.println(mess); this.setToolTipText(mess); } catch (NullPointerException npe) { } } }
12nosanshiro-pi4j-sample
ADC/src/adc/sample/log/LogAnalysisPanel.java
Java
mit
8,007
package adc.sample.log; import adc.ADCObserver; import adc.gui.AnalogDisplayApp; import adc.gui.AnalogDisplayPanel; import adc.sample.log.LogAnalysis.LogData; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import java.util.Map; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; public class LogAnalysisFrame extends JFrame { private JMenuBar menuBar = new JMenuBar(); private JMenu menuFile = new JMenu(); private JMenuItem menuFileExit = new JMenuItem(); private LogAnalysisPanel displayPanel = null; private transient LogAnalysis caller; private JScrollPane jScrollPane = null; public LogAnalysisFrame(LogAnalysis parent) { this.caller = parent; displayPanel = new LogAnalysisPanel(); try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setJMenuBar(menuBar); this.getContentPane().setLayout(new BorderLayout()); this.setSize(new Dimension(1000, 275)); this.setTitle("Battery Data"); menuFile.setText("File"); menuFileExit.setText("Exit"); menuFileExit.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { fileExit_ActionPerformed( ae ); } } ); menuFile.add( menuFileExit ); menuBar.add( menuFile ); displayPanel.setPreferredSize(new Dimension(1400, 275)); jScrollPane = new JScrollPane(displayPanel); // this.getContentPane().add(displayPanel, BorderLayout.CENTER); this.getContentPane().add(jScrollPane, BorderLayout.CENTER); } void fileExit_ActionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); // this.caller.close(); System.exit(0); } public void setLogData(Map<Date, LogData> logdata) { displayPanel.setLogData(logdata); } }
12nosanshiro-pi4j-sample
ADC/src/adc/sample/log/LogAnalysisFrame.java
Java
mit
2,021
package adc.sample; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; import adc.utils.EscapeSeq; import org.fusesource.jansi.AnsiConsole; public class FiveChannelListener { private final static boolean DEBUG = false; private final static String STR100 = " "; private final static int DIGITAL_OPTION = 0; private final static int ANALOG_OPTION = 1; private static int displayOption = ANALOG_OPTION; private static ADCObserver.MCP3008_input_channels channel[] = null; private final int[] channelValues = new int[] { 0, 0, 0, 0, 0 }; public FiveChannelListener() throws Exception { channel = new ADCObserver.MCP3008_input_channels[] { ADCObserver.MCP3008_input_channels.CH0, ADCObserver.MCP3008_input_channels.CH1, ADCObserver.MCP3008_input_channels.CH2, ADCObserver.MCP3008_input_channels.CH3, ADCObserver.MCP3008_input_channels.CH4 }; final ADCObserver obs = new ADCObserver(channel); final String[] channelColors = new String[] { EscapeSeq.ANSI_RED, EscapeSeq.ANSI_WHITE, EscapeSeq.ANSI_YELLOW, EscapeSeq.ANSI_GREEN, EscapeSeq.ANSI_BLUE }; ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { // if (inputChannel.equals(channel)) { int ch = inputChannel.ch(); int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] channelValues[ch] = volume; if (DEBUG) System.out.println("readAdc:" + Integer.toString(newValue) + " (0x" + lpad(Integer.toString(newValue, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(newValue, 2), "0", 8) + ")"); if (displayOption == DIGITAL_OPTION) { String output = ""; for (int chan=0; chan<channel.length; chan++) output += "Ch " + Integer.toString(chan) + ", Volume:" + channelValues[chan] + "% "; System.out.println(output.trim()); } else if (displayOption == ANALOG_OPTION) { for (int chan=0; chan<channel.length; chan++) { String str = ""; for (int i=0; i<channelValues[chan]; i++) str += "."; try { str = EscapeSeq.superpose(str, "Ch " + Integer.toString(chan) + ": " + Integer.toString(channelValues[chan]) + "%"); AnsiConsole.out.println(EscapeSeq.ansiLocate(2, 2 + chan + 1) + EscapeSeq.ANSI_NORMAL + EscapeSeq.ANSI_DEFAULT_BACKGROUND + EscapeSeq.ANSI_DEFAULT_TEXT + STR100); AnsiConsole.out.println(EscapeSeq.ansiLocate(2, 2 + chan + 1) + EscapeSeq.ansiSetTextAndBackgroundColor(EscapeSeq.ANSI_WHITE, channelColors[chan]) + EscapeSeq.ANSI_BOLD + str + EscapeSeq.ANSI_NORMAL + EscapeSeq.ANSI_DEFAULT_BACKGROUND + EscapeSeq.ANSI_DEFAULT_TEXT); } catch (Exception ex) { System.out.println(str); } } } } } }); obs.start(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (obs != null) obs.stop(); } }); } public static void main(String[] args) throws Exception { if (displayOption == ANALOG_OPTION) { AnsiConsole.systemInstall(); AnsiConsole.out.println(EscapeSeq.ANSI_CLS); AnsiConsole.out.println(EscapeSeq.ansiLocate(1, 1) + EscapeSeq.ANSI_NORMAL + EscapeSeq.ANSI_DEFAULT_BACKGROUND + EscapeSeq.ANSI_DEFAULT_TEXT + EscapeSeq.ANSI_BOLD + "Displaying channels' volume"); } // Channels are hard-coded new FiveChannelListener(); } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
12nosanshiro-pi4j-sample
ADC/src/adc/sample/FiveChannelListener.java
Java
mit
4,342
package adc.utils; import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; public class EscapeSeq { public final static char ESC = '\u001b'; // (char) 27; public final static String ANSI_BLACK = "0"; public final static String ANSI_RED = "1"; public final static String ANSI_GREEN = "2"; public final static String ANSI_YELLOW = "3"; public final static String ANSI_BLUE = "4"; public final static String ANSI_MAGENTA = "5"; public final static String ANSI_CYAN = "6"; public final static String ANSI_WHITE = "7"; public static final String ANSI_CLS = ESC + "[2J"; public static final String ANSI_HOME = ESC + "[H"; // 0,0 public static final String ANSI_HEAD = ESC + "[1G"; // Start of current line, position 1 public static final String ANSI_NORMAL = ESC + "[0m"; public static final String ANSI_BOLD = ESC + "[1m"; public static final String ANSI_FAINT = ESC + "[2m"; public static final String ANSI_ITALIC = ESC + "[3m"; public static final String ANSI_UNDERLINE = ESC + "[4m"; public static final String ANSI_BLINK = ESC + "[5m"; public static final String ANSI_BLINK_FAST = ESC + "[6m"; public static final String ANSI_REVERSE = ESC + "[7m"; public static final String ANSI_CONCEAL = ESC + "[8m"; public static final String ANSI_CROSSED_OUT = ESC + "[9m"; public static final String ANSI_DEFAULT_TEXT = ESC + "[39m"; public static final String ANSI_DEFAULT_BACKGROUND = ESC + "[49m"; private final static String[] SOME_TEXT = { "What happens when the boat sends an email:", "On the boat, you compose your email, and you put it in your outbox.", "Then you turn your SSB on, and you use the SailMail client program to contact a land SailMail station.", "When the contact is established, the messages sitting in the outbox go through the modem and the SSB to ", "be streamed to the land station. On receive, the land station then turns the messages back into digital files,", "and uses its Internet connection to post them on the web. From there, it's the usual email story." }; public static final String ANSI_AT55 = ESC + "[10;10H"; // Actually 10, 10 public static final String ANSI_WHITEONBLUE = ESC + "[37;44m"; public static String ansiSetBackGroundColor(String color) { // ESC[40-47 return ESC + "[4" + color + "m"; } public static String ansiSetTextColor(String color) { // ESC[30-37 return ESC + "[3" + color + "m"; } public static String ansiSetTextAndBackgroundColor(String text, String bg) { // ESC[30-37;40-47 return ESC + "[3" + text + ";4" + bg + "m"; } public static String ansiLocate(int x, int y) { return ESC + "[" + Integer.toString(y) + ";" + Integer.toString(x) + "H"; // Actually Y, X } // An example public static void main(String[] args) { String str80 = " "; AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); // Display 5 rows, like an horizontal bar chart for (int i=0; i<20; i++) { int value1 = (int)Math.round(Math.random() * 80); int value2 = (int)Math.round(Math.random() * 80); int value3 = (int)Math.round(Math.random() * 80); int value4 = (int)Math.round(Math.random() * 80); int value5 = (int)Math.round(Math.random() * 80); String str1 = ""; for (int j=0; j<value1; j++) str1 += "."; String str2 = ""; for (int j=0; j<value2; j++) str2 += "."; String str3 = ""; for (int j=0; j<value3; j++) str3 += "."; String str4 = ""; for (int j=0; j<value4; j++) str4 += "."; String str5 = ""; for (int j=0; j<value5; j++) str5 += "."; str1 = superpose(str1, "Cell 1:" + Integer.toString(value1)); str2 = superpose(str2, "Cell 2:" + Integer.toString(value2)); str3 = superpose(str3, "Cell 3:" + Integer.toString(value3)); str4 = superpose(str4, "Cell 4:" + Integer.toString(value4)); str5 = superpose(str5, "Cell 5:" + Integer.toString(value5)); // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ansiLocate(0, 1) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 1) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_RED) + ANSI_BOLD + str1 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 2) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 2) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_WHITE) + ANSI_BOLD + str2 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 3) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 3) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_YELLOW) + ANSI_BOLD + str3 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 4) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 4) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_GREEN) + ANSI_BOLD + str4 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 5) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 5) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLUE) + ANSI_BOLD + str5 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); try { Thread.sleep(1000L); } catch (Exception ex) {} } System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } public static String superpose(String orig, String override) { byte[] ret = orig.getBytes(); for (int i=0; i<Math.min(orig.length(), override.length()); i++) ret[i] = (byte)override.charAt(i); return new String(ret); } public static void main_(String[] args) { AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_AT55 + ANSI_REVERSE + "10,10 reverse : Hello world" + ANSI_NORMAL); AnsiConsole.out.println(ANSI_HOME + ANSI_WHITEONBLUE + "WhiteOnBlue : Hello world" + ANSI_NORMAL); AnsiConsole.out.print(ANSI_BOLD + "Bold : Press return..." + ANSI_NORMAL); try { System.in.read(); } catch (Exception e) { } // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); AnsiConsole.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); for (String line : SOME_TEXT) { System.out.print(ANSI_HEAD + line); try { Thread.sleep(1000); } catch (Exception ex) {} } System.out.println(); System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } }
12nosanshiro-pi4j-sample
ADC/src/adc/utils/EscapeSeq.java
Java
mit
7,897
package analogdigitalconverter.mcp3008; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * Read an Analog to Digital Converter */ public class MCP3008Reader { private final static boolean DISPLAY_DIGIT = "true".equals(System.getProperty("display.digit", "false")); // Note: "Mismatch" 23-24. The wiring says DOUT->#23, DIN->#24 // 23: DOUT on the ADC is IN on the GPIO. ADC:Slave, GPIO:Master // 24: DIN on the ADC, OUT on the GPIO. Same reason as above. // SPI: Serial Peripheral Interface private static Pin spiClk = RaspiPin.GPIO_01; // Pin #18, clock private static Pin spiMiso = RaspiPin.GPIO_04; // Pin #23, data in. MISO: Master In Slave Out private static Pin spiMosi = RaspiPin.GPIO_05; // Pin #24, data out. MOSI: Master Out Slave In private static Pin spiCs = RaspiPin.GPIO_06; // Pin #25, Chip Select public enum MCP3008_input_channels { CH0(0), CH1(1), CH2(2), CH3(3), CH4(4), CH5(5), CH6(6), CH7(7); private int ch; MCP3008_input_channels(int chNum) { this.ch = chNum; } public int ch() { return this.ch; } } private static GpioController gpio; private static GpioPinDigitalInput misoInput = null; private static GpioPinDigitalOutput mosiOutput = null; private static GpioPinDigitalOutput clockOutput = null; private static GpioPinDigitalOutput chipSelectOutput = null; public static void initMCP3008() { gpio = GpioFactory.getInstance(); mosiOutput = gpio.provisionDigitalOutputPin(spiMosi, "MOSI", PinState.LOW); clockOutput = gpio.provisionDigitalOutputPin(spiClk, "CLK", PinState.LOW); chipSelectOutput = gpio.provisionDigitalOutputPin(spiCs, "CS", PinState.LOW); misoInput = gpio.provisionDigitalInputPin(spiMiso, "MISO"); } public static void shutdownMCP3008() { gpio.shutdown(); } public static int readMCP3008(int channel) { chipSelectOutput.high(); clockOutput.low(); chipSelectOutput.low(); int adccommand = channel; if (DISPLAY_DIGIT) System.out.println("1 - ADCCOMMAND: 0x" + lpad(Integer.toString(adccommand, 16).toUpperCase(), "0", 4) + ", 0&" + lpad(Integer.toString(adccommand, 2).toUpperCase(), "0", 16)); adccommand |= 0x18; // 0x18: 00011000 if (DISPLAY_DIGIT) System.out.println("2 - ADCCOMMAND: 0x" + lpad(Integer.toString(adccommand, 16).toUpperCase(), "0", 4) + ", 0&" + lpad(Integer.toString(adccommand, 2).toUpperCase(), "0", 16)); adccommand <<= 3; if (DISPLAY_DIGIT) System.out.println("3 - ADCCOMMAND: 0x" + lpad(Integer.toString(adccommand, 16).toUpperCase(), "0", 4) + ", 0&" + lpad(Integer.toString(adccommand, 2).toUpperCase(), "0", 16)); // Send 5 bits: 8 - 3. 8 input channels on the MCP3008. for (int i=0; i<5; i++) // { if (DISPLAY_DIGIT) System.out.println("4 - (i=" + i + ") ADCCOMMAND: 0x" + lpad(Integer.toString(adccommand, 16).toUpperCase(), "0", 4) + ", 0&" + lpad(Integer.toString(adccommand, 2).toUpperCase(), "0", 16)); if ((adccommand & 0x80) != 0x0) // 0x80 = 0&10000000 mosiOutput.high(); else mosiOutput.low(); adccommand <<= 1; // Clock high and low tickOnPin(clockOutput); } int adcOut = 0; for (int i=0; i<12; i++) // Read in one empty bit, one null bit and 10 ADC bits { tickOnPin(clockOutput); adcOut <<= 1; if (misoInput.isHigh()) { // System.out.println(" " + misoInput.getName() + " is high (i:" + i + ")"); // Shift one bit on the adcOut adcOut |= 0x1; } if (DISPLAY_DIGIT) System.out.println("ADCOUT: 0x" + lpad(Integer.toString(adcOut, 16).toUpperCase(), "0", 4) + ", 0&" + lpad(Integer.toString(adcOut, 2).toUpperCase(), "0", 16)); } chipSelectOutput.high(); adcOut >>= 1; // Drop first bit return adcOut; } private static void tickOnPin(GpioPinDigitalOutput pin) { pin.high(); pin.low(); } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
12nosanshiro-pi4j-sample
ADC/src/analogdigitalconverter/mcp3008/MCP3008Reader.java
Java
mit
4,682
package analogdigitalconverter.mcp3008.sample; import analogdigitalconverter.mcp3008.MCP3008Reader; import analogdigitalconverter.mcp3008.MCP3008Reader.MCP3008_input_channels; public class MainMCP3008Sample { private final static boolean DEBUG = false; private static boolean go = true; private static int ADC_CHANNEL = MCP3008Reader.MCP3008_input_channels.CH0.ch(); // Between 0 and 7, 8 channels on the MCP3008 public static void main(String[] args) { MCP3008Reader.initMCP3008(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Shutting down."); go = false; synchronized (Thread.currentThread()) { Thread.currentThread().notify(); } } }); int lastRead = 0; int tolerance = 5; while (go) { boolean trimPotChanged = false; int adc = MCP3008Reader.readMCP3008(ADC_CHANNEL); int postAdjust = Math.abs(adc - lastRead); if (postAdjust > tolerance) { trimPotChanged = true; int volume = (int)(adc / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (DEBUG) System.out.println("readAdc:" + Integer.toString(adc) + " (0x" + lpad(Integer.toString(adc, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(adc, 2), "0", 8) + ")"); System.out.println("Volume:" + volume + "% (" + adc + ")"); lastRead = adc; } try { synchronized (Thread.currentThread()) { Thread.currentThread().wait(100L); } } catch (InterruptedException ie) { ie.printStackTrace(); } } System.out.println("Bye, freeing resources."); MCP3008Reader.shutdownMCP3008(); } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
12nosanshiro-pi4j-sample
ADC/src/analogdigitalconverter/mcp3008/sample/MainMCP3008Sample.java
Java
mit
2,438
package analogdigitalconverter; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * Read an Analog to Digital Converter */ public class ADCReader { private final static boolean DISPLAY_DIGIT = false; private final static boolean DEBUG = false; // Note: "Mismatch" 23-24. The wiring says DOUT->#23, DIN->#24 // 23: DOUT on the ADC is IN on the GPIO. ADC:Slave, GPIO:Master // 24: DIN on the ADC, OUT on the GPIO. Same reason as above. // SPI: Serial Peripheral Interface private static Pin spiClk = RaspiPin.GPIO_01; // Pin #18, clock private static Pin spiMiso = RaspiPin.GPIO_04; // Pin #23, data in. MISO: Master In Slave Out private static Pin spiMosi = RaspiPin.GPIO_05; // Pin #24, data out. MOSI: Master Out Slave In private static Pin spiCs = RaspiPin.GPIO_06; // Pin #25, Chip Select private enum MCP3008_input_channels { CH0(0), CH1(1), CH2(2), CH3(3), CH4(4), CH5(5), CH6(6), CH7(7); private int ch; MCP3008_input_channels(int chNum) { this.ch = chNum; } public int ch() { return this.ch; } } private static int ADC_CHANNEL = MCP3008_input_channels.CH0.ch(); // Between 0 and 7, 8 channels on the MCP3008 private static GpioPinDigitalInput misoInput = null; private static GpioPinDigitalOutput mosiOutput = null; private static GpioPinDigitalOutput clockOutput = null; private static GpioPinDigitalOutput chipSelectOutput = null; private static boolean go = true; public static void main(String[] args) { GpioController gpio = GpioFactory.getInstance(); mosiOutput = gpio.provisionDigitalOutputPin(spiMosi, "MOSI", PinState.LOW); clockOutput = gpio.provisionDigitalOutputPin(spiClk, "CLK", PinState.LOW); chipSelectOutput = gpio.provisionDigitalOutputPin(spiCs, "CS", PinState.LOW); misoInput = gpio.provisionDigitalInputPin(spiMiso, "MISO"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Shutting down."); go = false; } }); int lastRead = 0; int tolerance = 5; while (go) { boolean trimPotChanged = false; int adc = readAdc(); int postAdjust = Math.abs(adc - lastRead); if (postAdjust > tolerance) { trimPotChanged = true; int volume = (int)(adc / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (DEBUG) System.out.println("readAdc:" + Integer.toString(adc) + " (0x" + lpad(Integer.toString(adc, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(adc, 2), "0", 8) + ")"); System.out.println("Volume:" + volume + "% (" + adc + ")"); lastRead = adc; } try { Thread.sleep(100L); } catch (InterruptedException ie) { ie.printStackTrace(); } } System.out.println("Bye..."); gpio.shutdown(); } private static int readAdc() { chipSelectOutput.high(); clockOutput.low(); chipSelectOutput.low(); int adccommand = ADC_CHANNEL; adccommand |= 0x18; // 0x18: 00011000 adccommand <<= 3; // Send 5 bits: 8 - 3. 8 input channels on the MCP3008. for (int i=0; i<5; i++) // { if ((adccommand & 0x80) != 0x0) // 0x80 = 0&10000000 mosiOutput.high(); else mosiOutput.low(); adccommand <<= 1; clockOutput.high(); clockOutput.low(); } int adcOut = 0; for (int i=0; i<12; i++) // Read in one empty bit, one null bit and 10 ADC bits { clockOutput.high(); clockOutput.low(); adcOut <<= 1; if (misoInput.isHigh()) { // System.out.println(" " + misoInput.getName() + " is high (i:" + i + ")"); // Shift one bit on the adcOut adcOut |= 0x1; } if (DISPLAY_DIGIT) System.out.println("ADCOUT: 0x" + Integer.toString(adcOut, 16).toUpperCase() + ", 0&" + Integer.toString(adcOut, 2).toUpperCase()); } chipSelectOutput.high(); adcOut >>= 1; // Drop first bit return adcOut; } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
12nosanshiro-pi4j-sample
ADC/src/analogdigitalconverter/ADCReader.java
Java
mit
4,904
#!/bin/bash echo Read an ADC, feed a WebSocket # CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/orasocket-client-12.1.3.jar # sudo java -cp $CP -Dws.uri=ws://localhost:9876/ adc.sample.WebSocketFeeder $*
12nosanshiro-pi4j-sample
ADC/run.ws
Shell
mit
219
#!/bin/bash echo Read an ADC # CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/jansi-1.9.jar sudo java -cp $CP adc.sample.BatteryMonitor $*
12nosanshiro-pi4j-sample
ADC/battery.monitor
Shell
mit
154
/* * Compile with * gcc -l wiringPi -o readMCP3008 mcp3008reader.c mcp3008main.c *********************************************************************** * Oliv proudly did it. */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <wiringPi.h> #include "mcp3008reader.h" #define ADC_CHANNEL 0 // 0 to 7, 8 channels on the MCP3008 int main(void) { fprintf(stdout, "Raspberry Pi reads an ADC\n") ; initMPC3008(); bool go = true; int lastRead = -100; int tolerance = 10; while (go) { bool trimPotChanged = false; int pot = readMCP3008(ADC_CHANNEL); int potAdjust = abs(pot - lastRead); if (potAdjust > tolerance) { trimPotChanged = true; int volume = (int)((float)pot / 10.23); fprintf(stdout, "Pot volume:%d %% value:%d\n", volume, pot); lastRead = pot; } delay (250); } return 0; }
12nosanshiro-pi4j-sample
ADC/C/mcp3008main.c
C
mit
882
void initMPC3008(void); int readMCP3008(int channel);
12nosanshiro-pi4j-sample
ADC/C/mcp3008reader.h
C
mit
55
/* * Oliv proudly did it. */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <wiringPi.h> /* Pin numbers: * pin 1 is BCM_GPIO 18. * pin 4 is BCM_GPIO 23. * pin 5 is BCM_GPIO 24. * pin 6 is BCM_GPIO 25. */ #define SPI_CLK 1 // Clock #define SPI_MISO 4 // Master In Slave Out #define SPI_MOSI 5 // Master Out Slave In #define SPI_CS 6 // Chip Select #define ADC_CHANNEL 0 // 0 to 7, 8 channels on the MCP3008 #define DISPLAY_DIGIT 0 void initMPC3008(void) { wiringPiSetup(); pinMode(SPI_CLK, OUTPUT); pinMode(SPI_MOSI, OUTPUT); pinMode(SPI_CS, OUTPUT); digitalWrite(SPI_CLK, LOW); digitalWrite(SPI_MOSI, LOW); digitalWrite(SPI_CS, LOW); pinMode (SPI_MISO, INPUT); } int readMCP3008(int channel) { int i; digitalWrite(SPI_CS, HIGH); digitalWrite(SPI_CLK, LOW); digitalWrite(SPI_CS, LOW); int adcCommand = channel; adcCommand |= 0x18; // 0x18 = 00011000 adcCommand <<= 3; // Send 5 bits: 8 - 3. 8 input channels on the MCP3008. for (i=0; i<5; i++) { if (DISPLAY_DIGIT) fprintf(stdout, "(i=%d) ADCCOMMAND: 0x%04x\n", i, adcCommand); if ((adcCommand & 0x80) != 0x0) // 0x80 = 0&10000000 digitalWrite(SPI_MOSI, HIGH); else digitalWrite(SPI_MOSI, LOW); adcCommand <<= 1; digitalWrite(SPI_CLK, HIGH); digitalWrite(SPI_CLK, LOW); } int adcOut = 0; for (i=0; i<12; i++) // Read in one empty bit, one null bit and 10 ADC bits { digitalWrite(SPI_CLK, HIGH); digitalWrite(SPI_CLK, LOW); adcOut <<= 1; if (digitalRead(SPI_MISO) == HIGH) { // Shift one bit on the adcOut adcOut |= 0x1; } if (DISPLAY_DIGIT) fprintf(stdout, "ADCOUT: 0x%04x\n", (adcOut)); } digitalWrite(SPI_CS, HIGH); adcOut >>= 1; // Drop first bit return adcOut & 0x3FF; // 0x3FF = 2^10, 1024. }
12nosanshiro-pi4j-sample
ADC/C/mcp3008reader.c
C
mit
1,855
@setlocal @echo off set CP=.\classes set CP=%CP%;.\lib\jansi-1.9.jar java -cp %CP% adc.utils.EscapeSeq @endlocal
12nosanshiro-pi4j-sample
ADC/test.esc.cmd
Batchfile
mit
112
#!/bin/bash JAVAC_OPTIONS="-sourcepath ./src" JAVAC_OPTIONS="$JAVAC_OPTIONS -d ./classes" echo $JAVAC_OPTIONS CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # JAVAC_OPTIONS="-verbose $JAVAC_OPTIONS" JAVAC_OPTIONS="$JAVAC_OPTIONS -cp $CP" COMMAND="javac $JAVAC_OPTIONS `find ./src -name '*.java' -print`" echo Compiling: $COMMAND $COMMAND echo Done
12nosanshiro-pi4j-sample
DAC/compile
Shell
mit
351
#!/bin/bash CP=./classes:$PI4J_HOME/lib/pi4j-core.jar java -cp $CP dac.sample.DACSample
12nosanshiro-pi4j-sample
DAC/run
Shell
mit
88
package dac.sample; import dac.mcp4725.AdafruitMCP4725; import java.io.IOException; public class DACSample { private static final int[] DACLookupFullSine9Bit = new int[] { 2048, 2073, 2098, 2123, 2148, 2174, 2199, 2224, 2249, 2274, 2299, 2324, 2349, 2373, 2398, 2423, 2448, 2472, 2497, 2521, 2546, 2570, 2594, 2618, 2643, 2667, 2690, 2714, 2738, 2762, 2785, 2808, 2832, 2855, 2878, 2901, 2924, 2946, 2969, 2991, 3013, 3036, 3057, 3079, 3101, 3122, 3144, 3165, 3186, 3207, 3227, 3248, 3268, 3288, 3308, 3328, 3347, 3367, 3386, 3405, 3423, 3442, 3460, 3478, 3496, 3514, 3531, 3548, 3565, 3582, 3599, 3615, 3631, 3647, 3663, 3678, 3693, 3708, 3722, 3737, 3751, 3765, 3778, 3792, 3805, 3817, 3830, 3842, 3854, 3866, 3877, 3888, 3899, 3910, 3920, 3930, 3940, 3950, 3959, 3968, 3976, 3985, 3993, 4000, 4008, 4015, 4022, 4028, 4035, 4041, 4046, 4052, 4057, 4061, 4066, 4070, 4074, 4077, 4081, 4084, 4086, 4088, 4090, 4092, 4094, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4094, 4092, 4090, 4088, 4086, 4084, 4081, 4077, 4074, 4070, 4066, 4061, 4057, 4052, 4046, 4041, 4035, 4028, 4022, 4015, 4008, 4000, 3993, 3985, 3976, 3968, 3959, 3950, 3940, 3930, 3920, 3910, 3899, 3888, 3877, 3866, 3854, 3842, 3830, 3817, 3805, 3792, 3778, 3765, 3751, 3737, 3722, 3708, 3693, 3678, 3663, 3647, 3631, 3615, 3599, 3582, 3565, 3548, 3531, 3514, 3496, 3478, 3460, 3442, 3423, 3405, 3386, 3367, 3347, 3328, 3308, 3288, 3268, 3248, 3227, 3207, 3186, 3165, 3144, 3122, 3101, 3079, 3057, 3036, 3013, 2991, 2969, 2946, 2924, 2901, 2878, 2855, 2832, 2808, 2785, 2762, 2738, 2714, 2690, 2667, 2643, 2618, 2594, 2570, 2546, 2521, 2497, 2472, 2448, 2423, 2398, 2373, 2349, 2324, 2299, 2274, 2249, 2224, 2199, 2174, 2148, 2123, 2098, 2073, 2048, 2023, 1998, 1973, 1948, 1922, 1897, 1872, 1847, 1822, 1797, 1772, 1747, 1723, 1698, 1673, 1648, 1624, 1599, 1575, 1550, 1526, 1502, 1478, 1453, 1429, 1406, 1382, 1358, 1334, 1311, 1288, 1264, 1241, 1218, 1195, 1172, 1150, 1127, 1105, 1083, 1060, 1039, 1017, 995, 974, 952, 931, 910, 889, 869, 848, 828, 808, 788, 768, 749, 729, 710, 691, 673, 654, 636, 618, 600, 582, 565, 548, 531, 514, 497, 481, 465, 449, 433, 418, 403, 388, 374, 359, 345, 331, 318, 304, 291, 279, 266, 254, 242, 230, 219, 208, 197, 186, 176, 166, 156, 146, 137, 128, 120, 111, 103, 96, 88, 81, 74, 68, 61, 55, 50, 44, 39, 35, 30, 26, 22, 19, 15, 12, 10, 8, 6, 4, 2, 1, 1, 0, 0, 0, 1, 1, 2, 4, 6, 8, 10, 12, 15, 19, 22, 26, 30, 35, 39, 44, 50, 55, 61, 68, 74, 81, 88, 96, 103, 111, 120, 128, 137, 146, 156, 166, 176, 186, 197, 208, 219, 230, 242, 254, 266, 279, 291, 304, 318, 331, 345, 359, 374, 388, 403, 418, 433, 449, 465, 481, 497, 514, 531, 548, 565, 582, 600, 618, 636, 654, 673, 691, 710, 729, 749, 768, 788, 808, 828, 848, 869, 889, 910, 931, 952, 974, 995, 1017, 1039, 1060, 1083, 1105, 1127, 1150, 1172, 1195, 1218, 1241, 1264, 1288, 1311, 1334, 1358, 1382, 1406, 1429, 1453, 1478, 1502, 1526, 1550, 1575, 1599, 1624, 1648, 1673, 1698, 1723, 1747, 1772, 1797, 1822, 1847, 1872, 1897, 1922, 1948, 1973, 1998, 2023 }; public static void main(String[] args)// throws IOException { System.out.println("The output happens on the VOUT terminal of the MCP4725."); AdafruitMCP4725 dac = new AdafruitMCP4725(); for (int i=0; i<5; i++) { for (int volt : DACLookupFullSine9Bit) { dac.setVoltage(volt); try { Thread.sleep(10L); } catch (InterruptedException ie) {} } } } }
12nosanshiro-pi4j-sample
DAC/src/dac/sample/DACSample.java
Java
mit
3,914
package dac.mcp4725; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import java.io.IOException; public class AdafruitMCP4725 { public final static int MCP4725_ADDRESS = 0x62; // Can be changed with pin A0. A0 connected to VDD: 0x63 public final static int MCP4725_REG_WRITEDAC = 0x40; public final static int MCP4725_REG_WRITEDACEEPROM = 0x60; private static boolean verbose = true; private I2CBus bus; private I2CDevice mcp4725; public AdafruitMCP4725() { this(MCP4725_ADDRESS); } public AdafruitMCP4725(int address) { try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends on the RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself mcp4725 = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); } catch (IOException e) { System.err.println(e.getMessage()); } } // Set the voltage, readable on the VOUT terminal public void setVoltage(int voltage) // throws IOException { try { setVoltage(voltage, false); } catch (IOException ioe) { ioe.printStackTrace(); } catch (NullPointerException npe) { npe.printStackTrace(); } } public void setVoltage(int voltage, boolean persist) throws IOException, NullPointerException { voltage = Math.min(voltage, 4095); // 4096 = 2^12 voltage = Math.max(voltage, 0); byte[] bytes = new byte[2]; bytes[0] = (byte)((voltage >> 4) & 0xff); bytes[1] = (byte)((voltage << 4) & 0xff); if (persist) this.mcp4725.write(MCP4725_REG_WRITEDACEEPROM, bytes, 0, 2); else this.mcp4725.write(MCP4725_REG_WRITEDAC, bytes, 0, 2); } }
12nosanshiro-pi4j-sample
DAC/src/dac/mcp4725/AdafruitMCP4725.java
Java
mit
1,829
#!/bin/bash JAVAC_OPTIONS="-sourcepath ./src" JAVAC_OPTIONS="$JAVAC_OPTIONS -d ./classes" echo $JAVAC_OPTIONS CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:../GPSandSun/classes # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/almanactools.jar CP=$CP:./lib/geomutil.jar CP=$CP:./lib/nauticalalmanac.jar CP=$CP:./lib/nmeaparser.jar CP=$CP:./lib/jansi-1.9.jar # JAVAC_OPTIONS="-verbose $JAVAC_OPTIONS" JAVAC_OPTIONS="$JAVAC_OPTIONS -cp $CP" COMMAND="javac $JAVAC_OPTIONS `find ./src -name '*.java' -print`" echo Compiling: $COMMAND $COMMAND echo Done
12nosanshiro-pi4j-sample
GPS.sun.servo/compile
Shell
mit
620
#!/bin/bash echo Read serial port echo Usage $0 [BaudRate] \(default 4800\) echo Try 2400, 4800, 9600, 19200, 38400, 57600, 115200, ... CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:../GPSandSun/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/almanactools.jar CP=$CP:./lib/geomutil.jar CP=$CP:./lib/nauticalalmanac.jar CP=$CP:./lib/nmeaparser.jar CP=$CP:./lib/coreutilities.jar CP=$CP:./lib/jansi-1.9.jar sudo java -cp $CP sunservo.SunServoNMEAReader $* # sudo java -Dserial.port=/dev/ttyUSB0 -cp $CP sunservo.SunServoNMEAReader $*
12nosanshiro-pi4j-sample
GPS.sun.servo/run
Shell
mit
545
package sunservo; import org.fusesource.jansi.AnsiConsole; public class EscapeSeq { public final static char ESC = '\u001b'; // (char) 27; public final static String ANSI_BLACK = "0"; public final static String ANSI_RED = "1"; public final static String ANSI_GREEN = "2"; public final static String ANSI_YELLOW = "3"; public final static String ANSI_BLUE = "4"; public final static String ANSI_MAGENTA = "5"; public final static String ANSI_CYAN = "6"; public final static String ANSI_WHITE = "7"; public static final String ANSI_CLS = ESC + "[2J"; public static final String ANSI_HOME = ESC + "[H"; // 0,0 public static final String ANSI_HEAD = ESC + "[1G"; // Start of current line, position 1 public static final String ANSI_NORMAL = ESC + "[0m"; public static final String ANSI_BOLD = ESC + "[1m"; public static final String ANSI_FAINT = ESC + "[2m"; public static final String ANSI_ITALIC = ESC + "[3m"; public static final String ANSI_UNDERLINE = ESC + "[4m"; public static final String ANSI_BLINK = ESC + "[5m"; public static final String ANSI_BLINK_FAST = ESC + "[6m"; public static final String ANSI_REVERSE = ESC + "[7m"; public static final String ANSI_CONCEAL = ESC + "[8m"; public static final String ANSI_CROSSED_OUT = ESC + "[9m"; public static final String ANSI_DEFAULT_TEXT = ESC + "[39m"; public static final String ANSI_DEFAULT_BACKGROUND = ESC + "[49m"; private final static String[] SOME_TEXT = { "What happens when the boat sends an email:", "On the boat, you compose your email, and you put it in your outbox.", "Then you turn your SSB on, and you use the SailMail client program to contact a land SailMail station.", "When the contact is established, the messages sitting in the outbox go through the modem and the SSB to ", "be streamed to the land station. On receive, the land station then turns the messages back into digital files,", "and uses its Internet connection to post them on the web. From there, it's the usual email story." }; public static final String ANSI_AT55 = ESC + "[10;10H"; // Actually 10, 10 public static final String ANSI_WHITEONBLUE = ESC + "[37;44m"; public static String ansiSetBackGroundColor(String color) { // ESC[40-47 return ESC + "[4" + color + "m"; } public static String ansiSetTextColor(String color) { // ESC[30-37 return ESC + "[3" + color + "m"; } public static String ansiSetTextAndBackgroundColor(String text, String bg) { // ESC[30-37;40-47 return ESC + "[3" + text + ";4" + bg + "m"; } public static String ansiLocate(int x, int y) { return ESC + "[" + Integer.toString(y) + ";" + Integer.toString(x) + "H"; // Actually Y, X } // An example public static void main(String[] args) { String str80 = " "; AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); // Display 5 rows, like an horizontal bar chart for (int i=0; i<20; i++) { int value1 = (int)Math.round(Math.random() * 80); int value2 = (int)Math.round(Math.random() * 80); int value3 = (int)Math.round(Math.random() * 80); int value4 = (int)Math.round(Math.random() * 80); int value5 = (int)Math.round(Math.random() * 80); String str1 = ""; for (int j=0; j<value1; j++) str1 += "."; String str2 = ""; for (int j=0; j<value2; j++) str2 += "."; String str3 = ""; for (int j=0; j<value3; j++) str3 += "."; String str4 = ""; for (int j=0; j<value4; j++) str4 += "."; String str5 = ""; for (int j=0; j<value5; j++) str5 += "."; str1 = superpose(str1, "Cell 1:" + Integer.toString(value1)); str2 = superpose(str2, "Cell 2:" + Integer.toString(value2)); str3 = superpose(str3, "Cell 3:" + Integer.toString(value3)); str4 = superpose(str4, "Cell 4:" + Integer.toString(value4)); str5 = superpose(str5, "Cell 5:" + Integer.toString(value5)); // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ansiLocate(0, 1) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 1) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_RED) + ANSI_BOLD + str1 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 2) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 2) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_WHITE) + ANSI_BOLD + str2 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 3) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 3) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_YELLOW) + ANSI_BOLD + str3 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 4) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 4) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_GREEN) + ANSI_BOLD + str4 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 5) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 5) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLUE) + ANSI_BOLD + str5 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); try { Thread.sleep(1000L); } catch (Exception ex) {} } System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } public static String superpose(String orig, String override) { byte[] ret = orig.getBytes(); for (int i=0; i<Math.min(orig.length(), override.length()); i++) ret[i] = (byte)override.charAt(i); return new String(ret); } public static void main_(String[] args) { AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_AT55 + ANSI_REVERSE + "10,10 reverse : Hello world" + ANSI_NORMAL); AnsiConsole.out.println(ANSI_HOME + ANSI_WHITEONBLUE + "WhiteOnBlue : Hello world" + ANSI_NORMAL); AnsiConsole.out.print(ANSI_BOLD + "Bold : Press return..." + ANSI_NORMAL); try { System.in.read(); } catch (Exception e) { } // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); AnsiConsole.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); for (String line : SOME_TEXT) { System.out.print(ANSI_HEAD + line); try { Thread.sleep(1000); } catch (Exception ex) {} } System.out.println(); System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } }
12nosanshiro-pi4j-sample
GPS.sun.servo/src/sunservo/EscapeSeq.java
Java
mit
7,862
@setlocal @echo off set JAVA_HOME=D:\Java\jdk1.7.0_45 set PATH=%JAVA_HOME%\bin;%PATH% set JAVAC_OTPIONS=-sourcepath .\src set JAVAC_OPTIONS=%JAVAC_OPTIONS% -d .\classes set CP=.\classes set CP=%CP%;..\AdafruitI2C\classes set CP=%CP%;..\GPSandSun\classes set PI4J_HOME=D:\Cloud\pi4j set CP=%CP%;%PI4J_HOME%\libs\pi4j-core.jar :: set CP=%CP%;%PI4J_HOME%\libs\pi4j-device.jar :: set CP=%CP%;%PI4J_HOME%\libs\pi4j-gpio-extension.jar :: set CP=%CP%;%PI4J_HOME%\libs\pi4j-service.jar set CP=%CP%;.\lib\almanactools.jar set CP=%CP%;.\lib\geomutil.jar set CP=%CP%;.\lib\nauticalalmanac.jar set CP=%CP%;.\lib\nmeaparser.jar set CP=%CP%;.\lib\jansi-1.9.jar set JAVAC_OPTIONS=%JAVAC_OPTIONS% -cp %CP% echo Compiling javac %JAVAC_OPTIONS% .\src\sunservo\*.java echo Done @endlocal
12nosanshiro-pi4j-sample
GPS.sun.servo/compile.cmd
Batchfile
mit
771
#!/bin/bash echo Blinking 8 leds CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP gpio01.GPIO08led
12nosanshiro-pi4j-sample
GPIO.01/run8
Shell
mit
110
#!/bin/bash JAVAC_OPTIONS="-sourcepath ./src" JAVAC_OPTIONS="$JAVAC_OPTIONS -d ./classes" echo $JAVAC_OPTIONS CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # JAVAC_OPTIONS="-verbose $JAVAC_OPTIONS" JAVAC_OPTIONS="$JAVAC_OPTIONS -cp $CP" COMMAND="javac $JAVAC_OPTIONS `find ./src -name '*.java' -print`" echo Compiling: $COMMAND $COMMAND echo Done
12nosanshiro-pi4j-sample
GPIO.01/compile
Shell
mit
351
#!/bin/bash echo Speed Test CP=./classes:/home/pi/pi4j/pi4j-distribution/target/distro-contents/lib/pi4j-core.jar sudo java -cp $CP gpio01.SpeedTest
12nosanshiro-pi4j-sample
GPIO.01/test
Shell
mit
150
#!/bin/bash echo Blinking a led, pin 01 CP=./classes:$PI4J_HOME/lib/pi4j-core.jar java -cp $CP gpio01.GPIO01led
12nosanshiro-pi4j-sample
GPIO.01/run
Shell
mit
112
package gpio01; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class GPIO01led { public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - pin 01 ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #01 as an output pin and turn on final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "MyLED", PinState.HIGH); System.out.println("--> GPIO state should be: ON"); Thread.sleep(5000); // turn off gpio pin #01 pin.low(); System.out.println("--> GPIO state should be: OFF"); Thread.sleep(5000); // toggle the current state of gpio pin #01 (should turn on) pin.toggle(); System.out.println("--> GPIO state should be: ON"); Thread.sleep(5000); // toggle the current state of gpio pin #01 (should turn off) pin.toggle(); System.out.println("--> GPIO state should be: OFF"); Thread.sleep(5000); // turn on gpio pin #01 for 1 second and then off System.out.println("--> GPIO state should be: ON for only 1 second"); pin.pulse(1000, true); // set second argument to 'true' use a blocking call // stop all GPIO activity/threads by shutting down the GPIO controller // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks) gpio.shutdown(); } }
12nosanshiro-pi4j-sample
GPIO.01/src/gpio01/GPIO01led.java
Java
mit
1,582
package gpio01; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class GPIO08led { public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control ...started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalOutput pin00 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "00", PinState.HIGH); final GpioPinDigitalOutput pin01 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "01", PinState.HIGH); final GpioPinDigitalOutput pin02 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "02", PinState.HIGH); final GpioPinDigitalOutput pin03 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03, "03", PinState.HIGH); final GpioPinDigitalOutput pin04 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "04", PinState.HIGH); final GpioPinDigitalOutput pin05 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_05, "05", PinState.HIGH); final GpioPinDigitalOutput pin06 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_06, "06", PinState.HIGH); final GpioPinDigitalOutput pin07 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_07, "07", PinState.HIGH); final GpioPinDigitalOutput[] ledArray = { pin00, pin01, pin02, pin03, pin04, pin05, pin06, pin07 }; System.out.println("Down an Up"); // Down Thread.sleep(1000); for (int i=0; i<ledArray.length; i++) { ledArray[i].toggle(); Thread.sleep(100); } Thread.sleep(1000); // Up for (int i=0; i<ledArray.length; i++) { ledArray[ledArray.length - 1 - i].toggle(); Thread.sleep(100); } System.out.println("One only"); // Down Thread.sleep(1000); for (int i=0; i<ledArray.length; i++) { oneOnly(ledArray, ledArray[i]); Thread.sleep(100); } Thread.sleep(1000); // Up for (int i=0; i<ledArray.length; i++) { oneOnly(ledArray, ledArray[ledArray.length - 1 - i]); Thread.sleep(100); } System.out.println("Messy..."); Thread.sleep(1000); // Big mess for (int i=0; i<1000; i++) { int idx = (int)(Math.random() * 8); ledArray[idx].toggle(); Thread.sleep(50); } System.out.println("Down and Up, closing."); // Down Thread.sleep(500); for (int i=0; i<ledArray.length; i++) { oneOnly(ledArray, ledArray[i]); Thread.sleep(100); } // Up for (int i=0; i<ledArray.length; i++) { oneOnly(ledArray, ledArray[ledArray.length - 1 - i]); Thread.sleep(100); } System.out.println("Done."); Thread.sleep(1000); // Everything off for (int i=0; i<ledArray.length; i++) ledArray[i].low(); gpio.shutdown(); } private static void oneOnly(GpioPinDigitalOutput[] allLeds, GpioPinDigitalOutput theOneOn) { for (int i=0; i<allLeds.length; i++) { if (allLeds[i].equals(theOneOn)) allLeds[i].high(); else allLeds[i].low(); } } }
12nosanshiro-pi4j-sample
GPIO.01/src/gpio01/GPIO08led.java
Java
mit
3,172
package gpio01; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class GPIO02led { public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - pin 00 & 02 ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #00 & #02 as an output pin and turn on final GpioPinDigitalOutput pin00 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "RedLed", PinState.HIGH); final GpioPinDigitalOutput pin02 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "GreenLed", PinState.HIGH); Thread.sleep(1000); System.out.println("Blinking red fast..."); for (int i=0; i<100; i++) { pin00.toggle(); Thread.sleep(50); } System.out.println("Blinking green fast..."); for (int i=0; i<100; i++) { pin02.toggle(); Thread.sleep(50); } pin00.low(); pin02.low(); Thread.sleep(1000); pin00.high(); System.out.println("Blinking red & green fast..."); for (int i=0; i<100; i++) { pin00.toggle(); pin02.toggle(); Thread.sleep(50); } pin00.high(); pin02.low(); Thread.sleep(100); pin02.high(); Thread.sleep(1000); pin00.low(); pin02.low(); Thread.sleep(100); pin00.pulse(500, true); // set second argument to 'true' use a blocking call pin02.pulse(500, true); // set second argument to 'true' use a blocking call Thread.sleep(100); pin00.pulse(500, false); // set second argument to 'true' use a blocking call Thread.sleep(100); pin02.pulse(500, false); // set second argument to 'true' use a blocking call Thread.sleep(1000); // All on pin00.high(); pin02.high(); Thread.sleep(1000); pin00.low(); pin02.low(); // stop all GPIO activity/threads by shutting down the GPIO controller // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks) gpio.shutdown(); } }
12nosanshiro-pi4j-sample
GPIO.01/src/gpio01/GPIO02led.java
Java
mit
2,183
package gpio01; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class SpeedTest { public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - Speed test."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #01 as an output pin and turn on final GpioPinDigitalOutput pin01 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "One", PinState.LOW); final GpioPinDigitalOutput pin02 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "Two", PinState.LOW); final GpioPinDigitalOutput pin03 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03, "Three", PinState.LOW); Thread.sleep(1000); long before = System.currentTimeMillis(); pin01.toggle(); long after = System.currentTimeMillis(); System.out.println("Toggle took " + Long.toString(after - before) + " ms."); Thread.sleep(500); System.out.println("Pulse..."); for (int i=0; i<100; i++) { pin01.pulse(75, false); // set second argument to 'true' use a blocking call pin02.pulse(75, false); // set second argument to 'true' use a blocking call pin03.pulse(75, false); // set second argument to 'true' use a blocking call Thread.sleep(100); // 1/10 s } System.out.println("Done"); pin01.low(); // Off gpio.shutdown(); } }
12nosanshiro-pi4j-sample
GPIO.01/src/gpio01/SpeedTest.java
Java
mit
1,539
#!/bin/bash echo Blinking 2 leds CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP gpio01.GPIO02led
12nosanshiro-pi4j-sample
GPIO.01/run2
Shell
mit
110
#!/bin/bash echo Interactive LED CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP rgbled.RGBLed
12nosanshiro-pi4j-sample
RGB-Led/run
Shell
mit
107
package rgbled; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import java.io.BufferedReader; import java.io.InputStreamReader; public class RGBLed { private static final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); public static String userInput(String prompt) { String retString = ""; System.err.print(prompt); try { retString = stdin.readLine(); } catch(Exception e) { System.out.println(e); String s; try { s = userInput("<Oooch/>"); } catch(Exception exception) { exception.printStackTrace(); } } return retString; } public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - pin 00, 01 & 02 ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalOutput greenPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "green", PinState.LOW); final GpioPinDigitalOutput bluePin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "blue", PinState.LOW); final GpioPinDigitalOutput redPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "red", PinState.LOW); /* * yellow = R+G * cyan = G+B * magenta = R+B * white = R+G+B */ boolean go = true; while (go) { String s = userInput("R, G, B, or QUIT > "); if ("R".equals(s.toUpperCase())) redPin.toggle(); else if ("G".equals(s.toUpperCase())) greenPin.toggle(); else if ("B".equals(s.toUpperCase())) bluePin.toggle(); else if ("QUIT".equals(s.toUpperCase()) || "Q".equals(s.toUpperCase())) go = false; else System.out.println("Unknown command [" + s + "]"); } // Switch them off redPin.low(); greenPin.low(); bluePin.low(); // stop all GPIO activity/threads by shutting down the GPIO controller // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks) gpio.shutdown(); } }
12nosanshiro-pi4j-sample
RGB-Led/src/rgbled/RGBLed.java
Java
mit
2,260
package relay; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class RelayManager { private final GpioController gpio = GpioFactory.getInstance(); private final GpioPinDigitalOutput pin17; private final GpioPinDigitalOutput pin18; public RelayManager() { System.out.println("GPIO Control - pin 00/#17 and 01/#18 ... started."); System.out.println("(Labelled #17 an #18 on the cobbler.)"); // For a relay it seems that HIGH means NC (Normally Closed)... pin17 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "Relay1", PinState.HIGH); pin18 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "Relay2", PinState.HIGH); } public void set(String device, String status) { GpioPinDigitalOutput pin = ("01".equals(device)?pin17:pin18); if ("on".equals(status)) pin.low(); else pin.high(); } public void shutdown() { gpio.shutdown(); } }
12nosanshiro-pi4j-sample
Relay.by.http/src/relay/RelayManager.java
Java
mit
1,064
package httpserver; import com.sun.speech.freetts.Voice; import com.sun.speech.freetts.VoiceManager; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import relay.RelayManager; /** * Dedicated HTTP Server. * This is NOT J2EE Compliant, not even CGI. * * Runs the communication between an HTTP client and the * features of the Data server to be displayed remotely. * * Comes with a speech option using "freeTTS" (see http://freetts.sourceforge.net/docs/index.php) */ public class StandaloneHTTPServer { private static boolean verbose = false; private static boolean speak = false; private static RelayManager rm; private VoiceManager voiceManager = VoiceManager.getInstance(); private static Voice voice; private final static String VOICENAME = "kevin16"; public StandaloneHTTPServer() {} public StandaloneHTTPServer(String[] prms) { try { rm = new RelayManager(); } catch (Exception ex) { System.err.println("You're not on the PI, hey?"); ex.printStackTrace(); } // Bind the server String machineName = "localhost"; String port = "9999"; machineName = System.getProperty("http.host", machineName); port = System.getProperty("http.port", port); System.out.println("HTTP Host:" + machineName); System.out.println("HTTP Port:" + port); System.out.println("\nOptions are -verbose=y|[n], -speak=y|[n]"); if (prms != null && prms.length > 0) { for (int i=0; i<prms.length; i++) { // System.out.println("Parameter[" + i + "]=" + prms[i]); if (prms[i].startsWith("-verbose=")) { verbose = prms[i].substring("-verbose=".length()).equals("y"); } else if (prms[i].startsWith("-speak=")) { speak = prms[i].substring("-speak=".length()).equals("y"); } // System.out.println("verbose=" + verbose); } } int _port = 0; try { _port = Integer.parseInt(port); } catch (NumberFormatException nfe) { throw nfe; } if (speak) { voice = voiceManager.getVoice(VOICENAME); voice.allocate(); } if (verbose) System.out.println("Server running from [" + System.getProperty("user.dir") + "]"); // Infinite loop try { ServerSocket ss = new ServerSocket(_port); while (true) { Socket client = ss.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(new OutputStreamWriter(client.getOutputStream())); String line; while ((line = in.readLine()) != null) { if (line.length() == 0) break; else if (line.startsWith("POST /exit") || line.startsWith("GET /exit")) { System.out.println("Received an exit signal"); System.exit(0); } else if (line.startsWith("POST /") || line.startsWith("GET /")) { manageRequest(line, out); } if (verbose) System.out.println("Read:[" + line + "]"); } // out.println(generateContent()); out.flush(); out.close(); in.close(); client.close(); } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } private void manageRequest(String request, PrintWriter out) { out.println(generateContent(request)); } private String generateContent(String request) { String str = ""; // "Content-Type: text/xml\r\n\r\n"; // System.out.println("Managing request [" + request + "]"); String[] elements = request.split(" "); if (elements[0].equals("GET")) { String[] parts = elements[1].split("\\?"); if (parts.length != 2) { String fileName = parts[0]; File data = new File("." + fileName); if (data.exists()) { try { BufferedReader br = new BufferedReader(new FileReader(data)); String line = ""; while (line != null) { line = br.readLine(); if (line != null) str += (line + "\n"); } br.close(); } catch (Exception ex) { ex.printStackTrace(); } } else str = "- There is no parameter is this query -"; } else { if (request.startsWith("GET /relay-access")) { System.out.println("--> " + request); String dev = ""; String status = ""; String[] params = parts[1].split("&"); for (String nv : params) { String[] nvPair = nv.split("="); // System.out.println(nvPair[0] + " = " + nvPair[1]); if (nvPair[0].equals("dev")) dev = nvPair[1]; else if (nvPair[0].equals("status")) status = nvPair[1]; } System.out.println("Setting [" + dev + "] to [" + status + "]"); if (("01".equals(dev) || "02".equals(dev)) && ("on".equals(status) || "off".equals(status))) { if (speak) voice.speak("Turning light " + ("01".equals(dev)?"one":"two") + ", " + status + "!"); try { rm.set(dev, status); } catch (Exception ex) { System.err.println(ex.toString()); } str = "200 OK\r\n"; } else { System.out.println("Unknown dev/status [" + dev + "/" + status + "]"); } } } } else str = "- Not managed -"; return str; } public static void shutdown() { rm.shutdown(); rm.set("01", "off"); rm.set("02", "off"); if (speak) voice.deallocate(); } /** * * @param args see usage */ public static void main(String[] args) { System.out.println("Starting tiny dedicated server"); System.out.println("Use [Ctrl] + [C] to stop it, or POST the following request:"); System.out.println("http://localhost:" + System.getProperty("http.port", "9999") + "/exit"); System.out.println("Data are available at:"); System.out.println("http://localhost:" + System.getProperty("http.port", "9999")); System.out.println("----------------------------------"); if (isHelpRequired(args)) { System.out.println("Usage is: java " + new StandaloneHTTPServer().getClass().getName() + " prms"); System.out.println("\twhere prms can be:"); System.out.println("\t-?\tDisplay this message"); System.out.println("\t-verbose=[y|n] - default is n"); System.out.println("The following variables can be defined in the command line (before the class name):"); System.out.println("\t-Dhttp.port=[port number]\tThe HTTP port to listen to, 9999 by default"); System.out.println("\t-Dhttp.host=[hostname] \tThe HTTP host to bind, localhost by default"); System.out.println("Example:"); System.out.println("java -Dhttp.port=6789 -Dhttp.host=localhost " + new StandaloneHTTPServer().getClass().getName()); System.exit(0); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("\nShutting down nicely..."); shutdown(); } }); new StandaloneHTTPServer(args); } private static boolean isHelpRequired(String[] args) { boolean ret = false; if (args != null) { for (int i=0; i<args.length; i++) { if (args[i].toUpperCase().equals("-H") || args[i].toUpperCase().equals("-HELP") || args[i].toUpperCase().equals("HELP") || args[i].equals("?") || args[i].equals("-?")) { ret = true; break; } } } return ret; } }
12nosanshiro-pi4j-sample
Relay.by.http/src/httpserver/StandaloneHTTPServer.java
Java
mit
8,202
package httpserver; import java.io.EOFException; import java.net.HttpURLConnection; import java.net.SocketException; import java.net.URL; public class SmallClient { public static void main(String[] args) throws Exception { int responseCode = 0; try { URL url = new URL("http://raspberrypi:9999/relay-access?dev=01&status=off"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); responseCode = conn.getResponseCode(); System.out.println("Done. (" + responseCode + ")"); } catch (EOFException eofe) { System.out.println("EOFException"); // That's ok, nothing is returned } catch (SocketException se) { System.out.println("SocketException"); // OK too. } catch (Exception ex) { ex.printStackTrace(); } System.out.println("Response Code:" + responseCode); } }
12nosanshiro-pi4j-sample
Relay.by.http/src/httpserver/SmallClient.java
Java
mit
917
var set = function(device, state) { request(device, state); }; var SERVICE_ROOT = "/relay-access"; var request = function(pin, status) { var restRequest = SERVICE_ROOT + "?dev=" + pin + "&status=" + status; var ajax = new XMLHttpRequest(); ajax.open("GET", restRequest, false); ajax.send(null); };
12nosanshiro-pi4j-sample
Relay.by.http/web/relay.js
JavaScript
mit
310
<!DOCTYPE html> <html> <head> <title>Relay over the Internet</title> <link rel="stylesheet" href="./stylesheet.css" type="text/css"/> <script type="text/javascript" src="relay.js"></script> </head> <body> <h1>Home Automation <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcShXziEYSrwRD_qhgn29_PZsGBBTcrqty5O3dTViH1OpylgCpiQBg" alt="Raspberry PI" style="vertical-align:middle;" width="51" height="62"></h1> Choose below. <p> <table style="margin-left: auto; margin-right: auto;" cellspacing="10"> <!-- style="margin: auto;" --> <tr> <td><button onClick="set('01', 'on');">1 - On</button></td> <td><button onClick="set('01', 'off');">1 - Off</button></td> <td><button onClick="set('02', 'on');">2 - On</button></td> <td><button onClick="set('02', 'off');">2 - Off</button></td> </tr> </table> </p> <hr> <address>Oliv did it</address> </body> </html>
12nosanshiro-pi4j-sample
Relay.by.http/web/index.html
HTML
mit
978
body { color : blue; font-weight: normal; font-size: 10pt; font-family: Verdana, Helvetica, Geneva; background-position: top left; background-repeat: repeat } h1 { color: silver; font-style: italic; font-size: 26pt; font-family: Verdana, Arial, Helvetica, Geneva; padding-left: 5pt } h2 { color: silver; font-size: 12pt; font-family: Verdana, Arial, Helvetica, Geneva } h3 { color: silver; font-style: italic; font-weight: bold; font-size: 11pt; font-family: Verdana, Arial, Helvetica, Geneva; } h4 { color: silver; font-style: italic; font-weight: bold; font-size: 10pt; font-family: Verdana, Arial, Helvetica, Geneva; } h5 { color: silver; font-style: normal; font-weight: bold; font-size: 10pt; font-family: Arial, Helvetica, Geneva; } h6 { font-style: italic; font-weight: normal; font-size: 10pt; font-family: Verdana, Arial, Helvetica, Geneva; } li { font-weight: normal; font-size: 10pt; font-family: Verdana, Helvetica, Geneva; } dt { font-size: 10pt; font-weight: bold; font-family: Verdana, Arial, Helvetica, Geneva; } dd { font-size: 10pt; font-weight: normal; font-family: Verdana, Arial, Helvetica, Geneva; } p { font-size: 10pt; font-weight: normal; font-family: Verdana, Helvetica, Geneva; } td { font-size: 10pt; font-family: Arial, Helvetica, Geneva; } small { font-size: 8pt; font-family: Verdana, Arial, Helvetica, Geneva; } blockquote { font-style: italic; font-size: 10pt; font-family: Verdana, Arial, Helvetica, Geneva; } em { font-size: 10pt; font-style: italic; font-weight: bold; font-family: Verdana, Arial, Helvetica, Geneva } pre { font-size: 9pt; font-family: "Source Code Pro", "Courier New", Helvetica, Geneva; background-color: #d3d3d3; } address { font-size: 8pt; font-family: Verdana, Arial, Helvetica, Geneva; } .red { color:red; } a:link { color : #0000A0} a:active { color: #8080FF} a:visited { color : #8080FF}
12nosanshiro-pi4j-sample
Relay.by.http/web/stylesheet.css
CSS
mit
2,066
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/freetts.jar sudo java -cp $CP httpserver.StandaloneHTTPServer $*
12nosanshiro-pi4j-sample
Relay.by.http/start.server
Shell
mit
139
#!/bin/sh # This is a shell archive (produced by GNU sharutils 4.2.1). # To extract the files from this archive, save it to some FILE, remove # everything before the `!/bin/sh' line above, then type `sh FILE'. # # Existing files will *not* be overwritten unless `-c' is specified. # # This shar contains: # length mode name # ------ ---------- ------------------------------------------ # 51811 -rw-rw-r-- jsapi.jar # more <<- xxxFOOxxx Sun Microsystems, Inc. Binary Code License Agreement READ THE TERMS OF THIS AGREEMENT AND ANY PROVIDED SUPPLEMENTAL LICENSE TERMS (COLLECTIVELY "AGREEMENT") CAREFULLY BEFORE OPENING THE SOFTWARE MEDIA PACKAGE. BY OPENING THE SOFTWARE MEDIA PACKAGE, YOU AGREE TO THE TERMS OF THIS AGREEMENT. IF YOU ARE ACCESSING THE SOFTWARE ELECTRONICALLY, INDICATE YOUR ACCEPTANCE OF THESE TERMS BY SELECTING THE "ACCEPT" BUTTON AT THE END OF THIS AGREEMENT. IF YOU DO NOT AGREE TO ALL THESE TERMS, PROMPTLY RETURN THE UNUSED SOFTWARE TO YOUR PLACE OF PURCHASE FOR A REFUND OR, IF THE SOFTWARE IS ACCESSED ELECTRONICALLY, SELECT THE "DECLINE" BUTTON AT THE END OF THIS AGREEMENT. 1. LICENSE TO USE. Sun grants you a non-exclusive and non-transferable license for the internal use only of the accompanying software and documentation and any error corrections provided by Sun (collectively "Software"), by the number of users and the class of computer hardware for which the corresponding fee has been paid. 2. RESTRICTIONS. Software is confidential and copyrighted. Title to Software and all associated intellectual property rights is retained by Sun and/or its licensors. Except as specifically authorized in any Supplemental License Terms, you may not make copies of Software, other than a single copy of Software for archival purposes. Unless enforcement is prohibited by applicable law, you may not modify, decompile, or reverse engineer Software. You acknowledge that Software is not designed, licensed or intended for use in the design, construction, operation or maintenance of any nuclear facility. Sun disclaims any express or implied warranty of fitness for such uses. No right, title or interest in or to any trademark, service mark, logo or trade name of Sun or its licensors is granted under this Agreement. 3. LIMITED WARRANTY. Sun warrants to you that for a period of ninety (90) days from the date of purchase, as evidenced by a copy of the receipt, the media on which Software is furnished (if any) will be free of defects in materials and workmanship under normal use. Except for the foregoing, Software is provided "AS IS". Your exclusive remedy and Sun's entire liability under this limited warranty will be at Sun's option to replace Software media or refund the fee paid for Software. 4. DISCLAIMER OF WARRANTY. UNLESS SPECIFIED IN THIS AGREEMENT, ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT THESE DISCLAIMERS ARE HELD TO BE LEGALLY INVALID. 5. LIMITATION OF LIABILITY. TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR SPECIAL, INDIRECT, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF OR RELATED TO THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. In no event will Sun's liability to you, whether in contract, tort (including negligence), or otherwise, exceed the amount paid by you for Software under this Agreement. The foregoing limitations will apply even if the above stated warranty fails of its essential purpose. 6. Termination. This Agreement is effective until terminated. You may terminate this Agreement at any time by destroying all copies of Software. This Agreement will terminate immediately without notice from Sun if you fail to comply with any provision of this Agreement. Upon Termination, you must destroy all copies of Software. 7. Export Regulations. All Software and technical data delivered under this Agreement are subject to US export control laws and may be subject to export or import regulations in other countries. You agree to comply strictly with all such laws and regulations and acknowledge that you have the responsibility to obtain such licenses to export, re-export, or import as may be required after delivery to you. 8. U.S. Government Restricted Rights. If Software is being acquired by or on behalf of the U.S. Government or by a U.S. Government prime contractor or subcontractor (at any tier), then the Government's rights in Software and accompanying documentation will be only as set forth in this Agreement; this is in accordance with 48 CFR 227.7201 through 227.7202-4 (for Department of Defense (DOD) acquisitions) and with 48 CFR 2.101 and 12.212 (for non-DOD acquisitions). 9. Governing Law. Any action related to this Agreement will be governed by California law and controlling U.S. federal law. No choice of law rules of any jurisdiction will apply. 10. Severability. If any provision of this Agreement is held to be unenforceable, this Agreement will remain in effect with the provision omitted, unless omission would frustrate the intent of the parties, in which case this Agreement will immediately terminate. 11. Integration. This Agreement is the entire agreement between you and Sun relating to its subject matter. It supersedes all prior or contemporaneous oral or written communications, proposals, representations and warranties and prevails over any conflicting or additional terms of any quote, order, acknowledgment, or other communication between the parties relating to its subject matter during the term of this Agreement. No modification of this Agreement will be binding, unless in writing and signed by an authorized representative of each party. JAVA(TM) SPEECH API (JSAPI) SPECIFICATION IMPLEMETATION, VERSION 1.0 SUPPLEMENTAL LICENSE TERMS These supplemental license terms ("Supplemental Terms") add to or modify the terms of the Binary Code License Agreement (collectively, the "Agreement"). Capitalized terms not defined in these Supplemental Terms shall have the same meanings ascribed to them in the Agreement. These Supplemental Terms shall supersede any inconsistent or conflicting terms in the Agreement, or in any license contained within the Software. 1. Software Internal Use and Development License Grant. Subject to the terms and conditions of this Agreement, including, but not limited to Section 3 (Java(TM) Technology Restrictions) of these Supplemental Terms, Sun grants you a non-exclusive, non-transferable, limited license to reproduce internally and use internally the binary form of the Software, complete and unmodified, for the sole purpose of designing, developing and testing your Java applets and applications ("Programs"). 2. License to Distribute Software. In addition to the license granted in Section 1 (Software Internal Use and Development License Grant) of these Supplemental Terms, subject to the terms and conditions of this Agreement, including but not limited to Section 3 (Java Technology Restrictions), Sun grants you a non-exclusive, non-transferable, limited license to reproduce and distribute the Software in binary form only, provided that you (i) distribute the Software complete and unmodified and only bundled as part of your Programs, (ii) do not distribute additional software intended to replace any component(s) of the Software, (iii) do not remove or alter any proprietary legends or notices contained in the Software, (iv) only distribute the Software subject to a license agreement that protects Sun's interests consistent with the terms contained in this Agreement, and (v) agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software. 3. Java Technology Restrictions. You may not modify the Java Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the Java Platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation. 4. Trademarks and Logos. You acknowledge and agree as between you and Sun that Sun owns the SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET trademarks and all SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET-related trademarks, service marks, logos and other brand designations ("Sun Marks"), and you agree to comply with the Sun Trademark and Logo Usage Requirements currently located at http://www.sun.com/policies/trademarks. Any use you make of the Sun Marks inures to Sun's benefit. 5. Source Code. Software may contain source code that is provided solely for reference purposes pursuant to the terms of this Agreement. Source code may not be redistributed unless expressly provided for in this Agreement. 6. Termination for Infringement. Either party may terminate this Agreement immediately should any Software become, or in either party's opinion be likely to become, the subject of a claim of infringement of any intellectual property right. For inquiries please contact: Sun Microsystems, Inc. 901 San Antonio Road, Palo Alto, California 94303 (LFI#108931/Form ID#011801) xxxFOOxxx echo "Accept (y/n)?: " read ans if [ "$ans" != "y" ] then echo 'failed to accept license' exit 1 fi save_IFS="${IFS}" IFS="${IFS}:" gettext_dir=FAILED locale_dir=FAILED first_param="$1" for dir in $PATH do if test "$gettext_dir" = FAILED && test -f $dir/gettext \ && ($dir/gettext --version >/dev/null 2>&1) then set `$dir/gettext --version 2>&1` if test "$3" = GNU then gettext_dir=$dir fi fi if test "$locale_dir" = FAILED && test -f $dir/shar \ && ($dir/shar --print-text-domain-dir >/dev/null 2>&1) then locale_dir=`$dir/shar --print-text-domain-dir` fi done IFS="$save_IFS" if test "$locale_dir" = FAILED || test "$gettext_dir" = FAILED then echo=echo else TEXTDOMAINDIR=$locale_dir export TEXTDOMAINDIR TEXTDOMAIN=sharutils export TEXTDOMAIN echo="$gettext_dir/gettext -s" fi if touch -am -t 200112312359.59 $$.touch >/dev/null 2>&1 && test ! -f 200112312359.59 -a -f $$.touch; then shar_touch='touch -am -t $1$2$3$4$5$6.$7 "$8"' elif touch -am 123123592001.59 $$.touch >/dev/null 2>&1 && test ! -f 123123592001.59 -a ! -f 123123592001.5 -a -f $$.touch; then shar_touch='touch -am $3$4$5$6$1$2.$7 "$8"' elif touch -am 1231235901 $$.touch >/dev/null 2>&1 && test ! -f 1231235901 -a -f $$.touch; then shar_touch='touch -am $3$4$5$6$2 "$8"' else shar_touch=: echo $echo 'WARNING: not restoring timestamps. Consider getting and' $echo "installing GNU \`touch', distributed in GNU File Utilities..." echo fi rm -f 200112312359.59 123123592001.59 123123592001.5 1231235901 $$.touch # if mkdir _sh01451; then $echo 'x -' 'creating lock directory' else $echo 'failed to create lock directory' exit 1 fi # ============= jsapi.jar ============== if test -f 'jsapi.jar' && test "$first_param" != -c; then $echo 'x -' SKIPPING 'jsapi.jar' '(file already exists)' else $echo 'x -' extracting 'jsapi.jar' '(binary)' sed 's/^X//' << 'SHAR_EOF' | uudecode && begin 600 jsapi.jar M4$L#!!0`"``(`#2=624````````````````)``0`345402U)3D8O_LH```,` M4$L'"``````"`````````%!+`P04``@`"``UG5DE````````````````%``` M`$U%5$$M24Y&+TU!3DE&15-4+DU&\TW,RTQ++2[1#4LM*L[,S[-2,-0SX.7B MY0(`4$L'"+)_`NX;````&0```%!+`P04``@`"``A@%0E```````````````` M)@```&IA=F%X+W-P965C:"]S>6YT:&5S:7,O4W!E86MA8FQE+F-L87-S._5O MUSX&9@9=!FYV!DYV!BY&!A$-39^LQ+)$_9S$O'3]X)*BS+QT:T8&%N?\E%1& M!GZ?S+Q4O]+<I-2BD,2D'*`(5W!^:5%RJELFB,,77)":F`V2T`.9P<C`G9Y: MXA7LZQ.26E'"R""`,-@_*2LU&2BD`!*JT"\N2$U-SM`OKLPKR4@MSBS6AQO$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F!!0!02P<(2:JXTHL```"I````4$L#!!0`"``( M`"6`5"4````````````````?````:F%V87@O<W!E96-H+T%U9&EO061A<'1E M<BYC;&%S<V6.S0[!4!2$YRHM]5.6)")V2.@+B$0D5@T+8G_;GG"E6JE6O):5 MQ,(#>"AQVI7$9B;SS<G)O#_/%S2,81FH&:@;:)@0*-5@0!?0!L.=@#Y5H4IF M`JUYZJMH[LMS0O'D**]2H+B(?!*P'!72*CVY%&^E&S`Q-U$:>[1466AFQW8@ MP[V]=H_D)0+M#-WLRYG(.]B_GP4Z_YVC+@F%%*./`B_D;4#N/)2UPJF;9Z`T M>J!XSVN35<]AC[7*7D#Y"U!+!PBF#0UXO0```/4```!02P,$%``(``@`)8!4 M)0```````````````!X```!J879A>"]S<&5E8V@O4W!E96-H17)R;W(N8VQA M<W,[]6_7/@9F!ET&`78&/G8&?BX&1@96$,'&P\#)P`XB.!@9F#4TPQ@91#5\ MLA++$O5S$O/2]8-+BC+STJU!XFPVF7F9)7:,#"S.^2FIC`S\/IEYJ7ZEN4FI M12&)23E`$:[@_-*BY%2W3!!'(+@@-34YP[6H*+](#V0@4`?"7+`P(X,$2*1" MOQBL5!])!X,B`Q/0>2``HH%N!))<0)XBD`:)LVIM9V#>"&0P,G`#22Z@,@8& M#086!G6P<@ZH<B6@.$B&34M[.P,+NGI9!E8&&:`(#]@:7@!02P<(F#WKV=4` M```F`0``4$L#!!0`"``(`"6`5"4````````````````=````:F%V87@O<W!E M96-H+T%U9&EO179E;G0N8VQA<W-=4$U+PT`0?9O4Q*;1^M%6!2_BI4W1X$VL M""(5"D4/$>^;9(E;VDU)D^)_\J(@%#SX`_Q1XB0I:-W#S)OW9MZP\_7]\0D= M)VB9V#71L*#!J%(P<[1NPX9E8P=U&TU4&1KMSG#$Y]P=<Q6Y7II(%?486NT_ M[+T_$D':&W0>&0Y*X=F=384(GMR^BJ02I69<2B73*X;Z=1;*N#\7*CW-NQDJ M-W$H&-B`Q"$-W&437R0/W!\3:WEQE@3B5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AGZ<Q$-:,0VTG+A'_A(8%J.(QJZ6BOPT^0N8I_,!12NTG%FR^6IMKI0I M:2/DOE/(\(1.@PJ!/;*O*;-*+>,B5<S(CE5_H'#^GZY%R2:=M,,7U':D!VP1 MU?R&Z*FI?R=^4?R%]/O)U`A9U6N(_!#&$!/GU1'&+SL7J`OP@;I^@H4.95>B MKWK\#U!+!PB::S\Q]0$``)$#``!02P,$%``(``@`E814)0`````````````` M`",```!J879A>"]S<&5E8V@O4W!E96-H4&5R;6ES<VEO;BYC;&%S<SOU;]<^ M!F8&708!=@8^=@9^+@9&!E80P<;#P,G`#B(X&!E$-7RR$LL2]7,2\]+U@TN* M,O/2K37#&!G4L8AC5\EFDYF766+'R,#BG)^2RLC`[Y.9E^I7FIN46A22F)0# M%.$*SB\M2DYURP1Q1(,+4E.3,P)2BW(SBXLS\_/T0*8R,LB"#2].32XMRBRI MU'=*+,Y,1BB"RE?H%X-UZZ,;PF#(P`3T&@B`:*#_@"07D*<$Y#,!:38M[>T, MS!N!+$8&;B#)!1:-8&!E"`.KYX"J5P8&&3.09M?2UMG.P(*N(8N!C2$#*,(# MMH@7`%!+!PAH6AZ'Z@```&0!``!02P$"%``4``@`"``TG5DE``````(````` M````"0`$````````````````````345402U)3D8O_LH``%!+`0(4`!0`"``( M`#6=626R?P+N&P```!D````4`````````````````#T```!-151!+4E.1B]- M04Y)1D535"Y-1E!+`0(4`!0`"``(`"&`5"405)./HP```,`````F```````` M`````````)H```!J879A>"]S<&5E8V@O<WEN=&AE<VES+U-P96%K86)L92YC M;&%S<U!+`0(4`!0`"``(`"&`5"4&K:P:3`0``"$(```K```````````````` M`)$!``!J879A>"]S<&5E8V@O<WEN=&AE<VES+U-P96%K86)L945V96YT+F-L M87-S4$L!`A0`%``(``@`(8!4)4/N>C$'`0``N`$``"X````````````````` M-@8``&IA=F%X+W-P965C:"]S>6YT:&5S:7,O4W!E86MA8FQE3&ES=&5N97(N M8VQA<W-02P$"%``4``@`"``RG5DET&/,,Q@"``#*!```*``````````````` M``"9!P``:F%V87@O<W!E96-H+W-Y;G1H97-I<R]3>6YT:&5S:7IE<BYC;&%S M<U!+`0(4`!0`"``(`"&`5"6SBT7AZ````$$!```J``````````````````<* M``!J879A>"]S<&5E8V@O<WEN=&AE<VES+TI334Q%>&-E<'1I;VXN8VQA<W-0 M2P$"%``4``@`"``A@%0E*"U&QLD````G`0``,`````````````````!'"P`` M:F%V87@O<W!E96-H+W-Y;G1H97-I<R]3>6YT:&5S:7IE<DQI<W1E;F5R+F-L M87-S4$L!`A0`%``(``@`(8!4)1,#ZCU.`0```P,``"T````````````````` M;@P``&IA=F%X+W-P965C:"]S>6YT:&5S:7,O4W!E86MA8FQE061A<'1E<BYC M;&%S<U!+`0(4`!0`"``(`"&`5"6DS*@D_@```,`!```O```````````````` M`!<.``!J879A>"]S<&5E8V@O<WEN=&AE<VES+U-Y;G1H97-I>F5R061A<'1E M<BYC;&%S<U!+`0(4`!0`"``(`'QM524\YZ$Y*`0``%@(```B```````````` M`````'(/``!J879A>"]S<&5E8V@O<WEN=&AE<VES+U9O:6-E+F-L87-S4$L! M`A0`%``(``@`(H!4)?R&?G&7`P``^`8``#``````````````````ZA,``&IA M=F%X+W-P965C:"]S>6YT:&5S:7,O4WEN=&AE<VEZ97)-;V1E1&5S8RYC;&%S M<U!+`0(4`!0`"``(`"*`5"7/IE;A]@$``!0#```M`````````````````-\7 M``!J879A>"]S<&5E8V@O<WEN=&AE<VES+U-Y;G1H97-I>F5R179E;G0N8VQA M<W-02P$"%``4``@`"`!#3E<EQLEV'ST!``!A`@``,@`````````````````P M&@``:F%V87@O<W!E96-H+W-Y;G1H97-I<R]3>6YT:&5S:7IE<E!R;W!E<G1I M97,N8VQA<W-02P$"%``4``@`"``B@%0E*!E/9;$!``!_`P``,0`````````` M``````#-&P``:F%V87@O<W!E96-H+W-Y;G1H97-I<R]3>6YT:&5S:7IE<E%U M975E271E;2YC;&%S<U!+`0(4`!0`"``(`"*`5"46TLJ"^@```,D!```O```` M`````````````-T=``!J879A>"]S<&5E8V@O<F5C;V=N:71I;VXO1&EC=&%T M:6]N1W)A;6UA<BYC;&%S<U!+`0(4`!0`"``(`"*`5"5?4OV*M@$``"(#```F M`````````````````#0?``!J879A>"]S<&5E8V@O<F5C;V=N:71I;VXO1W)A M;6UA<BYC;&%S<U!+`0(4`!0`"``(`"*`5"4,U_+S(P,``#,&```K```````` M`````````#XA``!J879A>"]S<&5E8V@O<F5C;V=N:71I;VXO1W)A;6UA<D5V M96YT+F-L87-S4$L!`A0`%``(``@`(H!4)8PK9[/=````1P$``"X````````` M````````NB0``&IA=F%X+W-P965C:"]R96-O9VYI=&EO;B]'<F%M;6%R3&ES M=&5N97(N8VQA<W-02P$"%``4``@`"``RG5DEQ(`Q`4,#``#@"```*0`````` M``````````#S)0``:F%V87@O<W!E96-H+W)E8V]G;FET:6]N+U)E8V]G;FEZ M97(N8VQA<W-02P$"%``4``@`"``B@%0E4H+57>P!```Z!```+P`````````` M``````"-*0``:F%V87@O<W!E96-H+W)E8V]G;FET:6]N+T=R86UM87)%>&-E M<'1I;VXN8VQA<W-02P$"%``4``@`"``B@%0EI)_YP.8```!%`0``+P`````` M``````````#6*P``:F%V87@O<W!E96-H+W)E8V]G;FET:6]N+U)E<W5L=%-T M871E17)R;W(N8VQA<W-02P$"%``4``@`"``B@%0E%C`CO_0```!\`0``,0`` M```````````````9+0``:F%V87@O<W!E96-H+W)E8V]G;FET:6]N+U)E8V]G M;FEZ97),:7-T96YE<BYC;&%S<U!+`0(4`!0`"``(`"*`5"51`-2Q(0(``,T% M```J`````````````````&PN``!J879A>"]S<&5E8V@O<F5C;V=N:71I;VXO M4G5L94=R86UM87(N8VQA<W-02P$"%``4``@`"``B@%0E[66L1Z,!```!!``` M+0````````````````#E,```:F%V87@O<W!E96-H+W)E8V]G;FET:6]N+U-P M96%K97)-86YA9V5R+F-L87-S4$L!`A0`%``(``@`(X!4)=I8)]H3`0``]P$` M`"T`````````````````XS(``&IA=F%X+W-P965C:"]R96-O9VYI=&EO;B]' M<F%M;6%R061A<'1E<BYC;&%S<U!+`0(4`!0`"``(`".`5"5B%?[E+@$``'," M```P`````````````````%$T``!J879A>"]S<&5E8V@O<F5C;V=N:71I;VXO M4F5C;V=N:7IE<D%D87!T97(N8VQA<W-02P$"%``4``@`"``C@%0E.7URU9$! M``#$`@``)0````````````````#=-0``:F%V87@O<W!E96-H+W)E8V]G;FET M:6]N+U)E<W5L="YC;&%S<U!+`0(4`!0`"``(`".`5"4APOA_!0$``)X!```M M`````````````````,$W``!J879A>"]S<&5E8V@O<F5C;V=N:71I;VXO4F5S M=6QT3&ES=&5N97(N8VQA<W-02P$"%``4``@`"``D@%0E!P3>_D@!``#)`@`` M+``````````````````A.0``:F%V87@O<W!E96-H+W)E8V]G;FET:6]N+U)E M<W5L=$%D87!T97(N8VQA<W-02P$"%``4``@`"``D@%0ER<,G_F0#```'!@`` M*@````````````````##.@``:F%V87@O<W!E96-H+W)E8V]G;FET:6]N+U)E M<W5L=$5V96YT+F-L87-S4$L!`A0`%``(``@`)(!4)>0?6J3O````2`$``",` M````````````````?SX``&IA=F%X+W-P965C:"]R96-O9VYI=&EO;B]2=6QE M+F-L87-S4$L!`A0`%``(``@`)(!4):JD/^@#!P``5PT``"<````````````` M````OS\``&IA=F%X+W-P965C:"]R96-O9VYI=&EO;B]2=6QE3F%M92YC;&%S M<U!+`0(4`!0`"``(`"2`5"6SA+_2P0,``#8'```K`````````````````!=' M``!J879A>"]S<&5E8V@O<F5C;V=N:71I;VXO4G5L95-E<75E;F-E+F-L87-S M4$L!`A0`%``(``@`)(!4);7;3+K+!0``!0L``"\`````````````````,4L` M`&IA=F%X+W-P965C:"]R96-O9VYI=&EO;B]2=6QE06QT97)N871I=F5S+F-L M87-S4$L!`A0`%``(``@`)(!4)0S67&_,`@``[00``"@````````````````` M65$``&IA=F%X+W-P965C:"]R96-O9VYI=&EO;B]2=6QE5&]K96XN8VQA<W-0 M2P$"%``4``@`"``D@%0ER?^V1H@$``#0"0``,0````````````````![5``` M:F%V87@O<W!E96-H+W)E8V]G;FET:6]N+U)E8V]G;FEZ97)-;V1E1&5S8RYC M;&%S<U!+`0(4`!0`"``(`"6`5"4!GENW004``!@+```H```````````````` M`&)9``!J879A>"]S<&5E8V@O<F5C;V=N:71I;VXO4G5L95!A<G-E+F-L87-S M4$L!`A0`%``(``@`)8!4);D0!8=W`P``VP8``"8`````````````````^5X` M`&IA=F%X+W-P965C:"]R96-O9VYI=&EO;B]2=6QE5&%G+F-L87-S4$L!`A0` M%``(``@`)8!4)9@$/OM?`P``X`8``"@`````````````````Q&(``&IA=F%X M+W-P965C:"]R96-O9VYI=&EO;B]2=6QE0V]U;G0N8VQA<W-02P$"%``4``@` M"``E@%0E#>KB?+L!``")`P``*@````````````````!Y9@``:F%V87@O<W!E M96-H+W)E8V]G;FET:6]N+T9I;F%L4F5S=6QT+F-L87-S4$L!`A0`%``(``@` M)8!4)0$!=C4P`0``10(``"X`````````````````C&@``&IA=F%X+W-P965C M:"]R96-O9VYI=&EO;B]&:6YA;%)U;&5297-U;'0N8VQA<W-02P$"%``4``@` M"``E@%0E<*4+^?P```#@`0``,P`````````````````8:@``:F%V87@O<W!E M96-H+W)E8V]G;FET:6]N+T9I;F%L1&EC=&%T:6]N4F5S=6QT+F-L87-S4$L! M`A0`%``(``@`)8!4):RJW.#3`0``%P,``"H`````````````````=6L``&IA M=F%X+W-P965C:"]R96-O9VYI=&EO;B]297-U;'14;VME;BYC;&%S<U!+`0(4 M`!0`"``(`"6`5"6V&GK"M`(``/X$```N`````````````````*!M``!J879A M>"]S<&5E8V@O<F5C;V=N:71I;VXO4F5C;V=N:7IE<D5V96YT+F-L87-S4$L! M`A0`%``(``@`)8!4)6>I:G#3````30$``#8`````````````````L'```&IA M=F%X+W-P965C:"]R96-O9VYI=&EO;B]296-O9VYI>F5R075D:6],:7-T96YE M<BYC;&%S<U!+`0(4`!0`"``(`"6`5"62S0O3"0$```L"```U```````````` M`````.=Q``!J879A>"]S<&5E8V@O<F5C;V=N:71I;VXO4F5C;V=N:7IE<D%U M9&EO061A<'1E<BYC;&%S<U!+`0(4`!0`"``(`"6`5"7W'?PIX@$``'H#```R M`````````````````%-S``!J879A>"]S<&5E8V@O<F5C;V=N:71I;VXO1W)A M;6UA<E-Y;G1A>$1E=&%I;"YC;&%S<U!+`0(4`!0`"``(`"6`5"5)]+;-E`$` M`%H#```S`````````````````)5U``!J879A>"]S<&5E8V@O<F5C;V=N:71I M;VXO4F5C;V=N:7IE<E!R;W!E<G1I97,N8VQA<W-02P$"%``4``@`"``E@%0E M6B":R-\"``"4!0``+0````````````````"*=P``:F%V87@O<W!E96-H+W)E M8V]G;FET:6]N+U-P96%K97)0<F]F:6QE+F-L87-S4$L!`A0`%``(``@`)8!4 M)8TARG5.`@``%00``#,`````````````````Q'H``&IA=F%X+W-P965C:"]R M96-O9VYI=&EO;B]296-O9VYI>F5R075D:6]%=F5N="YC;&%S<U!+`0(4`!0` M"``(`""`5"7$\35C-@L``+07```:`````````````````'-]``!J879A>"]S M<&5E8V@O0V5N=')A;"YC;&%S<U!+`0(4`!0`"``(`""`5"6/SAUEVP```#L! M```B`````````````````/&(``!J879A>"]S<&5E8V@O16YG:6YE17AC97!T M:6]N+F-L87-S4$L!`A0`%``(``@`((!4)7,#`SO0`P``3`@``"$````````` M````````'(H``&IA=F%X+W-P965C:"]%;F=I;F5-;V1E1&5S8RYC;&%S<U!+ M`0(4`!0`"``(`""`5"5I*ZQ5%`$``,T!```?`````````````````#N.``!J M879A>"]S<&5E8V@O5F]C86)-86YA9V5R+F-L87-S4$L!`A0`%``(``@`,IU9 M)77=TLS/`@``2`8``!<`````````````````G(\``&IA=F%X+W-P965C:"]7 M;W)D+F-L87-S4$L!`A0`%``(``@`((!4)1M-F?/8````,@$``"(````````` M````````L)(``&IA=F%X+W-P965C:"]3<&5E8VA%>&-E<'1I;VXN8VQA<W-0 M2P$"%``4``@`"``A@%0E86H"%\(````?`0``(`````````````````#8DP`` M:F%V87@O<W!E96-H+T5N9VEN94-E;G1R86PN8VQA<W-02P$"%``4``@`"``A M@%0E9`X!L*P```#J````'P````````````````#HE```:F%V87@O<W!E96-H M+T%U9&EO36%N86=E<BYC;&%S<U!+`0(4`!0`"``(`"&`5"7]RHHXW@```#D! M```A`````````````````.&5``!J879A>"]S<&5E8V@O075D:6]%>&-E<'1I M;VXN8VQA<W-02P$"%``4``@`"``A@%0EIYR2C$0"``#?`P``'@`````````` M```````.EP``:F%V87@O<W!E96-H+T5N9VEN945V96YT+F-L87-S4$L!`A0` M%``(``@`(8!4)2!GR(0F`@``%00``!X`````````````````GID``&IA=F%X M+W-P965C:"]3<&5E8VA%=F5N="YC;&%S<U!+`0(4`!0`"``(`#*=626K?::K M.0(``,0$```9`````````````````!"<``!J879A>"]S<&5E8V@O16YG:6YE M+F-L87-S4$L!`A0`%``(``@`(8!4)?M<G+[<````.0$``",````````````` M````D)X``&IA=F%X+W-P965C:"]%;F=I;F53=&%T945R<F]R+F-L87-S4$L! M`A0`%``(``@`(8!4)2_/:OS^````O`$``"$`````````````````O9\``&IA M=F%X+W-P965C:"]%;F=I;F5,:7-T96YE<BYC;&%S<U!+`0(4`!0`"``(`"&` M5"4H%+[X0@$``-L"```@``````````````````JA``!J879A>"]S<&5E8V@O M16YG:6YE061A<'1E<BYC;&%S<U!+`0(4`!0`"``(`"*`5"6%U/SXZP```%@! M```C`````````````````)JB``!J879A>"]S<&5E8V@O16YG:6YE4')O<&5R M=&EE<RYC;&%S<U!+`0(4`!0`"``(`"*`5"7]8W.QY````$,!```F```````` M`````````-:C``!J879A>"]S<&5E8V@O5F5N9&]R1&%T845X8V5P=&EO;BYC M;&%S<U!+`0(4`!0`"``(`"6`5"5)JKC2BP```*D````@```````````````` M``ZE``!J879A>"]S<&5E8V@O075D:6],:7-T96YE<BYC;&%S<U!+`0(4`!0` M"``(`"6`5"6F#0UXO0```/4````?`````````````````.>E``!J879A>"]S M<&5E8V@O075D:6]!9&%P=&5R+F-L87-S4$L!`A0`%``(``@`)8!4)9@]Z]G5 M````)@$``!X`````````````````\:8``&IA=F%X+W-P965C:"]3<&5E8VA% M<G)O<BYC;&%S<U!+`0(4`!0`"``(`"6`5"6W'BLM%0$``(T!```=```````` M`````````!*H``!J879A>"]S<&5E8V@O075D:6]%=F5N="YC;&%S<U!+`0(4 M`!0`"``(`":`5"4,;M+!A0(``$0$```=`````````````````'*I``!J879A M>"]S<&5E8V@O16YG:6YE3&ES="YC;&%S<U!+`0(4`!0`"``(`":`5"7<"CZ& MV@```$8!```?`````````````````$*L``!J879A>"]S<&5E8V@O16YG:6YE M0W)E871E+F-L87-S4$L!`A0`%``(``@`)H!4)9IK/S'U`0``D0,``",````` M````````````::T``&IA=F%X+W-P965C:"]%;F=I;F5%<G)O<D5V96YT+F-L M87-S4$L!`A0`%``(``@`E814)6A:'H?J````9`$``",````````````````` MKZ\``&IA=F%X+W-P965C:"]3<&5E8VA097)M:7-S:6]N+F-L87-S4$L%!@`` 0``!,`$P`8QD``.JP`````"]3 ` end SHAR_EOF (set 20 01 12 20 08 39 06 'jsapi.jar'; eval "$shar_touch") && chmod 0664 'jsapi.jar' || $echo 'restore of' 'jsapi.jar' 'failed' if ( md5sum --help 2>&1 | grep 'sage: md5sum \[' ) >/dev/null 2>&1 \ && ( md5sum --version 2>&1 | grep -v 'textutils 1.12' ) >/dev/null; then md5sum -c << SHAR_EOF >/dev/null 2>&1 \ || $echo 'jsapi.jar:' 'MD5 check failed' 38d26ea55db20966bb1d747f4027c224 jsapi.jar SHAR_EOF else shar_count="`LC_ALL= LC_CTYPE= LANG= wc -c < 'jsapi.jar'`" test 51811 -eq "$shar_count" || $echo 'jsapi.jar:' 'original size' '51811,' 'current size' "$shar_count!" fi fi rm -fr _sh01451 exit 0
12nosanshiro-pi4j-sample
Relay.by.http/lib/jsapi.sh
Shell
mit
84,305
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/javax.mail_1.1.0.0_1-4-4.jar CP=$CP:./lib/json.jar # java -classpath $CP relay.email.PIControllerMain $*
12nosanshiro-pi4j-sample
Relay.by.email/run
Shell
mit
179
@echo off @setlocal set JDEV_HOME=D:\Oracle\Middleware\11.1.1.7 set CP=.\classes set CP=%CP%;%JDEV_HOME%\oracle_common\modules\javax.mail.jar set CP=%CP%;..\lib\json.jar :: :: -Dverbose=true java -classpath %CP% relay.email.SampleMain %* @endlocal
12nosanshiro-pi4j-sample
Relay.by.email/run.bat
Batchfile
mit
248
package relay.gpio; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; public class GPIOController { private GpioController gpio = null; private OneRelay relay = null; public GPIOController() { this.gpio = GpioFactory.getInstance(); this.relay = new OneRelay(this.gpio, RaspiPin.GPIO_00, "Relay01"); } public void shutdown() { this.gpio.shutdown(); } public void switchRelay(boolean on) { if (on) relay.on(); else relay.off(); } }
12nosanshiro-pi4j-sample
Relay.by.email/src/relay/gpio/GPIOController.java
Java
mit
764
package relay.gpio; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; public class OneRelay { private GpioPinDigitalOutput led = null; private String name; public OneRelay(GpioController gpio, Pin pin, String name) { this.name = name; led = gpio.provisionDigitalOutputPin(pin, name, PinState.HIGH); // Begin HIGH for a relay } public void on() { if ("true".equals(System.getProperty("verbose", "false"))) System.out.println(this.name + " is on."); led.low(); } public void off() { if ("true".equals(System.getProperty("verbose", "false"))) System.out.println(this.name + " is off."); led.high(); } }
12nosanshiro-pi4j-sample
Relay.by.email/src/relay/gpio/OneRelay.java
Java
mit
769
package relay.gpio; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; public interface RaspberryPIEventListener { public void manageEvent(GpioPinDigitalStateChangeEvent event); }
12nosanshiro-pi4j-sample
Relay.by.email/src/relay/gpio/RaspberryPIEventListener.java
Java
mit
195
package relay; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.json.JSONObject; import relay.email.EmailReceiver; import relay.email.EmailSender; public class SampleMain { private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); private static boolean verbose = "true".equals(System.getProperty("verbose", "false")); /** * Invoked like: * java pi4j.email.SampleMain [-verbose] -send:google -receive:yahoo * * This will send emails using google, and receive using yahoo. * Do check the file email.properties for the different values associated with email servers. * * NO GPIO INTERACTION in this one. * * @param args See above */ public static void main(String[] args) { // String provider = "yahoo"; String providerSend = "oracle"; // String provider = "oracle"; // provider = "yahoo"; String providerReceive = "oracle"; // provider = "oracle"; for (int i=0; i<args.length; i++) { if ("-verbose".equals(args[i])) { verbose = true; System.setProperty("verbose", "true"); } else if (args[i].startsWith("-send:")) providerSend = args[i].substring("-send:".length()); else if (args[i].startsWith("-receive:")) providerReceive =args[i].substring("-receive:".length()); else if ("-help".equals(args[i])) { System.out.println("Usage:"); System.out.println(" java pi4j.email.SampleMain -verbose -send:google -receive:yahoo -help"); System.exit(0); } } final EmailSender sender = new EmailSender(providerSend); Thread senderThread = new Thread() { public void run() { try { for (int i=0; i<10; i++) { System.out.println("Sending..."); sender.send(new String[] { "olivier@lediouris.net", "webmaster@lediouris.net", "olivier.lediouris@gmail.com", "olivier_le_diouris@yahoo.com", "olivier.lediouris@oracle.com" }, "PI Request", "{ operation: 'see-attached-" + Integer.toString(i + 1) + "' }", "P8150115.JPG"); System.out.println("Sent."); Thread.sleep(60000L); // 1 minute } System.out.println("Exiting..."); sender.send(new String[] { "olivier@lediouris.net", "webmaster@lediouris.net", "olivier.lediouris@gmail.com", "olivier_le_diouris@yahoo.com", "olivier.lediouris@oracle.com" }, "PI Request", "{ operation: 'exit' }"); System.out.println("Bye."); } catch (Exception ex) { ex.printStackTrace(); } } }; senderThread.start(); // Bombarding if (args.length > 1) providerSend = args[1]; EmailReceiver receiver = new EmailReceiver(providerReceive); // For Google, pop must be explicitely enabled at the account level try { boolean keepLooping = true; while (keepLooping) { List<String> received = receiver.receive(); if (verbose || received.size() > 0) System.out.println(SDF.format(new Date()) + " - Retrieved " + received.size() + " message(s)."); for (String s : received) { // System.out.println(s); String operation = ""; try { JSONObject json = new JSONObject(s); operation = json.getString("operation"); } catch (Exception ex) { System.err.println(ex.getMessage()); System.err.println("Message is [" + s + "]"); } if ("exit".equals(operation)) { keepLooping = false; System.out.println("Will exit next batch."); // break; } else { System.out.println("Operation: [" + operation + "], sent for processing."); try { Thread.sleep(1000L); } catch (InterruptedException ie) { ie.printStackTrace(); } } } } System.out.println("Done."); } catch (Exception ex) { ex.printStackTrace(); } } }
12nosanshiro-pi4j-sample
Relay.by.email/src/relay/SampleMain.java
Java
mit
4,644
package relay.email; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Set; import javax.mail.Address; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.InternetAddress; import javax.mail.search.AndTerm; import javax.mail.search.FlagTerm; import javax.mail.search.FromStringTerm; import javax.mail.search.OrTerm; import javax.mail.search.SearchTerm; import javax.mail.search.SubjectTerm; public class EmailReceiver { private static String protocol; private static int outgoingPort; private static int incomingPort; private static String username; private static String password; private static String outgoing; private static String incoming; private static String replyto; private static boolean smtpauth; private static String sendEmailsTo; private static String acceptEmailsFrom; private static String acceptSubject; private static String ackSubject; private static boolean verbose = "true".equals(System.getProperty("verbose", "false")); private EmailSender emailSender = null; // For Ack private String provider = null; public EmailReceiver(String provider) throws RuntimeException { this.provider = provider; EmailReceiver.protocol = ""; EmailReceiver.outgoingPort = 0; EmailReceiver.incomingPort = 0; EmailReceiver.username = ""; EmailReceiver.password = ""; EmailReceiver.outgoing = ""; EmailReceiver.incoming = ""; EmailReceiver.replyto = ""; EmailReceiver.smtpauth = false; EmailReceiver.sendEmailsTo = ""; EmailReceiver.acceptEmailsFrom = ""; EmailReceiver.acceptSubject = ""; EmailReceiver.ackSubject = ""; Properties props = new Properties(); String propFile = "email.properties"; try { FileInputStream fis = new FileInputStream(propFile); props.load(fis); } catch (Exception e) { System.out.println("email.properies file problem..."); throw new RuntimeException("File not found:email.properies"); } EmailReceiver.sendEmailsTo = props.getProperty("pi.send.emails.to"); EmailReceiver.acceptEmailsFrom = props.getProperty("pi.accept.emails.from"); EmailReceiver.acceptSubject = props.getProperty("pi.email.subject"); EmailReceiver.ackSubject = props.getProperty("pi.ack.subject"); EmailReceiver.protocol = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.protocol"); EmailReceiver.outgoingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server.port", "0")); EmailReceiver.incomingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server.port", "0")); EmailReceiver.username = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.username", ""); EmailReceiver.password = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.password", ""); EmailReceiver.outgoing = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server", ""); EmailReceiver.incoming = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server", ""); EmailReceiver.replyto = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.replyto", ""); EmailReceiver.smtpauth = "true".equals(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.smtpauth", "false")); if (verbose) { System.out.println("Protocol:" + EmailReceiver.protocol); System.out.println("Usr/pswd:" + EmailReceiver.username + "/" + EmailReceiver.password); } } private static SearchTerm[] buildSearchTerm(String str) { String[] sa = str.split(","); List<SearchTerm> lst = new ArrayList<SearchTerm>(); for (String s : sa) lst.add(new FromStringTerm(s.trim())); SearchTerm[] sta = new SearchTerm[lst.size()]; sta = lst.toArray(sta); return sta; } private Properties setProps() { Properties props = new Properties(); props.put("mail.debug", verbose?"true":"false"); // TASK smtp should be irrelevant for a receiver props.put("mail.smtp.host", EmailReceiver.outgoing); props.put("mail.smtp.port", Integer.toString(EmailReceiver.outgoingPort)); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // See http://www.oracle.com/technetwork/java/faq-135477.html#yahoomail // props.put("mail.smtp.starttls.required", "true"); props.put("mail.smtp.ssl.enable", "true"); if ("pop3".equals(EmailReceiver.protocol)) { props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.pop3.socketFactory.fallback", "false"); props.setProperty("mail.pop3.port", Integer.toString(EmailReceiver.incomingPort)); props.setProperty("mail.pop3.socketFactory.port", Integer.toString(EmailReceiver.incomingPort)); } if ("imap".equals(protocol)) { props.setProperty("mail.imap.starttls.enable", "false"); // Use SSL props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.imap.socketFactory.fallback", "false"); props.setProperty("mail.imap.port", Integer.toString(EmailReceiver.incomingPort)); props.setProperty("mail.imap.socketFactory.port", Integer.toString(EmailReceiver.incomingPort)); props.setProperty("mail.imaps.class", "com.sun.mail.imap.IMAPSSLStore"); } return props; } public boolean isAuthRequired() { return EmailReceiver.smtpauth; } public String getUserName() { return EmailReceiver.username; } public String getPassword() { return EmailReceiver.password; } public String getReplyTo() { return EmailReceiver.replyto; } public String getIncomingServer() { return EmailReceiver.incoming; } public String getOutgoingServer() { return EmailReceiver.outgoing; } public List<String> receive() throws Exception { return receive(null); } public List<String> receive(String dir) throws Exception { if (verbose) System.out.println("Receiving..."); List<String> messList = new ArrayList<String>(); Store store = null; Folder folder = null; try { // Properties props = System.getProperties(); Properties props = setProps(); if (verbose) { Set<Object> keys = props.keySet(); for (Object o : keys) System.out.println(o.toString() + ":" + props.get(o).toString()); } if (verbose) System.out.println("Getting session..."); // Session session = Session.getInstance(props, null); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); session.setDebug(verbose); if (verbose) System.out.println("Session established."); store = session.getStore(EmailReceiver.protocol); if (EmailReceiver.incomingPort == 0) store.connect(EmailReceiver.incoming, EmailReceiver.username, EmailReceiver.password); else store.connect(EmailReceiver.incoming, EmailReceiver.incomingPort, EmailReceiver.username, EmailReceiver.password); if (verbose) System.out.println("Connected to store"); folder = store.getDefaultFolder(); if (folder == null) throw new RuntimeException("No default folder"); folder = store.getFolder("INBOX"); if (folder == null) throw new RuntimeException("No INBOX"); folder.open(Folder.READ_WRITE); if (verbose) System.out.println("Connected... filtering, please wait."); SearchTerm st = new AndTerm(new SearchTerm[] { new OrTerm(buildSearchTerm(sendEmailsTo)), new SubjectTerm(acceptSubject), new FlagTerm(new Flags(Flags.Flag.SEEN), false) }); // st = new SubjectTerm("PI Request"); Message msgs[] = folder.search(st); // Message msgs[] = folder.getMessages(); if (verbose) System.out.println("Search completed, " + msgs.length + " message(s)."); for (int msgNum=0; msgNum<msgs.length; msgNum++) { try { Message mess = msgs[msgNum]; Address from[] = mess.getFrom(); String sender = ""; try { sender = from[0].toString(); } catch(Exception exception) { exception.printStackTrace(); } // System.out.println("Message from [" + sender + "], subject [" + subject + "], content [" + mess.getContent().toString().trim() + "]"); if (true) { if (!mess.isSet(javax.mail.Flags.Flag.SEEN) && !mess.isSet(javax.mail.Flags.Flag.DELETED)) { String txtMess = printMessage(mess, dir); messList.add(txtMess); mess.setFlag(javax.mail.Flags.Flag.SEEN, true); mess.setFlag(javax.mail.Flags.Flag.DELETED, true); // Send an ack - by email. if (this.emailSender == null) this.emailSender = new EmailSender(this.provider); this.emailSender.send(new String[] { sender }, ackSubject, "Your request [" + txtMess.trim() + "] is being taken care of."); if (verbose) System.out.println("Sent an ack to " + sender); } else { if (verbose) System.out.println("Old message in your inbox..., received " + mess.getReceivedDate().toString()); } } } catch(Exception ex) { // System.err.println(ex.getMessage()); ex.printStackTrace(); } } } catch(Exception ex) { throw ex; } finally { try { if (folder != null) folder.close(true); if (store != null) store.close(); } catch(Exception ex2) { System.err.println("Finally ..."); ex2.printStackTrace(); } } return messList; } public static String printMessage(Message message, String dir) { String ret = ""; try { String from = ((InternetAddress)message.getFrom()[0]).getPersonal(); if(from == null) from = ((InternetAddress)message.getFrom()[0]).getAddress(); if (verbose) System.out.println("From: " + from); String subject = message.getSubject(); if (verbose) System.out.println("Subject: " + subject); Part messagePart = message; Object content = messagePart.getContent(); if (content instanceof Multipart) { // messagePart = ((Multipart)content).getBodyPart(0); int nbParts = ((Multipart)content).getCount(); if (verbose) System.out.println("[ Multipart Message ], " + nbParts + " part(s)."); for (int i=0; i<nbParts; i++) { messagePart = ((Multipart)content).getBodyPart(i); if (messagePart.getContentType().toUpperCase().startsWith("APPLICATION/OCTET-STREAM")) { if (verbose) System.out.println(messagePart.getContentType() + ":" + messagePart.getFileName()); InputStream is = messagePart.getInputStream(); String newFileName = ""; if (dir != null) newFileName = dir + File.separator; newFileName += messagePart.getFileName(); FileOutputStream fos = new FileOutputStream(newFileName); ret = messagePart.getFileName(); if (verbose) System.out.println("Downloading " + messagePart.getFileName() + "..."); copy(is, fos); if (verbose) System.out.println("...done."); } else // text/plain, text/html { if (verbose) System.out.println("-- Part #" + i + " --, " + messagePart.getContentType().replace('\n', ' ').replace('\r', ' ').replace("\b", "").trim()); InputStream is = messagePart.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = ""; while (line != null) { line = br.readLine(); if (line != null) { if (verbose) System.out.println("[" + line + "]"); if (messagePart.getContentType().toUpperCase().startsWith("TEXT/PLAIN")) ret += line; } } br.close(); if (verbose) System.out.println("-------------------"); } } } else { // System.out.println(" .Message is a " + content.getClass().getName()); // System.out.println("Content:"); // System.out.println(content.toString()); ret = content.toString(); } if (verbose) System.out.println("-----------------------------"); } catch(Exception ex) { ex.printStackTrace(); } return ret; } private static void copy(InputStream in, OutputStream out) throws IOException { synchronized(in) { synchronized(out) { byte buffer[] = new byte[256]; while (true) { int bytesRead = in.read(buffer); if(bytesRead == -1) break; out.write(buffer, 0, bytesRead); } } } } }
12nosanshiro-pi4j-sample
Relay.by.email/src/relay/email/EmailReceiver.java
Java
mit
14,397
package relay.email; import com.sun.mail.smtp.SMTPTransport; import java.io.FileInputStream; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class EmailSender { private static String protocol; private static int outgoingPort; private static int incomingPort; private static String username; private static String password; private static String outgoing; private static String incoming; private static String replyto; private static boolean smtpauth; private static String sendEmailsTo; private static String eventSubject; private static boolean verbose = "true".equals(System.getProperty("verbose", "false")); public EmailSender(String provider) throws RuntimeException { EmailSender.protocol = ""; EmailSender.outgoingPort = 0; EmailSender.incomingPort = 0; EmailSender.username = ""; EmailSender.password = ""; EmailSender.outgoing = ""; EmailSender.incoming = ""; EmailSender.replyto = ""; EmailSender.smtpauth = false; EmailSender.sendEmailsTo = ""; EmailSender.eventSubject = ""; Properties props = new Properties(); String propFile = "email.properties"; try { FileInputStream fis = new FileInputStream(propFile); props.load(fis); } catch (Exception e) { System.out.println("email.properies file problem..."); throw new RuntimeException("File not found:email.properies"); } EmailSender.sendEmailsTo = props.getProperty("pi.send.emails.to"); EmailSender.eventSubject = props.getProperty("pi.event.subject"); EmailSender.protocol = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.protocol"); EmailSender.outgoingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server.port", "0")); EmailSender.incomingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server.port", "0")); EmailSender.username = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.username", ""); EmailSender.password = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.password", ""); EmailSender.outgoing = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server", ""); EmailSender.incoming = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server", ""); EmailSender.replyto = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.replyto", ""); EmailSender.smtpauth = "true".equals(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.smtpauth", "false")); if (verbose) { System.out.println("-------------------------------------"); System.out.println("Protocol : " + EmailSender.protocol); System.out.println("Usr/pswd : " + EmailSender.username + "/" + EmailSender.password); System.out.println("Incoming server: " + EmailSender.incoming + ":" + EmailSender.incomingPort); System.out.println("Outgoing server: " + EmailSender.outgoing + ":" + EmailSender.outgoingPort); System.out.println("replyto : " + EmailSender.replyto); System.out.println("SMTPAuth : " + EmailSender.smtpauth); System.out.println("-------------------------------------"); } } public boolean isAuthRequired() { return EmailSender.smtpauth; } public String getUserName() { return EmailSender.username; } public String getPassword() { return EmailSender.password; } public String getReplyTo() { return EmailSender.replyto; } public String getIncomingServer() { return EmailSender.incoming; } public String getOutgoingServer() { return EmailSender.outgoing; } public String getEmailDest() { return EmailSender.sendEmailsTo; } public String getEventSubject() { return EmailSender.eventSubject; } public void send(String[] dest, String subject, String content) throws MessagingException, AddressException { send(dest, subject, content, null); } public void send(String[] dest, String subject, String content, String attachment) throws MessagingException, AddressException { Properties props = setProps(); // Session session = Session.getDefaultInstance(props, auth); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); session.setDebug(verbose); Transport tr = session.getTransport("smtp"); if (!(tr instanceof SMTPTransport)) System.out.println("This is NOT an SMTPTransport:[" + tr.getClass().getName() + "]"); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(EmailSender.replyto)); if (dest == null || dest.length == 0) throw new RuntimeException("Need at least one recipient."); msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(dest[0])); for (int i=1; i<dest.length; i++) msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(dest[i])); msg.setSubject(subject); if (attachment != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(content); Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = attachment; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Send the complete message parts msg.setContent(multipart); } else { msg.setText(content != null ? content : ""); msg.setContent(content, "text/plain"); } msg.saveChanges(); if (verbose) System.out.println("sending:[" + content + "], " + Integer.toString(content.length()) + " characters"); Transport.send(msg); } private Properties setProps() { Properties props = new Properties(); props.put("mail.debug", verbose?"true":"false"); props.put("mail.smtp.host", EmailSender.outgoing); props.put("mail.smtp.port", Integer.toString(EmailSender.outgoingPort)); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // See http://www.oracle.com/technetwork/java/faq-135477.html#yahoomail // props.put("mail.smtp.starttls.required", "true"); props.put("mail.smtp.ssl.enable", "true"); return props; } }
12nosanshiro-pi4j-sample
Relay.by.email/src/relay/email/EmailSender.java
Java
mit
7,780
package relay; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import java.io.FileReader; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Properties; import org.json.JSONObject; import relay.email.EmailReceiver; import relay.email.EmailSender; import relay.gpio.GPIOController; import relay.gpio.RaspberryPIEventListener; public class PIControllerMain implements RaspberryPIEventListener { private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); private static boolean verbose = "true".equals(System.getProperty("verbose", "false")); private static String providerSend = "google"; private static String providerReceive = "google"; EmailSender sender = null; /** * Invoked like: * java relay.email.PIControllerMain [-verbose] -send:google -receive:yahoo -help * * This will send emails using google, and receive using yahoo. * Default values are: * java pi4j.email.PIControllerMain -send:google -receive:google * * Do check the file email.properties for the different values associated with email servers. * * @param args See above * * To try it: * send email to the right destination (like olivier.lediouris@gmail.com, see in email.properties) with a plain text payload like * { 'operation':'turn-relay-on' } * or * { 'operation':'turn-relay-off' } * * Subject: 'PI Request' */ public static void main(String[] args) { for (int i=0; i<args.length; i++) { if ("-verbose".equals(args[i])) { verbose = true; System.setProperty("verbose", "true"); } else if (args[i].startsWith("-send:")) providerSend = args[i].substring("-send:".length()); else if (args[i].startsWith("-receive:")) providerReceive =args[i].substring("-receive:".length()); else if ("-help".equals(args[i])) { System.out.println("Usage:"); System.out.println(" java relay.email.PIControllerMain -verbose -send:google -receive:yahoo -help"); System.exit(0); } } final GPIOController piController = new GPIOController(); EmailReceiver receiver = new EmailReceiver(providerReceive); // For Google, pop must be explicitely enabled at the account level Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { piController.switchRelay(false); piController.shutdown(); System.out.println("\nExiting nicely."); } }); try { String from = ""; try { Properties props = new Properties(); props.load(new FileReader("email.properties")); String emitters = props.getProperty("pi.accept.emails.from"); from = ", from " + emitters; } catch (Exception ex) { ex.printStackTrace(); } System.out.println("Waiting for instructions" + from + "."); boolean keepLooping = true; while (keepLooping) { List<String> received = receiver.receive(); if (verbose || received.size() > 0) System.out.println(SDF.format(new Date()) + " - Retrieved " + received.size() + " message(s)."); for (String s : received) { // System.out.println(s); String operation = ""; try { JSONObject json = new JSONObject(s); operation = json.getString("operation"); } catch (Exception ex) { System.err.println(ex.getMessage()); System.err.println("Message is [" + s + "]"); } if ("exit".equals(operation)) { keepLooping = false; System.out.println("Will exit next batch."); // break; } else { if ("turn-relay-on".equals(operation)) { System.out.println("Turning relay on"); piController.switchRelay(true); } else if ("turn-relay-off".equals(operation)) { System.out.println("Turning relay off"); piController.switchRelay(false); } try { Thread.sleep(1000L); } catch (InterruptedException ie) { ie.printStackTrace(); } } } } piController.shutdown(); System.out.println("Done."); System.exit(0); } catch (Exception ex) { ex.printStackTrace(); } } public void manageEvent(GpioPinDigitalStateChangeEvent event) { if (sender == null) sender = new EmailSender(providerSend); try { String mess = "{ pin: '" + event.getPin() + "', state:'" + event.getState() + "' }"; System.out.println("Sending:" + mess); sender.send(sender.getEmailDest().split(","), sender.getEventSubject(), mess); } catch (Exception ex) { ex.printStackTrace(); } } }
12nosanshiro-pi4j-sample
Relay.by.email/src/relay/PIControllerMain.java
Java
mit
5,041
"use strict"; var connection; (function () { var ws = window.WebSocket || window.MozWebSocket; if (!ws) { displayMessage('Sorry, but your browser does not support WebSockets.'); return; } // open connection var rootUri = "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" + (document.location.port === "" ? "8080" : document.location.port); console.log(rootUri); connection = new WebSocket(rootUri); // 'ws://localhost:9876'); connection.onopen = function() { displayMessage('Connected.') }; connection.onerror = function (error) { // just in there were some problems with connection... displayMessage('Sorry, but there is some problem with your connection or the server is down.'); }; // most important part - incoming messages connection.onmessage = function (message) { // console.log('onmessage:' + message); // try to parse JSON message. try { var json = JSON.parse(message.data); } catch (e) { displayMessage('This doesn\'t look like a valid JSON: ' + message.data); return; } // NOTE: if you're not sure about the JSON structure // check the server source code above if (json.type === 'message') { // it's a single message var value = parseInt(json.data.text); // console.log('Setting value to ' + value); displayValue.setValue(value); } else { displayMessage('Hmm..., I\'ve never seen JSON like this: ' + json); } }; /** * This method is optional. If the server wasn't able to respond to the * in 3 seconds then show some error message to notify the user that * something is wrong. */ setInterval(function() { if (connection.readyState !== 1) { displayMessage('Unable to communicate with the WebSocket server. Try again.'); } }, 3000); // Ping })(); var sendMessage = function(msg) { if (!msg) { return; } // send the message as an ordinary text connection.send(msg); }; var displayMessage = function(mess){ var messList = statusFld.innerHTML; messList = (((messList !== undefined && messList.length) > 0 ? messList + '<br>' : '') + mess); statusFld.innerHTML = messList; }; var resetStatus = function() { statusFld.innerHTML = ""; };
12nosanshiro-pi4j-sample
LelandOilDetector/node/client.js
JavaScript
mit
2,360
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Oil Detection / WebSockets</title> <script type="text/javascript" src="widgets/AnalogDisplay.js"></script> <style> * { font-family:tahoma; font-size:12px; padding:0px; margin:0px; } p { line-height:18px; } </style> <script type="text/javascript"> var response = {}; var displayValue; var statusFld; window.onload = function() { displayValue = new AnalogDisplay('valueCanvas', 100, 100, 10, 1, true, 40); statusFld = document.getElementById("status"); }; </script> </head> <body> <table width="100%"> <tr> <td valign="top"><h2>Oil Detection on WebSocket</h2></td> </tr> <tr> <td align="left"> <div id="status" style="padding:5px; background:#ddd; border-radius:5px; overflow-y: scroll; border:1px solid #CCC; margin-top:10px; height: 80px;"> <!--i>Status will go here when needed...</i--> </div> </td> </tr> <tr> <td valign="top" align="right"><a href="" onclick="javascript:resetStatus(); return false;" title="Clear status board"><small>Reset Status</small></a></td> </tr> <tr> <td align="center" valign="top"> <canvas id="valueCanvas" width="240" height="220" title="Potentiometer value"></canvas> </td> </tr> </table> <hr> <script src="./client.js"></script> </body> </html>
12nosanshiro-pi4j-sample
LelandOilDetector/node/display.html
HTML
mit
1,457
/* * @author Olivier Le Diouris */ // TODO This config in CSS // We wait for the var- custom properties to be implemented in CSS... // @see http://www.w3.org/TR/css-variables-1/ /* * For now: * Themes are applied based on a css class: * .display-scheme * { * color: black; * } * * if color is black, analogDisplayColorConfigBlack is applied * if color is white, analogDisplayColorConfigWhite is applied, etc */ var analogDisplayColorConfigWhite = { bgColor: 'white', digitColor: 'black', withGradient: true, displayBackgroundGradient: { from: 'LightGrey', to: 'white' }, withDisplayShadow: true, shadowColor: 'rgba(0, 0, 0, 0.75)', outlineColor: 'DarkGrey', majorTickColor: 'black', minorTickColor: 'black', valueColor: 'grey', valueOutlineColor: 'black', valueNbDecimal: 0, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'black', withHandShadow: true, knobColor: 'DarkGrey', knobOutlineColor: 'black', font: 'Arial' /* 'Source Code Pro' */ }; var analogDisplayColorConfigBlack = { bgColor: 'black', digitColor: 'LightBlue', withGradient: true, displayBackgroundGradient: { from: 'black', to: 'LightGrey' }, shadowColor: 'black', outlineColor: 'DarkGrey', majorTickColor: 'LightGreen', minorTickColor: 'LightGreen', valueColor: 'LightGreen', valueOutlineColor: 'black', valueNbDecimal: 1, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'blue', withHandShadow: true, knobColor: '#8ED6FF', // Kind of blue knobOutlineColor: 'blue', font: 'Arial' }; var analogDisplayColorConfig = analogDisplayColorConfigWhite; // White is the default function AnalogDisplay(cName, // Canvas Name dSize, // Display radius maxValue, // default 10 majorTicks, // default 1 minorTicks, // default 0 withDigits, // default true, boolean overlapOver180InDegree, // default 0, beyond horizontal, in degrees, before 0, after 180 startValue) // default 0, In case it is not 0 { if (maxValue === undefined) maxValue = 10; if (majorTicks === undefined) majorTicks = 1; if (minorTicks === undefined) minorTicks = 0; if (withDigits === undefined) withDigits = true; if (overlapOver180InDegree === undefined) overlapOver180InDegree = 0; if (startValue === undefined) startValue = 0; var scale = dSize / 100; var canvasName = cName; var displaySize = dSize; var running = false; var previousValue = startValue; var intervalID; var valueToDisplay = 0; var incr = 1; var instance = this; //try { console.log('in the AnalogDisplay constructor for ' + cName + " (" + dSize + ")"); } catch (e) {} (function(){ drawDisplay(canvasName, displaySize, previousValue); })(); // Invoked automatically this.repaint = function() { drawDisplay(canvasName, displaySize, previousValue); }; this.setDisplaySize = function(ds) { scale = ds / 100; displaySize = ds; drawDisplay(canvasName, displaySize, previousValue); }; this.startStop = function (buttonName) { // console.log('StartStop requested on ' + buttonName); var button = document.getElementById(buttonName); running = !running; button.value = (running ? "Stop" : "Start"); if (running) this.animate(); else { window.clearInterval(intervalID); previousValue = valueToDisplay; } }; this.animate = function() { var value; if (arguments.length === 1) value = arguments[0]; else { // console.log("Generating random value"); value = maxValue * Math.random(); } value = Math.max(value, startValue); value = Math.min(value, maxValue); //console.log("Reaching Value :" + value + " from " + previousValue); diff = value - previousValue; valueToDisplay = previousValue; // console.log(canvasName + " going from " + previousValue + " to " + value); // if (diff > 0) // incr = 0.01 * maxValue; // else // incr = -0.01 * maxValue; incr = diff / 10; if (intervalID) window.clearInterval(intervalID); intervalID = window.setInterval(function () { displayAndIncrement(value); }, 10); }; var displayAndIncrement = function(finalValue) { //console.log('Tic ' + inc + ', ' + finalValue); drawDisplay(canvasName, displaySize, valueToDisplay); valueToDisplay += incr; if ((incr > 0 && valueToDisplay > finalValue) || (incr < 0 && valueToDisplay < finalValue)) { // console.log('Stop, ' + finalValue + ' reached, steps were ' + incr); window.clearInterval(intervalID); previousValue = finalValue; if (running) instance.animate(); else drawDisplay(canvasName, displaySize, finalValue); // Final display } }; function drawDisplay(displayCanvasName, displayRadius, displayValue) { var schemeColor; try { schemeColor = getCSSClass(".display-scheme"); } catch (err) { /* not there */ } if (schemeColor !== undefined && schemeColor !== null) { var styleElements = schemeColor.split(";"); for (var i=0; i<styleElements.length; i++) { var nv = styleElements[i].split(":"); if ("color" === nv[0]) { // console.log("Scheme Color:[" + nv[1].trim() + "]"); if (nv[1].trim() === 'black') analogDisplayColorConfig = analogDisplayColorConfigBlack; else if (nv[1].trim() === 'white') analogDisplayColorConfig = analogDisplayColorConfigWhite; } } } var digitColor = analogDisplayColorConfig.digitColor; var canvas = document.getElementById(displayCanvasName); var context = canvas.getContext('2d'); var radius = displayRadius; // Cleanup //context.fillStyle = "#ffffff"; context.fillStyle = analogDisplayColorConfig.bgColor; //context.fillStyle = "transparent"; context.fillRect(0, 0, canvas.width, canvas.height); //context.fillStyle = 'rgba(255, 255, 255, 0.0)'; //context.fillRect(0, 0, canvas.width, canvas.height); context.beginPath(); //context.arc(x, y, radius, startAngle, startAngle + Math.PI, antiClockwise); // context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree), (2 * Math.PI) + toRadians(overlapOver180InDegree), false); context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree > 0?90:0), (2 * Math.PI) + toRadians(overlapOver180InDegree > 0?90:0), false); context.lineWidth = 5; if (analogDisplayColorConfig.withGradient) { var grd = context.createLinearGradient(0, 5, 0, radius); grd.addColorStop(0, analogDisplayColorConfig.displayBackgroundGradient.from);// 0 Beginning grd.addColorStop(1, analogDisplayColorConfig.displayBackgroundGradient.to); // 1 End context.fillStyle = grd; } else context.fillStyle = analogDisplayColorConfig.displayBackgroundGradient.to; if (analogDisplayColorConfig.withDisplayShadow) { context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; context.shadowColor = analogDisplayColorConfig.shadowColor; } context.lineJoin = "round"; context.fill(); context.strokeStyle = analogDisplayColorConfig.outlineColor; context.stroke(); context.closePath(); var totalAngle = (Math.PI + (2 * (toRadians(overlapOver180InDegree)))); // Major Ticks context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { var currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.85) * Math.cos(currentAngle)); yTo = (radius + 10) - ((radius * 0.85) * Math.sin(currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 3; context.strokeStyle = analogDisplayColorConfig.majorTickColor; context.stroke(); context.closePath(); // Minor Ticks if (minorTicks > 0) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=minorTicks) { var _currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(_currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(_currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.90) * Math.cos(_currentAngle)); yTo = (radius + 10) - ((radius * 0.90) * Math.sin(_currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.minorTickColor; context.stroke(); context.closePath(); } // Numbers if (withDigits) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { context.save(); context.translate(canvas.width/2, (radius + 10)); // canvas.height); var __currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // context.rotate((Math.PI * (i / maxValue)) - (Math.PI / 2)); context.rotate(__currentAngle - (Math.PI / 2)); context.font = "bold " + Math.round(scale * 15) + "px " + analogDisplayColorConfig.font; // Like "bold 15px Arial" context.fillStyle = digitColor; str = (i + startValue).toString(); len = context.measureText(str).width; context.fillText(str, - len / 2, (-(radius * .8) + 10)); context.restore(); } context.closePath(); } // Value text = displayValue.toFixed(analogDisplayColorConfig.valueNbDecimal); len = 0; context.font = "bold " + Math.round(scale * 40) + "px " + analogDisplayColorConfig.font; // "bold 40px Arial" var metrics = context.measureText(text); len = metrics.width; context.beginPath(); context.fillStyle = analogDisplayColorConfig.valueColor; context.fillText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.valueOutlineColor; context.strokeText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); // Outlined context.closePath(); // Hand context.beginPath(); if (analogDisplayColorConfig.withHandShadow) { context.shadowColor = analogDisplayColorConfig.shadowColor; context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; } // Center context.moveTo(canvas.width / 2, radius + 10); var ___currentAngle = (totalAngle * ((displayValue - startValue) / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // Left x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle - (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle - (Math.PI / 2)))); context.lineTo(x, y); // Tip x = (canvas.width / 2) - ((radius * 0.90) * Math.cos(___currentAngle)); y = (radius + 10) - ((radius * 0.90) * Math.sin(___currentAngle)); context.lineTo(x, y); // Right x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle + (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle + (Math.PI / 2)))); context.lineTo(x, y); context.closePath(); context.fillStyle = analogDisplayColorConfig.handColor; context.fill(); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.handOutlineColor; context.stroke(); // Knob context.beginPath(); context.arc((canvas.width / 2), (radius + 10), 7, 0, 2 * Math.PI, false); context.closePath(); context.fillStyle = analogDisplayColorConfig.knobColor; context.fill(); context.strokeStyle = analogDisplayColorConfig.knobOutlineColor; context.stroke(); }; this.setValue = function(val) { drawDisplay(canvasName, displaySize, val); }; function toDegrees(rad) { return rad * (180 / Math.PI); } function toRadians(deg) { return deg * (Math.PI / 180); } }
12nosanshiro-pi4j-sample
LelandOilDetector/node/widgets/AnalogDisplay.js
JavaScript
mit
12,851
/** * To debug: * Prompt> set HTTP_PROXY=http://www-proxy.us.oracle.com:80 * Prompt> npm install -g node-inspector * Prompt> node-inspector * * From another console: * Prompt> node --debug server.js */ "use strict"; process.title = 'node-oil-detector'; // Port where we'll run the websocket server var port = 9876; // websocket and http servers var webSocketServer = require('websocket').server; var http = require('http'); var fs = require('fs'); var verbose = false; if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str) { return this.indexOf(str) === 0; }; } if (typeof String.prototype.endsWith != 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } function handler (req, res) { var respContent = ""; if (verbose) { console.log("Speaking HTTP from " + __dirname); console.log("Server received an HTTP Request:\n" + req.method + "\n" + req.url + "\n-------------"); console.log("ReqHeaders:" + JSON.stringify(req.headers, null, '\t')); console.log('Request:' + req.url); var prms = require('url').parse(req.url, true); console.log(prms); console.log("Search: [" + prms.search + "]"); console.log("-------------------------------"); } if (req.url.startsWith("/data/")) { // Static resource var resource = req.url.substring("/data/".length); console.log('Loading static ' + req.url + " (" + resource + ")"); fs.readFile(__dirname + '/' + resource, function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading ' + resource); } if (verbose) { console.log("Read resource content:\n---------------\n" + data + "\n--------------"); } var contentType = "text/html"; if (resource.endsWith(".css")) { contentType = "text/css"; } else if (resource.endsWith(".html")) { contentType = "text/html"; } else if (resource.endsWith(".xml")) { contentType = "text/xml"; } else if (resource.endsWith(".js")) { contentType = "text/javascript"; } else if (resource.endsWith(".jpg")) { contentType = "image/jpg"; } else if (resource.endsWith(".gif")) { contentType = "image/gif"; } else if (resource.endsWith(".png")) { contentType = "image/png"; } res.writeHead(200, {'Content-Type': contentType}); // console.log('Data is ' + typeof(data)); if (resource.endsWith(".jpg") || resource.endsWith(".gif") || resource.endsWith(".png")) { // res.writeHead(200, {'Content-Type': 'image/gif' }); res.end(data, 'binary'); } else { res.end(data.toString().replace('$PORT$', port.toString())); // Replace $PORT$ with the actual port value. } }); } else if (req.url.startsWith("/verbose=")) { if (req.method === "GET") { verbose = (req.url.substring("/verbose=".length) === 'on'); res.end(JSON.stringify({verbose: verbose?'on':'off'})); } } else if (req.url == "/") { if (req.method === "POST") { var data = ""; if (verbose) { console.log("---- Headers ----"); for (var item in req.headers) { console.log(item + ": " + req.headers[item]); } console.log("-----------------"); } req.on("data", function(chunk) { data += chunk; }); req.on("end", function() { console.log("POST request: [" + data + "]"); res.writeHead(200, {'Content-Type': 'application/json'}); var status = {'status':'OK'}; res.end(JSON.stringify(status)); }); } } else { console.log("Unmanaged request: [" + req.url + "]"); respContent = "Response from " + req.url; res.writeHead(404, {'Content-Type': 'text/plain'}); res.end(); // respContent); } } // HTTP Handler /** * Global variables */ // list of currently connected clients (users) var clients = [ ]; /** * Helper function for escaping input strings */ var htmlEntities = function(str) { return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;') .replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }; /** * HTTP server */ var server = http.createServer(handler); server.listen(port, function() { console.log((new Date()) + " Server is listening on port " + port); }); /** * WebSocket server */ var wsServer = new webSocketServer({ // WebSocket server is tied to a HTTP server. WebSocket request is just // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6 httpServer: server }); // This callback function is called every time someone // tries to connect to the WebSocket server wsServer.on('request', function(request) { console.log((new Date()) + ' Connection from origin ' + request.origin + '.'); // accept connection - you should check 'request.origin' to make sure that // client is connecting from your website // (http://en.wikipedia.org/wiki/Same_origin_policy) var connection = request.accept(null, request.origin); clients.push(connection); console.log((new Date()) + ' Connection accepted.'); // user sent some message connection.on('message', function(message) { if (message.type === 'utf8') { // accept only text console.log((new Date()) + ' Received Message: ' + message.utf8Data); var obj = { time: (new Date()).getTime(), text: htmlEntities(message.utf8Data) }; // broadcast message to all connected clients. That's what this app is doing. var json = JSON.stringify({ type: 'message', data: obj }); for (var i=0; i<clients.length; i++) { clients[i].sendUTF(json); } } }); // user disconnected connection.on('close', function(code) { // Close var nb = clients.length; for (var i=0; i<clients.length; i++) { if (clients[i] === connection) { clients.splice(i, 1); break; } } if (verbose) { console.log("We have (" + nb + "->) " + clients.length + " client(s) connected."); } }); });
12nosanshiro-pi4j-sample
LelandOilDetector/node/server.js
JavaScript
mit
6,622
package relay; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class RelayManager { private final GpioController gpio = GpioFactory.getInstance(); private final GpioPinDigitalOutput pin17; private final GpioPinDigitalOutput pin18; public RelayManager() { System.out.println("GPIO Control - pin 00/#17 and 01/#18 ... started."); System.out.println("(Labelled #17 an #18 on the cobbler.)"); // For a relay it seems that HIGH means NC (Normally Closed)... pin17 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "Relay1", PinState.HIGH); pin18 = null; // gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "Relay2", PinState.HIGH); } public void set(String device, String status) { GpioPinDigitalOutput pin = ("00".equals(device)?pin17:pin18); if ("on".equals(status)) pin.low(); else pin.high(); } public String getStatus(String dev) { String status = "unknown"; GpioPinDigitalOutput pin = ("00".equals(dev)?pin17:pin18); status = pin.isHigh() ? "off" : "on"; return status; } public void shutdown() { gpio.shutdown(); } }
12nosanshiro-pi4j-sample
LelandOilDetector/src/relay/RelayManager.java
Java
mit
1,277
package ws; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import relay.RelayManager; public class WebSocketFeeder { private final static boolean DEBUG = "true".equals(System.getProperty("debug", "false")); private ADCObserver.MCP3008_input_channels channel = null; private static boolean keepWorking = true; private static WebSocketClient webSocketClient = null; private static RelayManager rm; private static ADCObserver obs = null; public WebSocketFeeder(int ch) throws Exception { channel = findChannel(ch); try { rm = new RelayManager(); rm.set("00", "on"); } catch (Exception ex) { System.err.println("You're not on the PI, hey?"); ex.printStackTrace(); } String wsUri = System.getProperty("ws.uri", "ws://localhost:9876/"); initWebSocketConnection(wsUri); obs = new ADCObserver(channel); // Note: We could instantiate more than one observer (on several channels). ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { if (inputChannel.equals(channel)) { int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (DEBUG) System.out.println("readAdc:" + Integer.toString(newValue) + " (0x" + lpad(Integer.toString(newValue, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(newValue, 2), "0", 8) + ")"); System.out.println("Volume:" + volume + "% (" + newValue + ")"); try { webSocketClient.send(Integer.toString(volume)); } catch (Exception ex) { ex.printStackTrace(); } // Turn relay off above 75% if (volume > 75) { String status = rm.getStatus("00"); // System.out.println("Relay is:" + status); if ("on".equals(status)) { System.out.println("Turning relay off!"); try { rm.set("00", "off"); } catch (Exception ex) { System.err.println(ex.toString()); } } } } } }); obs.start(); } private void initWebSocketConnection(String serverURI) { try { webSocketClient = new WebSocketClient(new URI(serverURI)) { @Override public void onOpen(ServerHandshake serverHandshake) { System.out.println("WS On Open"); } @Override public void onMessage(String string) { // System.out.println("WS On Message"); } @Override public void onClose(int i, String string, boolean b) { System.out.println("WS On Close"); } @Override public void onError(Exception exception) { System.out.println("WS On Error"); exception.printStackTrace(); } }; webSocketClient.connect(); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) throws Exception { int channel = 0; if (args.length > 0) channel = Integer.parseInt(args[0]); System.out.println("Listening to MCP3008 channel " + channel); // System.out.println("Adding shutdown hook"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Shutting down nicely."); if (obs != null) { System.out.println("Stopping observer..."); obs.stop(); } keepWorking = false; System.out.println("Closing WebSocket client..."); webSocketClient.close(); try { System.out.println("Turning power off..."); rm.set("00", "off"); rm.shutdown(); } catch (Exception ex) { System.err.println(ex.toString()); } System.out.println("Done."); } }); new WebSocketFeeder(channel); } private static ADCObserver.MCP3008_input_channels findChannel(int ch) throws IllegalArgumentException { ADCObserver.MCP3008_input_channels channel = null; switch (ch) { case 0: channel = ADCObserver.MCP3008_input_channels.CH0; break; case 1: channel = ADCObserver.MCP3008_input_channels.CH1; break; case 2: channel = ADCObserver.MCP3008_input_channels.CH2; break; case 3: channel = ADCObserver.MCP3008_input_channels.CH3; break; case 4: channel = ADCObserver.MCP3008_input_channels.CH4; break; case 5: channel = ADCObserver.MCP3008_input_channels.CH5; break; case 6: channel = ADCObserver.MCP3008_input_channels.CH6; break; case 7: channel = ADCObserver.MCP3008_input_channels.CH7; break; default: throw new IllegalArgumentException("No channel " + Integer.toString(ch)); } return channel; } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
12nosanshiro-pi4j-sample
LelandOilDetector/src/ws/WebSocketFeeder.java
Java
mit
5,842
package adc; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * Read an Analog to Digital Converter */ public class ADCObserver { private final static boolean DISPLAY_DIGIT = false; // Note: "Mismatch" 23-24. The wiring says DOUT->#23, DIN->#24 // 23: DOUT on the ADC is IN on the GPIO. ADC:Slave, GPIO:Master // 24: DIN on the ADC, OUT on the GPIO. Same reason as above. // SPI: Serial Peripheral Interface private static Pin spiClk = RaspiPin.GPIO_01; // Pin #18, clock private static Pin spiMiso = RaspiPin.GPIO_04; // Pin #23, data in. MISO: Master In Slave Out private static Pin spiMosi = RaspiPin.GPIO_05; // Pin #24, data out. MOSI: Master Out Slave In private static Pin spiCs = RaspiPin.GPIO_06; // Pin #25, Chip Select public static enum MCP3008_input_channels { CH0(0), CH1(1), CH2(2), CH3(3), CH4(4), CH5(5), CH6(6), CH7(7); private int ch; MCP3008_input_channels(int chNum) { this.ch = chNum; } public int ch() { return this.ch; } } private MCP3008_input_channels[] adcChannel; // Between 0 and 7, 8 channels on the MCP3008 private static GpioPinDigitalInput misoInput = null; private static GpioPinDigitalOutput mosiOutput = null; private static GpioPinDigitalOutput clockOutput = null; private static GpioPinDigitalOutput chipSelectOutput = null; private boolean go = true; public ADCObserver(MCP3008_input_channels channel) { this(new MCP3008_input_channels[] { channel }) ; } public ADCObserver(MCP3008_input_channels[] channel) { adcChannel = channel; } public void start() { GpioController gpio = GpioFactory.getInstance(); mosiOutput = gpio.provisionDigitalOutputPin(spiMosi, "MOSI", PinState.LOW); clockOutput = gpio.provisionDigitalOutputPin(spiClk, "CLK", PinState.LOW); chipSelectOutput = gpio.provisionDigitalOutputPin(spiCs, "CS", PinState.LOW); misoInput = gpio.provisionDigitalInputPin(spiMiso, "MISO"); int lastRead[] = new int[adcChannel.length]; for (int i=0; i<lastRead.length; i++) lastRead[i] = 0; int tolerance = 5; while (go) { for (int i=0; i<adcChannel.length; i++) { int adc = readAdc(adcChannel[i]); // System.out.println("ADC:" + adc); int postAdjust = Math.abs(adc - lastRead[i]); if (postAdjust > tolerance) { ADCContext.getInstance().fireValueChanged(adcChannel[i], adc); lastRead[i] = adc; } } try { Thread.sleep(100L); } catch (InterruptedException ie) { ie.printStackTrace(); } } System.out.println("Shutting down..."); gpio.shutdown(); } public void stop() { go = false; } private int readAdc(MCP3008_input_channels channel) { chipSelectOutput.high(); clockOutput.low(); chipSelectOutput.low(); int adccommand = channel.ch(); adccommand |= 0x18; // 0x18: 00011000 adccommand <<= 3; // Send 5 bits: 8 - 3. 8 input channels on the MCP3008. for (int i=0; i<5; i++) // { if ((adccommand & 0x80) != 0x0) // 0x80 = 0&10000000 mosiOutput.high(); else mosiOutput.low(); adccommand <<= 1; clockOutput.high(); clockOutput.low(); } int adcOut = 0; for (int i=0; i<12; i++) // Read in one empty bit, one null bit and 10 ADC bits { clockOutput.high(); clockOutput.low(); adcOut <<= 1; if (misoInput.isHigh()) { // System.out.println(" " + misoInput.getName() + " is high (i:" + i + ")"); // Shift one bit on the adcOut adcOut |= 0x1; } if (DISPLAY_DIGIT) System.out.println("ADCOUT: 0x" + Integer.toString(adcOut, 16).toUpperCase() + ", 0&" + Integer.toString(adcOut, 2).toUpperCase()); } chipSelectOutput.high(); adcOut >>= 1; // Drop first bit return adcOut; } }
12nosanshiro-pi4j-sample
LelandOilDetector/src/adc/ADCObserver.java
Java
mit
4,263
package adc; import java.util.ArrayList; import java.util.List; public class ADCContext { private static ADCContext instance = null; private List<ADCListener> listeners = null; private ADCContext() { listeners = new ArrayList<ADCListener>(); } public synchronized static ADCContext getInstance() { if (instance == null) instance = new ADCContext(); return instance; } public void addListener(ADCListener listener) { if (!listeners.contains(listener)) listeners.add(listener); } public void removeListener(ADCListener listener) { if (listeners.contains(listener)) listeners.remove(listener); } public List<ADCListener> getListeners() { return this.listeners; } public void fireValueChanged(ADCObserver.MCP3008_input_channels channel, int newValue) { for (ADCListener listener : listeners) listener.valueUpdated(channel, newValue); } }
12nosanshiro-pi4j-sample
LelandOilDetector/src/adc/ADCContext.java
Java
mit
946
package adc; public class ADCListener { public void valueUpdated(ADCObserver.MCP3008_input_channels channel, int newValue) {}; }
12nosanshiro-pi4j-sample
LelandOilDetector/src/adc/ADCListener.java
Java
mit
132
package adc.utils; import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; public class EscapeSeq { public final static char ESC = '\u001b'; // (char) 27; public final static String ANSI_BLACK = "0"; public final static String ANSI_RED = "1"; public final static String ANSI_GREEN = "2"; public final static String ANSI_YELLOW = "3"; public final static String ANSI_BLUE = "4"; public final static String ANSI_MAGENTA = "5"; public final static String ANSI_CYAN = "6"; public final static String ANSI_WHITE = "7"; public static final String ANSI_CLS = ESC + "[2J"; public static final String ANSI_HOME = ESC + "[H"; // 0,0 public static final String ANSI_HEAD = ESC + "[1G"; // Start of current line, position 1 public static final String ANSI_NORMAL = ESC + "[0m"; public static final String ANSI_BOLD = ESC + "[1m"; public static final String ANSI_FAINT = ESC + "[2m"; public static final String ANSI_ITALIC = ESC + "[3m"; public static final String ANSI_UNDERLINE = ESC + "[4m"; public static final String ANSI_BLINK = ESC + "[5m"; public static final String ANSI_BLINK_FAST = ESC + "[6m"; public static final String ANSI_REVERSE = ESC + "[7m"; public static final String ANSI_CONCEAL = ESC + "[8m"; public static final String ANSI_CROSSED_OUT = ESC + "[9m"; public static final String ANSI_DEFAULT_TEXT = ESC + "[39m"; public static final String ANSI_DEFAULT_BACKGROUND = ESC + "[49m"; private final static String[] SOME_TEXT = { "What happens when the boat sends an email:", "On the boat, you compose your email, and you put it in your outbox.", "Then you turn your SSB on, and you use the SailMail client program to contact a land SailMail station.", "When the contact is established, the messages sitting in the outbox go through the modem and the SSB to ", "be streamed to the land station. On receive, the land station then turns the messages back into digital files,", "and uses its Internet connection to post them on the web. From there, it's the usual email story." }; public static final String ANSI_AT55 = ESC + "[10;10H"; // Actually 10, 10 public static final String ANSI_WHITEONBLUE = ESC + "[37;44m"; public static String ansiSetBackGroundColor(String color) { // ESC[40-47 return ESC + "[4" + color + "m"; } public static String ansiSetTextColor(String color) { // ESC[30-37 return ESC + "[3" + color + "m"; } public static String ansiSetTextAndBackgroundColor(String text, String bg) { // ESC[30-37;40-47 return ESC + "[3" + text + ";4" + bg + "m"; } public static String ansiLocate(int x, int y) { return ESC + "[" + Integer.toString(y) + ";" + Integer.toString(x) + "H"; // Actually Y, X } // An example public static void main(String[] args) { String str80 = " "; AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); // Display 5 rows, like an horizontal bar chart for (int i=0; i<20; i++) { int value1 = (int)Math.round(Math.random() * 80); int value2 = (int)Math.round(Math.random() * 80); int value3 = (int)Math.round(Math.random() * 80); int value4 = (int)Math.round(Math.random() * 80); int value5 = (int)Math.round(Math.random() * 80); String str1 = ""; for (int j=0; j<value1; j++) str1 += "."; String str2 = ""; for (int j=0; j<value2; j++) str2 += "."; String str3 = ""; for (int j=0; j<value3; j++) str3 += "."; String str4 = ""; for (int j=0; j<value4; j++) str4 += "."; String str5 = ""; for (int j=0; j<value5; j++) str5 += "."; str1 = superpose(str1, "Cell 1:" + Integer.toString(value1)); str2 = superpose(str2, "Cell 2:" + Integer.toString(value2)); str3 = superpose(str3, "Cell 3:" + Integer.toString(value3)); str4 = superpose(str4, "Cell 4:" + Integer.toString(value4)); str5 = superpose(str5, "Cell 5:" + Integer.toString(value5)); // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ansiLocate(0, 1) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 1) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_RED) + ANSI_BOLD + str1 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 2) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 2) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_WHITE) + ANSI_BOLD + str2 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 3) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 3) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_YELLOW) + ANSI_BOLD + str3 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 4) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 4) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_GREEN) + ANSI_BOLD + str4 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 5) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 5) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLUE) + ANSI_BOLD + str5 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); try { Thread.sleep(1000L); } catch (Exception ex) {} } System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } public static String superpose(String orig, String override) { byte[] ret = orig.getBytes(); for (int i=0; i<Math.min(orig.length(), override.length()); i++) ret[i] = (byte)override.charAt(i); return new String(ret); } public static void main_(String[] args) { AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_AT55 + ANSI_REVERSE + "10,10 reverse : Hello world" + ANSI_NORMAL); AnsiConsole.out.println(ANSI_HOME + ANSI_WHITEONBLUE + "WhiteOnBlue : Hello world" + ANSI_NORMAL); AnsiConsole.out.print(ANSI_BOLD + "Bold : Press return..." + ANSI_NORMAL); try { System.in.read(); } catch (Exception e) { } // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); AnsiConsole.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); for (String line : SOME_TEXT) { System.out.print(ANSI_HEAD + line); try { Thread.sleep(1000); } catch (Exception ex) {} } System.out.println(); System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } }
12nosanshiro-pi4j-sample
LelandOilDetector/src/adc/utils/EscapeSeq.java
Java
mit
7,897
#!/bin/bash echo Read an ADC, feed a WebSocket # if [ "$PI4J_HOME" = "" ] then PI4J_HOME=/opt/pi4j fi # CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/java_websocket.jar # sudo java -cp $CP -Dws.uri=ws://localhost:9876/ ws.WebSocketFeeder $*
12nosanshiro-pi4j-sample
LelandOilDetector/run.ws
Shell
mit
259
#! /usr/bin/perl -w use strict; use POSIX; use Fcntl; use File::Temp 'tempfile'; use Getopt::Long qw(:config bundling); # Command-line options. our ($start_time) = time (); our ($sim); # Simulator: bochs, qemu, or player. our ($debug) = "none"; # Debugger: none, monitor, or gdb. our ($mem) = 4; # Physical RAM in MB. our ($serial) = 1; # Use serial port for input and output? our ($vga); # VGA output: window, terminal, or none. our ($jitter); # Seed for random timer interrupts, if set. our ($realtime); # Synchronize timer interrupts with real time? our ($timeout); # Maximum runtime in seconds, if set. our ($kill_on_failure); # Abort quickly on test failure? our (@puts); # Files to copy into the VM. our (@gets); # Files to copy out of the VM. our ($as_ref); # Reference to last addition to @gets or @puts. our (@kernel_args); # Arguments to pass to kernel. our (%disks) = (OS => {DEF_FN => 'os.dsk'}, # Disks to give VM. FS => {DEF_FN => 'fs.dsk'}, SCRATCH => {DEF_FN => 'scratch.dsk'}, SWAP => {DEF_FN => 'swap.dsk'}); our (@disks_by_iface) = @disks{qw (OS FS SCRATCH SWAP)}; parse_command_line (); find_disks (); prepare_scratch_disk (); prepare_arguments (); run_vm (); finish_scratch_disk (); exit 0; # Parses the command line. sub parse_command_line { usage (0) if @ARGV == 0 || (@ARGV == 1 && $ARGV[0] eq '--help'); @kernel_args = @ARGV; if (grep ($_ eq '--', @kernel_args)) { @ARGV = (); while ((my $arg = shift (@kernel_args)) ne '--') { push (@ARGV, $arg); } GetOptions ("sim=s" => sub { set_sim ($_[1]) }, "bochs" => sub { set_sim ("bochs") }, "qemu" => sub { set_sim ("qemu") }, "player" => sub { set_sim ("player") }, "debug=s" => sub { set_debug ($_[1]) }, "no-debug" => sub { set_debug ("none") }, "monitor" => sub { set_debug ("monitor") }, "gdb" => sub { set_debug ("gdb") }, "m|memory=i" => \$mem, "j|jitter=i" => sub { set_jitter ($_[1]) }, "r|realtime" => sub { set_realtime () }, "T|timeout=i" => \$timeout, "k|kill-on-failure" => \$kill_on_failure, "v|no-vga" => sub { set_vga ('none'); }, "s|no-serial" => sub { $serial = 0; }, "t|terminal" => sub { set_vga ('terminal'); }, "p|put-file=s" => sub { add_file (\@puts, $_[1]); }, "g|get-file=s" => sub { add_file (\@gets, $_[1]); }, "a|as=s" => sub { set_as ($_[1]); }, "h|help" => sub { usage (0); }, "os-disk=s" => \$disks{OS}{FILE_NAME}, "fs-disk=s" => \$disks{FS}{FILE_NAME}, "scratch-disk=s" => \$disks{SCRATCH}{FILE_NAME}, "swap-disk=s" => \$disks{SWAP}{FILE_NAME}, "0|disk-0|hda=s" => \$disks_by_iface[0]{FILE_NAME}, "1|disk-1|hdb=s" => \$disks_by_iface[1]{FILE_NAME}, "2|disk-2|hdc=s" => \$disks_by_iface[2]{FILE_NAME}, "3|disk-3|hdd=s" => \$disks_by_iface[3]{FILE_NAME}) or exit 1; } $sim = "bochs" if !defined $sim; $debug = "none" if !defined $debug; $vga = "window" if !defined $vga; undef $timeout, print "warning: disabling timeout with --$debug\n" if defined ($timeout) && $debug ne 'none'; print "warning: enabling serial port for -k or --kill-on-failure\n" if $kill_on_failure && !$serial; } # usage($exitcode). # Prints a usage message and exits with $exitcode. sub usage { my ($exitcode) = @_; $exitcode = 1 unless defined $exitcode; print <<'EOF'; pintos, a utility for running Pintos in a simulator Usage: pintos [OPTION...] -- [ARGUMENT...] where each OPTION is one of the following options and each ARGUMENT is passed to Pintos kernel verbatim. Simulator selection: --bochs (default) Use Bochs as simulator --qemu Use QEMU as simulator --player Use VMware Player as simulator Debugger selection: --no-debug (default) No debugger --monitor Debug with simulator's monitor --gdb Debug with gdb Display options: (default is both VGA and serial) -v, --no-vga No VGA display or keyboard -s, --no-serial No serial input or output -t, --terminal Display VGA in terminal (Bochs only) Timing options: (Bochs only) -j SEED Randomize timer interrupts -r, --realtime Use realistic, not reproducible, timings Testing options: -T, --timeout=N Kill Pintos after N seconds CPU time or N*load_avg seconds wall-clock time (whichever comes first) -k, --kill-on-failure Kill Pintos a few seconds after a kernel or user panic, test failure, or triple fault Configuration options: -m, --mem=N Give Pintos N MB physical RAM (default: 4) File system commands (for `run' command): -p, --put-file=HOSTFN Copy HOSTFN into VM, by default under same name -g, --get-file=GUESTFN Copy GUESTFN out of VM, by default under same name -a, --as=FILENAME Specifies guest (for -p) or host (for -g) file name Disk options: (name an existing FILE or specify SIZE in MB for a temp disk) --os-disk=FILE Set OS disk file (default: os.dsk) --fs-disk=FILE|SIZE Set FS disk file (default: fs.dsk) --scratch-disk=FILE|SIZE Set scratch disk (default: scratch.dsk) --swap-disk=FILE|SIZE Set swap disk file (default: swap.dsk) Other options: -h, --help Display this help message. EOF exit $exitcode; } # Sets the simulator. sub set_sim { my ($new_sim) = @_; die "--$new_sim conflicts with --$sim\n" if defined ($sim) && $sim ne $new_sim; $sim = $new_sim; } # Sets the debugger. sub set_debug { my ($new_debug) = @_; die "--$new_debug conflicts with --$debug\n" if $debug ne 'none' && $new_debug ne 'none' && $debug ne $new_debug; $debug = $new_debug; } # Sets VGA output destination. sub set_vga { my ($new_vga) = @_; if (defined ($vga) && $vga ne $new_vga) { print "warning: conflicting vga display options\n"; } $vga = $new_vga; } # Sets randomized timer interrupts. sub set_jitter { my ($new_jitter) = @_; die "--realtime conflicts with --jitter\n" if defined $realtime; die "different --jitter already defined\n" if defined $jitter && $jitter != $new_jitter; $jitter = $new_jitter; } # Sets real-time timer interrupts. sub set_realtime { die "--realtime conflicts with --jitter\n" if defined $jitter; $realtime = 1; } # add_file(\@list, $file) # # Adds [$file] to @list, which should be @puts or @gets. # Sets $as_ref to point to the added element. sub add_file { my ($list, $file) = @_; $as_ref = [$file]; push (@$list, $as_ref); } # Sets the guest/host name for the previous put/get. sub set_as { my ($as) = @_; die "-a (or --as) is only allowed after -p or -g\n" if !defined $as_ref; die "Only one -a (or --as) is allowed after -p or -g\n" if defined $as_ref->[1]; $as_ref->[1] = $as; } # Locates the files used to back each of the virtual disks, # and creates temporary disks. sub find_disks { for my $disk (values %disks) { # If there's no assigned file name but the default file exists, # try to assign a default file name. if (!defined ($disk->{FILE_NAME})) { for my $try_fn ($disk->{DEF_FN}, "build/" . $disk->{DEF_FN}) { $disk->{FILE_NAME} = $try_fn, last if -e $try_fn; } } # If there's no file name, we're done. next if !defined ($disk->{FILE_NAME}); if ($disk->{FILE_NAME} =~ /^\d+(\.\d+)?|\.\d+$/) { # Create a temporary disk of approximately the specified # size in megabytes. die "OS disk can't be temporary\n" if $disk == $disks{OS}; my ($mb) = $disk->{FILE_NAME}; undef $disk->{FILE_NAME}; my ($cyl_size) = 512 * 16 * 63; extend_disk ($disk, ceil ($mb * 2) * $cyl_size); } else { # The file must exist and have nonzero size. -e $disk->{FILE_NAME} or die "$disk->{FILE_NAME}: stat: $!\n"; -s _ or die "$disk->{FILE_NAME}: disk has zero size\n"; } } # Warn about (potentially) missing disks. die "Cannot find OS disk\n" if !defined $disks{OS}{FILE_NAME}; if (my ($project) = `pwd` =~ /\b(threads|userprog|vm|filesys)\b/) { if ((grep ($project eq $_, qw (userprog vm filesys))) && !defined ($disks{FS}{FILE_NAME})) { print STDERR "warning: it looks like you're running the $project "; print STDERR "project, but no file system disk is present\n"; } if ($project eq 'vm' && !defined $disks{SWAP}{FILE_NAME}) { print STDERR "warning: it looks like you're running the $project "; print STDERR "project, but no swap disk is present\n"; } } } # Prepare the scratch disk for gets and puts. sub prepare_scratch_disk { if (@puts) { # Write ustar header and data for each file. put_scratch_file ($_->[0], defined $_->[1] ? $_->[1] : $_->[0]) foreach @puts; # Write end-of-archive marker. #print { $disks{SCRATCH}{HANDLE} } "\0" x 1024; write_fully ($disks{SCRATCH}{HANDLE}, $disks{SCRATCH}{FILE_NAME}, "\0" x 1024); } # Make sure the scratch disk is big enough to get big files. extend_disk ($disks{SCRATCH}, @gets * 1024 * 1024) if @gets; } # Read "get" files from the scratch disk. sub finish_scratch_disk { # We need to start reading the scratch disk from the beginning again. if (@gets) { close ($disks{SCRATCH}{HANDLE}); undef ($disks{SCRATCH}{HANDLE}); } # Read each file. # If reading fails, delete that file and all subsequent files. my ($ok) = 1; foreach my $get (@gets) { my ($name) = defined ($get->[1]) ? $get->[1] : $get->[0]; my ($error) = get_scratch_file ($name); if ($error) { print STDERR "getting $name failed ($error)\n"; die "$name: unlink: $!\n" if !unlink ($name) && !$!{ENOENT}; $ok = 0; } } } # mk_ustar_field($number, $size) # # Returns $number in a $size-byte numeric field in the format used by # the standard ustar archive header. sub mk_ustar_field { my ($number, $size) = @_; my ($len) = $size - 1; my ($out) = sprintf ("%0${len}o", $number) . "\0"; die "$number: too large for $size-byte octal ustar field\n" if length ($out) != $size; return $out; } # calc_ustar_chksum($s) # # Calculates and returns the ustar checksum of 512-byte ustar archive # header $s. sub calc_ustar_chksum { my ($s) = @_; die if length ($s) != 512; substr ($s, 148, 8, ' ' x 8); return unpack ("%32a*", $s); } # put_scratch_file($src_file_name, $dst_file_name). # # Copies $src_file_name into the scratch disk for extraction as # $dst_file_name. sub put_scratch_file { my ($src_file_name, $dst_file_name) = @_; my ($disk_handle, $disk_file_name) = open_disk ($disks{SCRATCH}); print "Copying $src_file_name to scratch partition...\n"; # ustar format supports up to 100 characters for a file name, and # even longer names given some common properties, but our code in # the Pintos kernel only supports at most 99 characters. die "$dst_file_name: name too long (max 99 characters)\n" if length ($dst_file_name) > 99; # Compose and write ustar header. stat $src_file_name or die "$src_file_name: stat: $!\n"; my ($size) = -s _; my ($header) = (pack ("a100", $dst_file_name) # name . mk_ustar_field (0644, 8) # mode . mk_ustar_field (0, 8) # uid . mk_ustar_field (0, 8) # gid . mk_ustar_field ($size, 12) # size . mk_ustar_field (1136102400, 12) # mtime . (' ' x 8) # chksum . '0' # typeflag . ("\0" x 100) # linkname . "ustar\0" # magic . "00" # version . "root" . ("\0" x 28) # uname . "root" . ("\0" x 28) # gname . "\0" x 8 # devmajor . "\0" x 8 # devminor . ("\0" x 155)) # prefix . "\0" x 12; # pad to 512 bytes substr ($header, 148, 8) = mk_ustar_field (calc_ustar_chksum ($header), 8); write_fully ($disk_handle, $disk_file_name, $header); # Copy file data. my ($put_handle); sysopen ($put_handle, $src_file_name, O_RDONLY) or die "$src_file_name: open: $!\n"; copy_file ($put_handle, $src_file_name, $disk_handle, $disk_file_name, $size); die "$src_file_name: changed size while being read\n" if $size != -s $put_handle; close ($put_handle); # Round up disk data to beginning of next sector. write_fully ($disk_handle, $disk_file_name, "\0" x (512 - $size % 512)) if $size % 512; } # get_scratch_file($file). # # Copies from the scratch disk to $file. # Returns 1 if successful, 0 on failure. sub get_scratch_file { my ($get_file_name) = @_; my ($disk_handle, $disk_file_name) = open_disk ($disks{SCRATCH}); print "Copying $get_file_name out of $disk_file_name...\n"; # Read ustar header sector. my ($header) = read_fully ($disk_handle, $disk_file_name, 512); return "scratch disk tar archive ends unexpectedly" if $header eq ("\0" x 512); # Verify magic numbers. return "corrupt ustar signature" if substr ($header, 257, 6) ne "ustar\0"; return "invalid ustar version" if substr ($header, 263, 2) ne '00'; # Verify checksum. my ($chksum) = oct (unpack ("Z*", substr ($header, 148, 8))); my ($correct_chksum) = calc_ustar_chksum ($header); return "checksum mismatch" if $chksum != $correct_chksum; # Get type. my ($typeflag) = substr ($header, 156, 1); return "not a regular file" if $typeflag ne '0' && $typeflag ne "\0"; # Get size. my ($size) = oct (unpack ("Z*", substr ($header, 124, 12))); return "bad size $size\n" if $size < 0; # Copy file data. my ($get_handle); sysopen ($get_handle, $get_file_name, O_WRONLY | O_CREAT, 0666) or die "$get_file_name: create: $!\n"; copy_file ($disk_handle, $disk_file_name, $get_handle, $get_file_name, $size); close ($get_handle); # Skip forward in disk up to beginning of next sector. read_fully ($disk_handle, $disk_file_name, 512 - $size % 512) if $size % 512; return 0; } # Prepares the arguments to pass to the Pintos kernel, # and then write them into Pintos bootloader. sub prepare_arguments { my (@args); push (@args, shift (@kernel_args)) while @kernel_args && $kernel_args[0] =~ /^-/; push (@args, 'extract') if @puts; push (@args, @kernel_args); push (@args, 'append', $_->[0]) foreach @gets; write_cmd_line ($disks{OS}, @args); } # Writes @args into the Pintos bootloader at the beginning of $disk. sub write_cmd_line { my ($disk, @args) = @_; # Figure out command line to write. my ($arg_cnt) = pack ("V", scalar (@args)); my ($args) = join ('', map ("$_\0", @args)); die "command line exceeds 128 bytes" if length ($args) > 128; $args .= "\0" x (128 - length ($args)); # Write command line. my ($handle, $file_name) = open_disk_copy ($disk); print "Writing command line to $file_name...\n"; sysseek ($handle, 0x17a, 0) == 0x17a or die "$file_name: seek: $!\n"; syswrite ($handle, "$arg_cnt$args") or die "$file_name: write: $!\n"; } # Running simulators. # Runs the selected simulator. sub run_vm { if ($sim eq 'bochs') { run_bochs (); } elsif ($sim eq 'qemu') { run_qemu (); } elsif ($sim eq 'player') { run_player (); } else { die "unknown simulator `$sim'\n"; } } # Runs Bochs. sub run_bochs { # Select Bochs binary based on the chosen debugger. my ($bin) = $debug eq 'monitor' ? 'bochs-dbg' : 'bochs'; my ($squish_pty); if ($serial) { $squish_pty = find_in_path ("squish-pty"); print "warning: can't find squish-pty, so terminal input will fail\n" if !defined $squish_pty; } # Write bochsrc.txt configuration file. open (BOCHSRC, ">", "bochsrc.txt") or die "bochsrc.txt: create: $!\n"; print BOCHSRC <<EOF; romimage: file=\$BXSHARE/BIOS-bochs-latest vgaromimage: file=\$BXSHARE/VGABIOS-lgpl-latest boot: disk cpu: ips=1000000 megs: $mem log: bochsout.txt panic: action=fatal EOF print BOCHSRC "gdbstub: enabled=1\n" if $debug eq 'gdb'; if ($realtime) { print BOCHSRC "clock: sync=realtime\n"; } else { print BOCHSRC "clock: sync=none, time0=0\n"; } print_bochs_disk_line ("ata0-master", 0); print_bochs_disk_line ("ata0-slave", 1); if (defined ($disks_by_iface[2]{FILE_NAME}) || defined ($disks_by_iface[3]{FILE_NAME})) { print BOCHSRC "ata1: enabled=1, ioaddr1=0x170, ", "ioaddr2=0x370, irq=15\n"; print_bochs_disk_line ("ata1-master", 2); print_bochs_disk_line ("ata1-slave", 3); } if ($vga ne 'terminal') { if ($serial) { my $mode = defined ($squish_pty) ? "term" : "file"; print BOCHSRC "com1: enabled=1, mode=$mode, dev=/dev/stdout\n"; } print BOCHSRC "display_library: nogui\n" if $vga eq 'none'; } else { print BOCHSRC "display_library: term\n"; } close (BOCHSRC); # Compose Bochs command line. my (@cmd) = ($bin, '-q'); unshift (@cmd, $squish_pty) if defined $squish_pty; push (@cmd, '-j', $jitter) if defined $jitter; # Run Bochs. print join (' ', @cmd), "\n"; my ($exit) = xsystem (@cmd); if (WIFEXITED ($exit)) { # Bochs exited normally. # Ignore the exit code; Bochs normally exits with status 1, # which is weird. } elsif (WIFSIGNALED ($exit)) { die "Bochs died with signal ", WTERMSIG ($exit), "\n"; } else { die "Bochs died: code $exit\n"; } } # print_bochs_disk_line($device, $iface) # # If IDE interface $iface has a disk attached, prints a bochsrc.txt # line for attaching it to $device. sub print_bochs_disk_line { my ($device, $iface) = @_; my ($disk) = $disks_by_iface[$iface]; my ($file) = $disk->{FILE_NAME}; if (defined $file) { my (%geom) = disk_geometry ($disk); print BOCHSRC "$device: type=disk, path=$file, mode=flat, "; print BOCHSRC "cylinders=$geom{C}, heads=$geom{H}, spt=$geom{S}, "; print BOCHSRC "translation=none\n"; } } # Runs QEMU. sub run_qemu { print "warning: qemu doesn't support --terminal\n" if $vga eq 'terminal'; print "warning: qemu doesn't support jitter\n" if defined $jitter; my (@cmd) = ('qemu'); for my $iface (0...3) { my ($option) = ('-hda', '-hdb', '-hdc', '-hdd')[$iface]; push (@cmd, $option, $disks_by_iface[$iface]{FILE_NAME}) if defined $disks_by_iface[$iface]{FILE_NAME}; } push (@cmd, '-m', $mem); push (@cmd, '-net', 'none'); push (@cmd, '-nographic') if $vga eq 'none'; push (@cmd, '-serial', 'stdio') if $serial && $vga ne 'none'; push (@cmd, '-S') if $debug eq 'monitor'; push (@cmd, '-s', '-S') if $debug eq 'gdb'; push (@cmd, '-monitor', 'null') if $vga eq 'none' && $debug eq 'none'; run_command (@cmd); } # player_unsup($flag) # # Prints a message that $flag is unsupported by VMware Player. sub player_unsup { my ($flag) = @_; print "warning: no support for $flag with VMware Player\n"; } # Runs VMware Player. sub run_player { player_unsup ("--$debug") if $debug ne 'none'; player_unsup ("--no-vga") if $vga eq 'none'; player_unsup ("--terminal") if $vga eq 'terminal'; player_unsup ("--jitter") if defined $jitter; player_unsup ("--timeout"), undef $timeout if defined $timeout; player_unsup ("--kill-on-failure"), undef $kill_on_failure if defined $kill_on_failure; # Memory size must be multiple of 4. $mem = int (($mem + 3) / 4) * 4; open (VMX, ">", "pintos.vmx") or die "pintos.vmx: create: $!\n"; chmod 0777 & ~umask, "pintos.vmx"; print VMX <<EOF; #! /usr/bin/vmware -G config.version = 8 guestOS = "linux" memsize = $mem floppy0.present = FALSE usb.present = FALSE sound.present = FALSE gui.exitAtPowerOff = TRUE gui.exitOnCLIHLT = TRUE gui.powerOnAtStartUp = TRUE EOF print VMX <<EOF if $serial; serial0.present = TRUE serial0.fileType = "pipe" serial0.fileName = "pintos.socket" serial0.pipe.endPoint = "client" serial0.tryNoRxLoss = "TRUE" EOF for (my ($i) = 0; $i < 4; $i++) { my ($disk) = $disks_by_iface[$i]; my ($dsk) = $disk->{FILE_NAME}; next if !defined $dsk; my ($device) = "ide" . int ($i / 2) . ":" . ($i % 2); my ($pln) = "$device.pln"; print VMX <<EOF; $device.present = TRUE $device.deviceType = "plainDisk" $device.fileName = "$pln" EOF open (URANDOM, '<', '/dev/urandom') or die "/dev/urandom: open: $!\n"; my ($bytes); sysread (URANDOM, $bytes, 4) == 4 or die "/dev/urandom: read: $!\n"; close (URANDOM); my ($cid) = unpack ("L", $bytes); my (%geom) = disk_geometry ($disk); open (PLN, ">", $pln) or die "$pln: create: $!\n"; print PLN <<EOF; version=1 CID=$cid parentCID=ffffffff createType="monolithicFlat" RW $geom{CAPACITY} FLAT "$dsk" 0 # The Disk Data Base #DDB ddb.adapterType = "ide" ddb.virtualHWVersion = "4" ddb.toolsVersion = "2" ddb.geometry.cylinders = "$geom{C}" ddb.geometry.heads = "$geom{H}" ddb.geometry.sectors = "$geom{S}" EOF close (PLN); } close (VMX); my ($squish_unix); if ($serial) { $squish_unix = find_in_path ("squish-unix"); print "warning: can't find squish-unix, so terminal input ", "and output will fail\n" if !defined $squish_unix; } my ($vmx) = getcwd () . "/pintos.vmx"; my (@cmd) = ("vmplayer", $vmx); unshift (@cmd, $squish_unix, "pintos.socket") if $squish_unix; print join (' ', @cmd), "\n"; xsystem (@cmd); } # Disk utilities. # open_disk($disk) # # Opens $disk, if it is not already open, and returns its file handle # and file name. sub open_disk { my ($disk) = @_; if (!defined ($disk->{HANDLE})) { if ($disk->{FILE_NAME}) { sysopen ($disk->{HANDLE}, $disk->{FILE_NAME}, O_RDWR) or die "$disk->{FILE_NAME}: open: $!\n"; } else { ($disk->{HANDLE}, $disk->{FILE_NAME}) = tempfile (UNLINK => 1, SUFFIX => '.dsk'); } } return ($disk->{HANDLE}, $disk->{FILE_NAME}); } # open_disk_copy($disk) # # Makes a temporary copy of $disk and returns its file handle and file name. sub open_disk_copy { my ($disk) = @_; die if !$disk->{FILE_NAME}; my ($orig_handle, $orig_file_name) = open_disk ($disk); my ($cp_handle, $cp_file_name) = tempfile (UNLINK => 1, SUFFIX => '.dsk'); copy_file ($orig_handle, $orig_file_name, $cp_handle, $cp_file_name, -s $orig_handle); return ($disk->{HANDLE}, $disk->{FILE_NAME}) = ($cp_handle, $cp_file_name); } # extend_disk($disk, $size) # # Extends $disk, if necessary, so that it is at least $size bytes # long. sub extend_disk { my ($disk, $size) = @_; my ($handle, $file_name) = open_disk ($disk); if (-s ($handle) < $size) { sysseek ($handle, $size - 1, 0) == $size - 1 or die "$file_name: seek: $!\n"; syswrite ($handle, "\0") == 1 or die "$file_name: write: $!\n"; } } # disk_geometry($file) # # Examines $file and returns a valid IDE disk geometry for it, as a # hash. sub disk_geometry { my ($disk) = @_; my ($file) = $disk->{FILE_NAME}; my ($size) = -s $file; die "$file: stat: $!\n" if !defined $size; die "$file: size not a multiple of 512 bytes\n" if $size % 512; my ($cyl_size) = 512 * 16 * 63; my ($cylinders) = ceil ($size / $cyl_size); extend_disk ($disk, $cylinders * $cyl_size) if $size % $cyl_size; return (CAPACITY => $size / 512, C => $cylinders, H => 16, S => 63); } # copy_file($from_handle, $from_file_name, $to_handle, $to_file_name, $size) # # Copies $size bytes from $from_handle to $to_handle. # $from_file_name and $to_file_name are used in error messages. sub copy_file { my ($from_handle, $from_file_name, $to_handle, $to_file_name, $size) = @_; while ($size > 0) { my ($chunk_size) = 4096; $chunk_size = $size if $chunk_size > $size; $size -= $chunk_size; my ($data) = read_fully ($from_handle, $from_file_name, $chunk_size); write_fully ($to_handle, $to_file_name, $data); } } # read_fully($handle, $file_name, $bytes) # # Reads exactly $bytes bytes from $handle and returns the data read. # $file_name is used in error messages. sub read_fully { my ($handle, $file_name, $bytes) = @_; my ($data); my ($read_bytes) = sysread ($handle, $data, $bytes); die "$file_name: read: $!\n" if !defined $read_bytes; die "$file_name: unexpected end of file\n" if $read_bytes != $bytes; return $data; } # write_fully($handle, $file_name, $data) # # Write $data to $handle. # $file_name is used in error messages. sub write_fully { my ($handle, $file_name, $data) = @_; my ($written_bytes) = syswrite ($handle, $data); die "$file_name: write: $!\n" if !defined $written_bytes; die "$file_name: short write\n" if $written_bytes != length $data; } # Subprocess utilities. # run_command(@args) # # Runs xsystem(@args). # Also prints the command it's running and checks that it succeeded. sub run_command { print join (' ', @_), "\n"; die "command failed\n" if xsystem (@_); } # xsystem(@args) # # Creates a subprocess via exec(@args) and waits for it to complete. # Relays common signals to the subprocess. # If $timeout is set then the subprocess will be killed after that long. sub xsystem { # QEMU turns off local echo and does not restore it if killed by a signal. # We compensate by restoring it ourselves. my $cleanup = sub {}; if (isatty (0)) { my $termios = POSIX::Termios->new; $termios->getattr (0); $cleanup = sub { $termios->setattr (0, &POSIX::TCSANOW); } } # Create pipe for filtering output. pipe (my $in, my $out) or die "pipe: $!\n" if $kill_on_failure; my ($pid) = fork; if (!defined ($pid)) { # Fork failed. die "fork: $!\n"; } elsif (!$pid) { # Running in child process. dup2 (fileno ($out), STDOUT_FILENO) or die "dup2: $!\n" if $kill_on_failure; exec_setitimer (@_); } else { # Running in parent process. close $out if $kill_on_failure; my ($cause); local $SIG{ALRM} = sub { timeout ($pid, $cause, $cleanup); }; local $SIG{INT} = sub { relay_signal ($pid, "INT", $cleanup); }; local $SIG{TERM} = sub { relay_signal ($pid, "TERM", $cleanup); }; alarm ($timeout * get_load_average () + 1) if defined ($timeout); if ($kill_on_failure) { # Filter output. my ($buf) = ""; my ($boots) = 0; local ($|) = 1; for (;;) { if (waitpid ($pid, WNOHANG) != 0) { # Subprocess died. Pass through any remaining data. print $buf while sysread ($in, $buf, 4096) > 0; last; } # Read and print out pipe data. my ($len) = length ($buf); waitpid ($pid, 0), last if sysread ($in, $buf, 4096, $len) <= 0; print substr ($buf, $len); # Remove full lines from $buf and scan them for keywords. while ((my $idx = index ($buf, "\n")) >= 0) { local $_ = substr ($buf, 0, $idx + 1, ''); next if defined ($cause); if (/(Kernel PANIC|User process ABORT)/ ) { $cause = "\L$1\E"; alarm (5); } elsif (/Pintos booting/ && ++$boots > 1) { $cause = "triple fault"; alarm (5); } elsif (/FAILED/) { $cause = "test failure"; alarm (5); } } } } else { waitpid ($pid, 0); } alarm (0); &$cleanup (); if (WIFSIGNALED ($?) && WTERMSIG ($?) == SIGVTALRM ()) { seek (STDOUT, 0, 2); print "\nTIMEOUT after $timeout seconds of host CPU time\n"; exit 0; } return $?; } } # relay_signal($pid, $signal, &$cleanup) # # Relays $signal to $pid and then reinvokes it for us with the default # handler. Also cleans up temporary files and invokes $cleanup. sub relay_signal { my ($pid, $signal, $cleanup) = @_; kill $signal, $pid; eval { File::Temp::cleanup() }; # Not defined in old File::Temp. &$cleanup (); $SIG{$signal} = 'DEFAULT'; kill $signal, getpid (); } # timeout($pid, $cause, &$cleanup) # # Interrupts $pid and dies with a timeout error message, # after invoking $cleanup. sub timeout { my ($pid, $cause, $cleanup) = @_; kill "INT", $pid; waitpid ($pid, 0); &$cleanup (); seek (STDOUT, 0, 2); if (!defined ($cause)) { my ($load_avg) = `uptime` =~ /(load average:.*)$/i; print "\nTIMEOUT after ", time () - $start_time, " seconds of wall-clock time"; print " - $load_avg" if defined $load_avg; print "\n"; } else { print "Simulation terminated due to $cause.\n"; } exit 0; } # Returns the system load average over the last minute. # If the load average is less than 1.0 or cannot be determined, returns 1.0. sub get_load_average { my ($avg) = `uptime` =~ /load average:\s*([^,]+),/; return $avg >= 1.0 ? $avg : 1.0; } # Calls setitimer to set a timeout, then execs what was passed to us. sub exec_setitimer { if (defined $timeout) { if ($ ge 5.8.0) { eval " use Time::HiRes qw(setitimer ITIMER_VIRTUAL); setitimer (ITIMER_VIRTUAL, $timeout, 0); "; } else { { exec ("setitimer-helper", $timeout, @_); }; exit 1 if !$!{ENOENT}; print STDERR "warning: setitimer-helper is not installed, so ", "CPU time limit will not be enforced\n"; } } exec (@_); exit (1); } sub SIGVTALRM { use Config; my $i = 0; foreach my $name (split(' ', $Config{sig_name})) { return $i if $name eq 'VTALRM'; $i++; } return 0; } # find_in_path ($program) # # Searches for $program in $ENV{PATH}. # Returns $program if found, otherwise undef. sub find_in_path { my ($program) = @_; -x "$_/$program" and return $program foreach split (':', $ENV{PATH}); return; }
10cm
trunk/10cm/pintos/src/utils/pintos
Perl
oos
29,493
#! /usr/bin/perl -w use strict; # Check command line. if (grep ($_ eq '-h' || $_ eq '--help', @ARGV)) { print <<'EOF'; backtrace, for converting raw addresses into symbolic backtraces usage: backtrace [BINARY]... ADDRESS... where BINARY is the binary file or files from which to obtain symbols and ADDRESS is a raw address to convert to a symbol name. If no BINARY is unspecified, the default is the first of kernel.o or build/kernel.o that exists. If multiple binaries are specified, each symbol printed is from the first binary that contains a match. The ADDRESS list should be taken from the "Call stack:" printed by the kernel. Read "Backtraces" in the "Debugging Tools" chapter of the Pintos documentation for more information. EOF exit 0; } die "backtrace: at least one argument required (use --help for help)\n" if @ARGV == 0; # Drop garbage inserted by kernel. @ARGV = grep (!/^(call|stack:?|[-+])$/i, @ARGV); s/\.$// foreach @ARGV; # Find binaries. my (@binaries); while ($ARGV[0] !~ /^0x/) { my ($bin) = shift @ARGV; die "backtrace: $bin: not found (use --help for help)\n" if ! -e $bin; push (@binaries, $bin); } if (!@binaries) { my ($bin); if (-e 'kernel.o') { $bin = 'kernel.o'; } elsif (-e 'build/kernel.o') { $bin = 'build/kernel.o'; } else { die "backtrace: no binary specified and neither \"kernel.o\" nor \"build/kernel.o\" exists (use --help for help)\n"; } push (@binaries, $bin); } # Find addr2line. my ($a2l) = search_path ("i386-elf-addr2line") || search_path ("addr2line"); if (!$a2l) { die "backtrace: neither `i386-elf-addr2line' nor `addr2line' in PATH\n"; } sub search_path { my ($target) = @_; for my $dir (split (':', $ENV{PATH})) { my ($file) = "$dir/$target"; return $file if -e $file; } return undef; } # Figure out backtrace. my (@locs) = map ({ADDR => $_}, @ARGV); for my $bin (@binaries) { open (A2L, "$a2l -fe $bin " . join (' ', map ($_->{ADDR}, @locs)) . "|"); for (my ($i) = 0; <A2L>; $i++) { my ($function, $line); chomp ($function = $_); chomp ($line = <A2L>); next if defined $locs[$i]{BINARY}; if ($function ne '??' || $line ne '??:0') { $locs[$i]{FUNCTION} = $function; $locs[$i]{LINE} = $line; $locs[$i]{BINARY} = $bin; } } close (A2L); } # Print backtrace. my ($cur_binary); for my $loc (@locs) { if (defined ($loc->{BINARY}) && @binaries > 1 && (!defined ($cur_binary) || $loc->{BINARY} ne $cur_binary)) { $cur_binary = $loc->{BINARY}; print "In $cur_binary:\n"; } my ($addr) = $loc->{ADDR}; $addr = sprintf ("0x%08x", hex ($addr)) if $addr =~ /^0x[0-9a-f]+$/i; print $addr, ": "; if (defined ($loc->{BINARY})) { my ($function) = $loc->{FUNCTION}; my ($line) = $loc->{LINE}; $line =~ s/^(\.\.\/)*//; $line = "..." . substr ($line, -25) if length ($line) > 28; print "$function ($line)"; } else { print "(unknown)"; } print "\n"; }
10cm
trunk/10cm/pintos/src/utils/backtrace
Perl
oos
2,951
#! /usr/bin/perl use strict; use warnings; use POSIX; use Getopt::Long; use Fcntl 'SEEK_SET'; GetOptions ("h|help" => sub { usage (0); }) or exit 1; usage (1) if @ARGV != 2; my ($disk, $mb) = @ARGV; die "$disk: already exists\n" if -e $disk; die "\"$mb\" is not a valid size in megabytes\n" if $mb <= 0 || $mb > 1024 || $mb !~ /^\d+(\.\d+)?|\.\d+/; my ($cyl_cnt) = ceil ($mb * 2); my ($cyl_bytes) = 512 * 16 * 63; my ($bytes) = $cyl_bytes * $cyl_cnt; open (DISK, '>', $disk) or die "$disk: create: $!\n"; sysseek (DISK, $bytes - 1, SEEK_SET) or die "$disk: seek: $!\n"; syswrite (DISK, "\0", 1) == 1 or die "$disk: write: $!\n"; close (DISK) or die "$disk: close: $!\n"; sub usage { print <<'EOF'; pintos-mkdisk, a utility for creating Pintos virtual disks Usage: pintos DISKFILE MB where DISKFILE is the file to use for the disk and MB is the disk size in (approximate) megabytes. Options: -h, --help Display this help message. EOF exit (@_); }
10cm
trunk/10cm/pintos/src/utils/pintos-mkdisk
Perl
oos
975
#define _GNU_SOURCE 1 #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stropts.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/socket.h> #include <sys/un.h> #include <termios.h> #include <unistd.h> static void fail_io (const char *msg, ...) __attribute__ ((noreturn)) __attribute__ ((format (printf, 1, 2))); /* Prints MSG, formatting as with printf(), plus an error message based on errno, and exits. */ static void fail_io (const char *msg, ...) { va_list args; va_start (args, msg); vfprintf (stderr, msg, args); va_end (args); if (errno != 0) fprintf (stderr, ": %s", strerror (errno)); putc ('\n', stderr); exit (EXIT_FAILURE); } /* If FD is a terminal, configures it for noncanonical input mode with VMIN and VTIME set as indicated. If FD is not a terminal, has no effect. */ static void make_noncanon (int fd, int vmin, int vtime) { if (isatty (fd)) { struct termios termios; if (tcgetattr (fd, &termios) < 0) fail_io ("tcgetattr"); termios.c_lflag &= ~(ICANON | ECHO); termios.c_cc[VMIN] = vmin; termios.c_cc[VTIME] = vtime; if (tcsetattr (fd, TCSANOW, &termios) < 0) fail_io ("tcsetattr"); } } /* Make FD non-blocking if NONBLOCKING is true, or blocking if NONBLOCKING is false. */ static void make_nonblocking (int fd, bool nonblocking) { int flags = fcntl (fd, F_GETFL); if (flags < 0) fail_io ("fcntl"); if (nonblocking) flags |= O_NONBLOCK; else flags &= ~O_NONBLOCK; if (fcntl (fd, F_SETFL, flags) < 0) fail_io ("fcntl"); } /* Handle a read or write on *FD, which is the socket if FD_IS_SOCK is true, that returned end-of-file or error indication RETVAL. The system call is named CALL, for use in error messages. Returns true if processing may continue, false if we're all done. */ static bool handle_error (ssize_t retval, int *fd, bool fd_is_sock, const char *call) { if (retval == 0) { if (fd_is_sock) return false; else { *fd = -1; return true; } } else fail_io (call); } /* Copies data from stdin to SOCK and from SOCK to stdout until no more data can be read or written. */ static void relay (int sock) { struct pipe { int in, out; char buf[BUFSIZ]; size_t size, ofs; bool active; }; struct pipe pipes[2]; /* In case stdin is a file, go back to the beginning. This allows replaying the input on reset. */ lseek (STDIN_FILENO, 0, SEEK_SET); /* Make SOCK, stdin, and stdout non-blocking. */ make_nonblocking (sock, true); make_nonblocking (STDIN_FILENO, true); make_nonblocking (STDOUT_FILENO, true); /* Configure noncanonical mode on stdin to avoid waiting for end-of-line. */ make_noncanon (STDIN_FILENO, 1, 0); memset (pipes, 0, sizeof pipes); pipes[0].in = STDIN_FILENO; pipes[0].out = sock; pipes[1].in = sock; pipes[1].out = STDOUT_FILENO; while (pipes[0].in != -1 || pipes[1].in != -1 || (pipes[1].size && pipes[1].out != -1)) { fd_set read_fds, write_fds; sigset_t empty_set; int retval; int i; FD_ZERO (&read_fds); FD_ZERO (&write_fds); for (i = 0; i < 2; i++) { struct pipe *p = &pipes[i]; /* Don't do anything with the stdin->sock pipe until we have some data for the sock->stdout pipe. If we get too eager, vmplayer will throw away our input. */ if (i == 0 && !pipes[1].active) continue; if (p->in != -1 && p->size + p->ofs < sizeof p->buf) FD_SET (p->in, &read_fds); if (p->out != -1 && p->size > 0) FD_SET (p->out, &write_fds); } sigemptyset (&empty_set); retval = pselect (FD_SETSIZE, &read_fds, &write_fds, NULL, NULL, &empty_set); if (retval < 0) { if (errno == EINTR) { /* Child died. Do final relaying. */ struct pipe *p = &pipes[1]; if (p->out == -1) exit (0); make_nonblocking (STDOUT_FILENO, false); for (;;) { ssize_t n; /* Write buffer. */ while (p->size > 0) { n = write (p->out, p->buf + p->ofs, p->size); if (n < 0) fail_io ("write"); else if (n == 0) fail_io ("zero-length write"); p->ofs += n; p->size -= n; } p->ofs = 0; p->size = n = read (p->in, p->buf, sizeof p->buf); if (n <= 0) exit (0); } } fail_io ("select"); } for (i = 0; i < 2; i++) { struct pipe *p = &pipes[i]; if (p->in != -1 && FD_ISSET (p->in, &read_fds)) { ssize_t n = read (p->in, p->buf + p->ofs + p->size, sizeof p->buf - p->ofs - p->size); if (n > 0) { p->active = true; p->size += n; if (p->size == BUFSIZ && p->ofs != 0) { memmove (p->buf, p->buf + p->ofs, p->size); p->ofs = 0; } } else if (!handle_error (n, &p->in, p->in == sock, "read")) return; } if (p->out != -1 && FD_ISSET (p->out, &write_fds)) { ssize_t n = write (p->out, p->buf + p->ofs, p->size); if (n > 0) { p->ofs += n; p->size -= n; if (p->size == 0) p->ofs = 0; } else if (!handle_error (n, &p->out, p->out == sock, "write")) return; } } } } static void sigchld_handler (int signo __attribute__ ((unused))) { /* Nothing to do. */ } int main (int argc __attribute__ ((unused)), char *argv[]) { pid_t pid; struct itimerval zero_itimerval; struct sockaddr_un sun; sigset_t sigchld_set; int sock; if (argc < 3) { fprintf (stderr, "usage: squish-unix SOCKET COMMAND [ARG]...\n" "Squishes both stdin and stdout into a single Unix domain\n" "socket named SOCKET, and runs COMMAND as a subprocess.\n"); return EXIT_FAILURE; } /* Create socket. */ sock = socket (PF_LOCAL, SOCK_STREAM, 0); if (sock < 0) fail_io ("socket"); /* Configure socket. */ sun.sun_family = AF_LOCAL; strncpy (sun.sun_path, argv[1], sizeof sun.sun_path); sun.sun_path[sizeof sun.sun_path - 1] = '\0'; if (unlink (sun.sun_path) < 0 && errno != ENOENT) fail_io ("unlink"); if (bind (sock, (struct sockaddr *) &sun, (offsetof (struct sockaddr_un, sun_path) + strlen (sun.sun_path) + 1)) < 0) fail_io ("bind"); /* Listen on socket. */ if (listen (sock, 1) < 0) fail_io ("listen"); /* Block SIGCHLD and set up a handler for it. */ sigemptyset (&sigchld_set); sigaddset (&sigchld_set, SIGCHLD); if (sigprocmask (SIG_BLOCK, &sigchld_set, NULL) < 0) fail_io ("sigprocmask"); if (signal (SIGCHLD, sigchld_handler) == SIG_ERR) fail_io ("signal"); /* Save the virtual interval timer, which might have been set by the process that ran us. It really should be applied to our child process. */ memset (&zero_itimerval, 0, sizeof zero_itimerval); if (setitimer (ITIMER_VIRTUAL, &zero_itimerval, NULL) < 0) fail_io ("setitimer"); pid = fork (); if (pid < 0) fail_io ("fork"); else if (pid != 0) { /* Running in parent process. */ make_nonblocking (sock, true); for (;;) { fd_set read_fds; sigset_t empty_set; int retval; int conn; /* Wait for connection. */ FD_ZERO (&read_fds); FD_SET (sock, &read_fds); sigemptyset (&empty_set); retval = pselect (sock + 1, &read_fds, NULL, NULL, NULL, &empty_set); if (retval < 0) { if (errno == EINTR) break; fail_io ("select"); } /* Accept connection. */ conn = accept (sock, NULL, NULL); if (conn < 0) fail_io ("accept"); /* Relay connection. */ relay (conn); close (conn); } return 0; } else { /* Running in child process. */ if (close (sock) < 0) fail_io ("close"); execvp (argv[2], argv + 2); fail_io ("exec"); } }
10cm
trunk/10cm/pintos/src/utils/squish-unix.c
C
oos
9,175
#! /usr/bin/perl -w use strict; # Check command line. if (grep ($_ eq '-h' || $_ eq '--help', @ARGV)) { print <<'EOF'; backtrace, for converting raw addresses into symbolic backtraces usage: backtrace [BINARY]... ADDRESS... where BINARY is the binary file or files from which to obtain symbols and ADDRESS is a raw address to convert to a symbol name. If no BINARY is unspecified, the default is the first of kernel.o or build/kernel.o that exists. If multiple binaries are specified, each symbol printed is from the first binary that contains a match. The ADDRESS list should be taken from the "Call stack:" printed by the kernel. Read "Backtraces" in the "Debugging Tools" chapter of the Pintos documentation for more information. EOF exit 0; } die "backtrace: at least one argument required (use --help for help)\n" if @ARGV == 0; # Drop garbage inserted by kernel. @ARGV = grep (!/^(call|stack:?|[-+])$/i, @ARGV); s/\.$// foreach @ARGV; # Find binaries. my (@binaries); while ($ARGV[0] !~ /^0x/) { my ($bin) = shift @ARGV; die "backtrace: $bin: not found (use --help for help)\n" if ! -e $bin; push (@binaries, $bin); } if (!@binaries) { my ($bin); if (-e 'kernel.o') { $bin = 'kernel.o'; } elsif (-e 'build/kernel.o') { $bin = 'build/kernel.o'; } else { die "backtrace: no binary specified and neither \"kernel.o\" nor \"build/kernel.o\" exists (use --help for help)\n"; } push (@binaries, $bin); } # Find addr2line. my ($a2l) = search_path ("i386-elf-addr2line") || search_path ("addr2line"); if (!$a2l) { die "backtrace: neither `i386-elf-addr2line' nor `addr2line' in PATH\n"; } sub search_path { my ($target) = @_; for my $dir (split (':', $ENV{PATH})) { my ($file) = "$dir/$target"; return $file if -e $file; } return undef; } # Figure out backtrace. my (@locs) = map ({ADDR => $_}, @ARGV); for my $bin (@binaries) { open (A2L, "$a2l -fe $bin " . join (' ', map ($_->{ADDR}, @locs)) . "|"); for (my ($i) = 0; <A2L>; $i++) { my ($function, $line); chomp ($function = $_); chomp ($line = <A2L>); next if defined $locs[$i]{BINARY}; if ($function ne '??' || $line ne '??:0') { $locs[$i]{FUNCTION} = $function; $locs[$i]{LINE} = $line; $locs[$i]{BINARY} = $bin; } } close (A2L); } # Print backtrace. my ($cur_binary); for my $loc (@locs) { if (defined ($loc->{BINARY}) && @binaries > 1 && (!defined ($cur_binary) || $loc->{BINARY} ne $cur_binary)) { $cur_binary = $loc->{BINARY}; print "In $cur_binary:\n"; } my ($addr) = $loc->{ADDR}; $addr = sprintf ("0x%08x", hex ($addr)) if $addr =~ /^0x[0-9a-f]+$/i; print $addr, ": "; if (defined ($loc->{BINARY})) { my ($function) = $loc->{FUNCTION}; my ($line) = $loc->{LINE}; $line =~ s/^(\.\.\/)*//; $line = "..." . substr ($line, -25) if length ($line) > 28; print "$function ($line)"; } else { print "(unknown)"; } print "\n"; }
10cm
trunk/10cm/pintos/src/utils/.svn/text-base/backtrace.svn-base
Perl
oos
2,951
#! /usr/bin/perl use strict; use warnings; use POSIX; use Getopt::Long; use Fcntl 'SEEK_SET'; GetOptions ("h|help" => sub { usage (0); }) or exit 1; usage (1) if @ARGV != 2; my ($disk, $mb) = @ARGV; die "$disk: already exists\n" if -e $disk; die "\"$mb\" is not a valid size in megabytes\n" if $mb <= 0 || $mb > 1024 || $mb !~ /^\d+(\.\d+)?|\.\d+/; my ($cyl_cnt) = ceil ($mb * 2); my ($cyl_bytes) = 512 * 16 * 63; my ($bytes) = $cyl_bytes * $cyl_cnt; open (DISK, '>', $disk) or die "$disk: create: $!\n"; sysseek (DISK, $bytes - 1, SEEK_SET) or die "$disk: seek: $!\n"; syswrite (DISK, "\0", 1) == 1 or die "$disk: write: $!\n"; close (DISK) or die "$disk: close: $!\n"; sub usage { print <<'EOF'; pintos-mkdisk, a utility for creating Pintos virtual disks Usage: pintos DISKFILE MB where DISKFILE is the file to use for the disk and MB is the disk size in (approximate) megabytes. Options: -h, --help Display this help message. EOF exit (@_); }
10cm
trunk/10cm/pintos/src/utils/.svn/text-base/pintos-mkdisk.svn-base
Perl
oos
975
#! /bin/sh # Path to GDB macros file. Customize for your site. GDBMACROS=/usr/class/cs140/pintos/pintos/src/misc/gdb-macros # Choose correct GDB. if command -v i386-elf-gdb >/dev/null 2>&1; then GDB=i386-elf-gdb else GDB=gdb fi # Run GDB. if test -f "$GDBMACROS"; then exec $GDB -x "$GDBMACROS" "$@" else echo "*** $GDBMACROS does not exist ***" echo "*** Pintos GDB macros will not be available ***" exec $GDB "$@" fi
10cm
trunk/10cm/pintos/src/utils/.svn/text-base/pintos-gdb.svn-base
Shell
oos
429
#! /usr/bin/perl -w use strict; use POSIX; use Fcntl; use File::Temp 'tempfile'; use Getopt::Long qw(:config bundling); # Command-line options. our ($start_time) = time (); our ($sim); # Simulator: bochs, qemu, or player. our ($debug) = "none"; # Debugger: none, monitor, or gdb. our ($mem) = 4; # Physical RAM in MB. our ($serial) = 1; # Use serial port for input and output? our ($vga); # VGA output: window, terminal, or none. our ($jitter); # Seed for random timer interrupts, if set. our ($realtime); # Synchronize timer interrupts with real time? our ($timeout); # Maximum runtime in seconds, if set. our ($kill_on_failure); # Abort quickly on test failure? our (@puts); # Files to copy into the VM. our (@gets); # Files to copy out of the VM. our ($as_ref); # Reference to last addition to @gets or @puts. our (@kernel_args); # Arguments to pass to kernel. our (%disks) = (OS => {DEF_FN => 'os.dsk'}, # Disks to give VM. FS => {DEF_FN => 'fs.dsk'}, SCRATCH => {DEF_FN => 'scratch.dsk'}, SWAP => {DEF_FN => 'swap.dsk'}); our (@disks_by_iface) = @disks{qw (OS FS SCRATCH SWAP)}; parse_command_line (); find_disks (); prepare_scratch_disk (); prepare_arguments (); run_vm (); finish_scratch_disk (); exit 0; # Parses the command line. sub parse_command_line { usage (0) if @ARGV == 0 || (@ARGV == 1 && $ARGV[0] eq '--help'); @kernel_args = @ARGV; if (grep ($_ eq '--', @kernel_args)) { @ARGV = (); while ((my $arg = shift (@kernel_args)) ne '--') { push (@ARGV, $arg); } GetOptions ("sim=s" => sub { set_sim ($_[1]) }, "bochs" => sub { set_sim ("bochs") }, "qemu" => sub { set_sim ("qemu") }, "player" => sub { set_sim ("player") }, "debug=s" => sub { set_debug ($_[1]) }, "no-debug" => sub { set_debug ("none") }, "monitor" => sub { set_debug ("monitor") }, "gdb" => sub { set_debug ("gdb") }, "m|memory=i" => \$mem, "j|jitter=i" => sub { set_jitter ($_[1]) }, "r|realtime" => sub { set_realtime () }, "T|timeout=i" => \$timeout, "k|kill-on-failure" => \$kill_on_failure, "v|no-vga" => sub { set_vga ('none'); }, "s|no-serial" => sub { $serial = 0; }, "t|terminal" => sub { set_vga ('terminal'); }, "p|put-file=s" => sub { add_file (\@puts, $_[1]); }, "g|get-file=s" => sub { add_file (\@gets, $_[1]); }, "a|as=s" => sub { set_as ($_[1]); }, "h|help" => sub { usage (0); }, "os-disk=s" => \$disks{OS}{FILE_NAME}, "fs-disk=s" => \$disks{FS}{FILE_NAME}, "scratch-disk=s" => \$disks{SCRATCH}{FILE_NAME}, "swap-disk=s" => \$disks{SWAP}{FILE_NAME}, "0|disk-0|hda=s" => \$disks_by_iface[0]{FILE_NAME}, "1|disk-1|hdb=s" => \$disks_by_iface[1]{FILE_NAME}, "2|disk-2|hdc=s" => \$disks_by_iface[2]{FILE_NAME}, "3|disk-3|hdd=s" => \$disks_by_iface[3]{FILE_NAME}) or exit 1; } $sim = "bochs" if !defined $sim; $debug = "none" if !defined $debug; $vga = "window" if !defined $vga; undef $timeout, print "warning: disabling timeout with --$debug\n" if defined ($timeout) && $debug ne 'none'; print "warning: enabling serial port for -k or --kill-on-failure\n" if $kill_on_failure && !$serial; } # usage($exitcode). # Prints a usage message and exits with $exitcode. sub usage { my ($exitcode) = @_; $exitcode = 1 unless defined $exitcode; print <<'EOF'; pintos, a utility for running Pintos in a simulator Usage: pintos [OPTION...] -- [ARGUMENT...] where each OPTION is one of the following options and each ARGUMENT is passed to Pintos kernel verbatim. Simulator selection: --bochs (default) Use Bochs as simulator --qemu Use QEMU as simulator --player Use VMware Player as simulator Debugger selection: --no-debug (default) No debugger --monitor Debug with simulator's monitor --gdb Debug with gdb Display options: (default is both VGA and serial) -v, --no-vga No VGA display or keyboard -s, --no-serial No serial input or output -t, --terminal Display VGA in terminal (Bochs only) Timing options: (Bochs only) -j SEED Randomize timer interrupts -r, --realtime Use realistic, not reproducible, timings Testing options: -T, --timeout=N Kill Pintos after N seconds CPU time or N*load_avg seconds wall-clock time (whichever comes first) -k, --kill-on-failure Kill Pintos a few seconds after a kernel or user panic, test failure, or triple fault Configuration options: -m, --mem=N Give Pintos N MB physical RAM (default: 4) File system commands (for `run' command): -p, --put-file=HOSTFN Copy HOSTFN into VM, by default under same name -g, --get-file=GUESTFN Copy GUESTFN out of VM, by default under same name -a, --as=FILENAME Specifies guest (for -p) or host (for -g) file name Disk options: (name an existing FILE or specify SIZE in MB for a temp disk) --os-disk=FILE Set OS disk file (default: os.dsk) --fs-disk=FILE|SIZE Set FS disk file (default: fs.dsk) --scratch-disk=FILE|SIZE Set scratch disk (default: scratch.dsk) --swap-disk=FILE|SIZE Set swap disk file (default: swap.dsk) Other options: -h, --help Display this help message. EOF exit $exitcode; } # Sets the simulator. sub set_sim { my ($new_sim) = @_; die "--$new_sim conflicts with --$sim\n" if defined ($sim) && $sim ne $new_sim; $sim = $new_sim; } # Sets the debugger. sub set_debug { my ($new_debug) = @_; die "--$new_debug conflicts with --$debug\n" if $debug ne 'none' && $new_debug ne 'none' && $debug ne $new_debug; $debug = $new_debug; } # Sets VGA output destination. sub set_vga { my ($new_vga) = @_; if (defined ($vga) && $vga ne $new_vga) { print "warning: conflicting vga display options\n"; } $vga = $new_vga; } # Sets randomized timer interrupts. sub set_jitter { my ($new_jitter) = @_; die "--realtime conflicts with --jitter\n" if defined $realtime; die "different --jitter already defined\n" if defined $jitter && $jitter != $new_jitter; $jitter = $new_jitter; } # Sets real-time timer interrupts. sub set_realtime { die "--realtime conflicts with --jitter\n" if defined $jitter; $realtime = 1; } # add_file(\@list, $file) # # Adds [$file] to @list, which should be @puts or @gets. # Sets $as_ref to point to the added element. sub add_file { my ($list, $file) = @_; $as_ref = [$file]; push (@$list, $as_ref); } # Sets the guest/host name for the previous put/get. sub set_as { my ($as) = @_; die "-a (or --as) is only allowed after -p or -g\n" if !defined $as_ref; die "Only one -a (or --as) is allowed after -p or -g\n" if defined $as_ref->[1]; $as_ref->[1] = $as; } # Locates the files used to back each of the virtual disks, # and creates temporary disks. sub find_disks { for my $disk (values %disks) { # If there's no assigned file name but the default file exists, # try to assign a default file name. if (!defined ($disk->{FILE_NAME})) { for my $try_fn ($disk->{DEF_FN}, "build/" . $disk->{DEF_FN}) { $disk->{FILE_NAME} = $try_fn, last if -e $try_fn; } } # If there's no file name, we're done. next if !defined ($disk->{FILE_NAME}); if ($disk->{FILE_NAME} =~ /^\d+(\.\d+)?|\.\d+$/) { # Create a temporary disk of approximately the specified # size in megabytes. die "OS disk can't be temporary\n" if $disk == $disks{OS}; my ($mb) = $disk->{FILE_NAME}; undef $disk->{FILE_NAME}; my ($cyl_size) = 512 * 16 * 63; extend_disk ($disk, ceil ($mb * 2) * $cyl_size); } else { # The file must exist and have nonzero size. -e $disk->{FILE_NAME} or die "$disk->{FILE_NAME}: stat: $!\n"; -s _ or die "$disk->{FILE_NAME}: disk has zero size\n"; } } # Warn about (potentially) missing disks. die "Cannot find OS disk\n" if !defined $disks{OS}{FILE_NAME}; if (my ($project) = `pwd` =~ /\b(threads|userprog|vm|filesys)\b/) { if ((grep ($project eq $_, qw (userprog vm filesys))) && !defined ($disks{FS}{FILE_NAME})) { print STDERR "warning: it looks like you're running the $project "; print STDERR "project, but no file system disk is present\n"; } if ($project eq 'vm' && !defined $disks{SWAP}{FILE_NAME}) { print STDERR "warning: it looks like you're running the $project "; print STDERR "project, but no swap disk is present\n"; } } } # Prepare the scratch disk for gets and puts. sub prepare_scratch_disk { if (@puts) { # Write ustar header and data for each file. put_scratch_file ($_->[0], defined $_->[1] ? $_->[1] : $_->[0]) foreach @puts; # Write end-of-archive marker. #print { $disks{SCRATCH}{HANDLE} } "\0" x 1024; write_fully ($disks{SCRATCH}{HANDLE}, $disks{SCRATCH}{FILE_NAME}, "\0" x 1024); } # Make sure the scratch disk is big enough to get big files. extend_disk ($disks{SCRATCH}, @gets * 1024 * 1024) if @gets; } # Read "get" files from the scratch disk. sub finish_scratch_disk { # We need to start reading the scratch disk from the beginning again. if (@gets) { close ($disks{SCRATCH}{HANDLE}); undef ($disks{SCRATCH}{HANDLE}); } # Read each file. # If reading fails, delete that file and all subsequent files. my ($ok) = 1; foreach my $get (@gets) { my ($name) = defined ($get->[1]) ? $get->[1] : $get->[0]; my ($error) = get_scratch_file ($name); if ($error) { print STDERR "getting $name failed ($error)\n"; die "$name: unlink: $!\n" if !unlink ($name) && !$!{ENOENT}; $ok = 0; } } } # mk_ustar_field($number, $size) # # Returns $number in a $size-byte numeric field in the format used by # the standard ustar archive header. sub mk_ustar_field { my ($number, $size) = @_; my ($len) = $size - 1; my ($out) = sprintf ("%0${len}o", $number) . "\0"; die "$number: too large for $size-byte octal ustar field\n" if length ($out) != $size; return $out; } # calc_ustar_chksum($s) # # Calculates and returns the ustar checksum of 512-byte ustar archive # header $s. sub calc_ustar_chksum { my ($s) = @_; die if length ($s) != 512; substr ($s, 148, 8, ' ' x 8); return unpack ("%32a*", $s); } # put_scratch_file($src_file_name, $dst_file_name). # # Copies $src_file_name into the scratch disk for extraction as # $dst_file_name. sub put_scratch_file { my ($src_file_name, $dst_file_name) = @_; my ($disk_handle, $disk_file_name) = open_disk ($disks{SCRATCH}); print "Copying $src_file_name to scratch partition...\n"; # ustar format supports up to 100 characters for a file name, and # even longer names given some common properties, but our code in # the Pintos kernel only supports at most 99 characters. die "$dst_file_name: name too long (max 99 characters)\n" if length ($dst_file_name) > 99; # Compose and write ustar header. stat $src_file_name or die "$src_file_name: stat: $!\n"; my ($size) = -s _; my ($header) = (pack ("a100", $dst_file_name) # name . mk_ustar_field (0644, 8) # mode . mk_ustar_field (0, 8) # uid . mk_ustar_field (0, 8) # gid . mk_ustar_field ($size, 12) # size . mk_ustar_field (1136102400, 12) # mtime . (' ' x 8) # chksum . '0' # typeflag . ("\0" x 100) # linkname . "ustar\0" # magic . "00" # version . "root" . ("\0" x 28) # uname . "root" . ("\0" x 28) # gname . "\0" x 8 # devmajor . "\0" x 8 # devminor . ("\0" x 155)) # prefix . "\0" x 12; # pad to 512 bytes substr ($header, 148, 8) = mk_ustar_field (calc_ustar_chksum ($header), 8); write_fully ($disk_handle, $disk_file_name, $header); # Copy file data. my ($put_handle); sysopen ($put_handle, $src_file_name, O_RDONLY) or die "$src_file_name: open: $!\n"; copy_file ($put_handle, $src_file_name, $disk_handle, $disk_file_name, $size); die "$src_file_name: changed size while being read\n" if $size != -s $put_handle; close ($put_handle); # Round up disk data to beginning of next sector. write_fully ($disk_handle, $disk_file_name, "\0" x (512 - $size % 512)) if $size % 512; } # get_scratch_file($file). # # Copies from the scratch disk to $file. # Returns 1 if successful, 0 on failure. sub get_scratch_file { my ($get_file_name) = @_; my ($disk_handle, $disk_file_name) = open_disk ($disks{SCRATCH}); print "Copying $get_file_name out of $disk_file_name...\n"; # Read ustar header sector. my ($header) = read_fully ($disk_handle, $disk_file_name, 512); return "scratch disk tar archive ends unexpectedly" if $header eq ("\0" x 512); # Verify magic numbers. return "corrupt ustar signature" if substr ($header, 257, 6) ne "ustar\0"; return "invalid ustar version" if substr ($header, 263, 2) ne '00'; # Verify checksum. my ($chksum) = oct (unpack ("Z*", substr ($header, 148, 8))); my ($correct_chksum) = calc_ustar_chksum ($header); return "checksum mismatch" if $chksum != $correct_chksum; # Get type. my ($typeflag) = substr ($header, 156, 1); return "not a regular file" if $typeflag ne '0' && $typeflag ne "\0"; # Get size. my ($size) = oct (unpack ("Z*", substr ($header, 124, 12))); return "bad size $size\n" if $size < 0; # Copy file data. my ($get_handle); sysopen ($get_handle, $get_file_name, O_WRONLY | O_CREAT, 0666) or die "$get_file_name: create: $!\n"; copy_file ($disk_handle, $disk_file_name, $get_handle, $get_file_name, $size); close ($get_handle); # Skip forward in disk up to beginning of next sector. read_fully ($disk_handle, $disk_file_name, 512 - $size % 512) if $size % 512; return 0; } # Prepares the arguments to pass to the Pintos kernel, # and then write them into Pintos bootloader. sub prepare_arguments { my (@args); push (@args, shift (@kernel_args)) while @kernel_args && $kernel_args[0] =~ /^-/; push (@args, 'extract') if @puts; push (@args, @kernel_args); push (@args, 'append', $_->[0]) foreach @gets; write_cmd_line ($disks{OS}, @args); } # Writes @args into the Pintos bootloader at the beginning of $disk. sub write_cmd_line { my ($disk, @args) = @_; # Figure out command line to write. my ($arg_cnt) = pack ("V", scalar (@args)); my ($args) = join ('', map ("$_\0", @args)); die "command line exceeds 128 bytes" if length ($args) > 128; $args .= "\0" x (128 - length ($args)); # Write command line. my ($handle, $file_name) = open_disk_copy ($disk); print "Writing command line to $file_name...\n"; sysseek ($handle, 0x17a, 0) == 0x17a or die "$file_name: seek: $!\n"; syswrite ($handle, "$arg_cnt$args") or die "$file_name: write: $!\n"; } # Running simulators. # Runs the selected simulator. sub run_vm { if ($sim eq 'bochs') { run_bochs (); } elsif ($sim eq 'qemu') { run_qemu (); } elsif ($sim eq 'player') { run_player (); } else { die "unknown simulator `$sim'\n"; } } # Runs Bochs. sub run_bochs { # Select Bochs binary based on the chosen debugger. my ($bin) = $debug eq 'monitor' ? 'bochs-dbg' : 'bochs'; my ($squish_pty); if ($serial) { $squish_pty = find_in_path ("squish-pty"); print "warning: can't find squish-pty, so terminal input will fail\n" if !defined $squish_pty; } # Write bochsrc.txt configuration file. open (BOCHSRC, ">", "bochsrc.txt") or die "bochsrc.txt: create: $!\n"; print BOCHSRC <<EOF; romimage: file=\$BXSHARE/BIOS-bochs-latest vgaromimage: file=\$BXSHARE/VGABIOS-lgpl-latest boot: disk cpu: ips=1000000 megs: $mem log: bochsout.txt panic: action=fatal EOF print BOCHSRC "gdbstub: enabled=1\n" if $debug eq 'gdb'; if ($realtime) { print BOCHSRC "clock: sync=realtime\n"; } else { print BOCHSRC "clock: sync=none, time0=0\n"; } print_bochs_disk_line ("ata0-master", 0); print_bochs_disk_line ("ata0-slave", 1); if (defined ($disks_by_iface[2]{FILE_NAME}) || defined ($disks_by_iface[3]{FILE_NAME})) { print BOCHSRC "ata1: enabled=1, ioaddr1=0x170, ", "ioaddr2=0x370, irq=15\n"; print_bochs_disk_line ("ata1-master", 2); print_bochs_disk_line ("ata1-slave", 3); } if ($vga ne 'terminal') { if ($serial) { my $mode = defined ($squish_pty) ? "term" : "file"; print BOCHSRC "com1: enabled=1, mode=$mode, dev=/dev/stdout\n"; } print BOCHSRC "display_library: nogui\n" if $vga eq 'none'; } else { print BOCHSRC "display_library: term\n"; } close (BOCHSRC); # Compose Bochs command line. my (@cmd) = ($bin, '-q'); unshift (@cmd, $squish_pty) if defined $squish_pty; push (@cmd, '-j', $jitter) if defined $jitter; # Run Bochs. print join (' ', @cmd), "\n"; my ($exit) = xsystem (@cmd); if (WIFEXITED ($exit)) { # Bochs exited normally. # Ignore the exit code; Bochs normally exits with status 1, # which is weird. } elsif (WIFSIGNALED ($exit)) { die "Bochs died with signal ", WTERMSIG ($exit), "\n"; } else { die "Bochs died: code $exit\n"; } } # print_bochs_disk_line($device, $iface) # # If IDE interface $iface has a disk attached, prints a bochsrc.txt # line for attaching it to $device. sub print_bochs_disk_line { my ($device, $iface) = @_; my ($disk) = $disks_by_iface[$iface]; my ($file) = $disk->{FILE_NAME}; if (defined $file) { my (%geom) = disk_geometry ($disk); print BOCHSRC "$device: type=disk, path=$file, mode=flat, "; print BOCHSRC "cylinders=$geom{C}, heads=$geom{H}, spt=$geom{S}, "; print BOCHSRC "translation=none\n"; } } # Runs QEMU. sub run_qemu { print "warning: qemu doesn't support --terminal\n" if $vga eq 'terminal'; print "warning: qemu doesn't support jitter\n" if defined $jitter; my (@cmd) = ('qemu'); for my $iface (0...3) { my ($option) = ('-hda', '-hdb', '-hdc', '-hdd')[$iface]; push (@cmd, $option, $disks_by_iface[$iface]{FILE_NAME}) if defined $disks_by_iface[$iface]{FILE_NAME}; } push (@cmd, '-m', $mem); push (@cmd, '-net', 'none'); push (@cmd, '-nographic') if $vga eq 'none'; push (@cmd, '-serial', 'stdio') if $serial && $vga ne 'none'; push (@cmd, '-S') if $debug eq 'monitor'; push (@cmd, '-s', '-S') if $debug eq 'gdb'; push (@cmd, '-monitor', 'null') if $vga eq 'none' && $debug eq 'none'; run_command (@cmd); } # player_unsup($flag) # # Prints a message that $flag is unsupported by VMware Player. sub player_unsup { my ($flag) = @_; print "warning: no support for $flag with VMware Player\n"; } # Runs VMware Player. sub run_player { player_unsup ("--$debug") if $debug ne 'none'; player_unsup ("--no-vga") if $vga eq 'none'; player_unsup ("--terminal") if $vga eq 'terminal'; player_unsup ("--jitter") if defined $jitter; player_unsup ("--timeout"), undef $timeout if defined $timeout; player_unsup ("--kill-on-failure"), undef $kill_on_failure if defined $kill_on_failure; # Memory size must be multiple of 4. $mem = int (($mem + 3) / 4) * 4; open (VMX, ">", "pintos.vmx") or die "pintos.vmx: create: $!\n"; chmod 0777 & ~umask, "pintos.vmx"; print VMX <<EOF; #! /usr/bin/vmware -G config.version = 8 guestOS = "linux" memsize = $mem floppy0.present = FALSE usb.present = FALSE sound.present = FALSE gui.exitAtPowerOff = TRUE gui.exitOnCLIHLT = TRUE gui.powerOnAtStartUp = TRUE EOF print VMX <<EOF if $serial; serial0.present = TRUE serial0.fileType = "pipe" serial0.fileName = "pintos.socket" serial0.pipe.endPoint = "client" serial0.tryNoRxLoss = "TRUE" EOF for (my ($i) = 0; $i < 4; $i++) { my ($disk) = $disks_by_iface[$i]; my ($dsk) = $disk->{FILE_NAME}; next if !defined $dsk; my ($device) = "ide" . int ($i / 2) . ":" . ($i % 2); my ($pln) = "$device.pln"; print VMX <<EOF; $device.present = TRUE $device.deviceType = "plainDisk" $device.fileName = "$pln" EOF open (URANDOM, '<', '/dev/urandom') or die "/dev/urandom: open: $!\n"; my ($bytes); sysread (URANDOM, $bytes, 4) == 4 or die "/dev/urandom: read: $!\n"; close (URANDOM); my ($cid) = unpack ("L", $bytes); my (%geom) = disk_geometry ($disk); open (PLN, ">", $pln) or die "$pln: create: $!\n"; print PLN <<EOF; version=1 CID=$cid parentCID=ffffffff createType="monolithicFlat" RW $geom{CAPACITY} FLAT "$dsk" 0 # The Disk Data Base #DDB ddb.adapterType = "ide" ddb.virtualHWVersion = "4" ddb.toolsVersion = "2" ddb.geometry.cylinders = "$geom{C}" ddb.geometry.heads = "$geom{H}" ddb.geometry.sectors = "$geom{S}" EOF close (PLN); } close (VMX); my ($squish_unix); if ($serial) { $squish_unix = find_in_path ("squish-unix"); print "warning: can't find squish-unix, so terminal input ", "and output will fail\n" if !defined $squish_unix; } my ($vmx) = getcwd () . "/pintos.vmx"; my (@cmd) = ("vmplayer", $vmx); unshift (@cmd, $squish_unix, "pintos.socket") if $squish_unix; print join (' ', @cmd), "\n"; xsystem (@cmd); } # Disk utilities. # open_disk($disk) # # Opens $disk, if it is not already open, and returns its file handle # and file name. sub open_disk { my ($disk) = @_; if (!defined ($disk->{HANDLE})) { if ($disk->{FILE_NAME}) { sysopen ($disk->{HANDLE}, $disk->{FILE_NAME}, O_RDWR) or die "$disk->{FILE_NAME}: open: $!\n"; } else { ($disk->{HANDLE}, $disk->{FILE_NAME}) = tempfile (UNLINK => 1, SUFFIX => '.dsk'); } } return ($disk->{HANDLE}, $disk->{FILE_NAME}); } # open_disk_copy($disk) # # Makes a temporary copy of $disk and returns its file handle and file name. sub open_disk_copy { my ($disk) = @_; die if !$disk->{FILE_NAME}; my ($orig_handle, $orig_file_name) = open_disk ($disk); my ($cp_handle, $cp_file_name) = tempfile (UNLINK => 1, SUFFIX => '.dsk'); copy_file ($orig_handle, $orig_file_name, $cp_handle, $cp_file_name, -s $orig_handle); return ($disk->{HANDLE}, $disk->{FILE_NAME}) = ($cp_handle, $cp_file_name); } # extend_disk($disk, $size) # # Extends $disk, if necessary, so that it is at least $size bytes # long. sub extend_disk { my ($disk, $size) = @_; my ($handle, $file_name) = open_disk ($disk); if (-s ($handle) < $size) { sysseek ($handle, $size - 1, 0) == $size - 1 or die "$file_name: seek: $!\n"; syswrite ($handle, "\0") == 1 or die "$file_name: write: $!\n"; } } # disk_geometry($file) # # Examines $file and returns a valid IDE disk geometry for it, as a # hash. sub disk_geometry { my ($disk) = @_; my ($file) = $disk->{FILE_NAME}; my ($size) = -s $file; die "$file: stat: $!\n" if !defined $size; die "$file: size not a multiple of 512 bytes\n" if $size % 512; my ($cyl_size) = 512 * 16 * 63; my ($cylinders) = ceil ($size / $cyl_size); extend_disk ($disk, $cylinders * $cyl_size) if $size % $cyl_size; return (CAPACITY => $size / 512, C => $cylinders, H => 16, S => 63); } # copy_file($from_handle, $from_file_name, $to_handle, $to_file_name, $size) # # Copies $size bytes from $from_handle to $to_handle. # $from_file_name and $to_file_name are used in error messages. sub copy_file { my ($from_handle, $from_file_name, $to_handle, $to_file_name, $size) = @_; while ($size > 0) { my ($chunk_size) = 4096; $chunk_size = $size if $chunk_size > $size; $size -= $chunk_size; my ($data) = read_fully ($from_handle, $from_file_name, $chunk_size); write_fully ($to_handle, $to_file_name, $data); } } # read_fully($handle, $file_name, $bytes) # # Reads exactly $bytes bytes from $handle and returns the data read. # $file_name is used in error messages. sub read_fully { my ($handle, $file_name, $bytes) = @_; my ($data); my ($read_bytes) = sysread ($handle, $data, $bytes); die "$file_name: read: $!\n" if !defined $read_bytes; die "$file_name: unexpected end of file\n" if $read_bytes != $bytes; return $data; } # write_fully($handle, $file_name, $data) # # Write $data to $handle. # $file_name is used in error messages. sub write_fully { my ($handle, $file_name, $data) = @_; my ($written_bytes) = syswrite ($handle, $data); die "$file_name: write: $!\n" if !defined $written_bytes; die "$file_name: short write\n" if $written_bytes != length $data; } # Subprocess utilities. # run_command(@args) # # Runs xsystem(@args). # Also prints the command it's running and checks that it succeeded. sub run_command { print join (' ', @_), "\n"; die "command failed\n" if xsystem (@_); } # xsystem(@args) # # Creates a subprocess via exec(@args) and waits for it to complete. # Relays common signals to the subprocess. # If $timeout is set then the subprocess will be killed after that long. sub xsystem { # QEMU turns off local echo and does not restore it if killed by a signal. # We compensate by restoring it ourselves. my $cleanup = sub {}; if (isatty (0)) { my $termios = POSIX::Termios->new; $termios->getattr (0); $cleanup = sub { $termios->setattr (0, &POSIX::TCSANOW); } } # Create pipe for filtering output. pipe (my $in, my $out) or die "pipe: $!\n" if $kill_on_failure; my ($pid) = fork; if (!defined ($pid)) { # Fork failed. die "fork: $!\n"; } elsif (!$pid) { # Running in child process. dup2 (fileno ($out), STDOUT_FILENO) or die "dup2: $!\n" if $kill_on_failure; exec_setitimer (@_); } else { # Running in parent process. close $out if $kill_on_failure; my ($cause); local $SIG{ALRM} = sub { timeout ($pid, $cause, $cleanup); }; local $SIG{INT} = sub { relay_signal ($pid, "INT", $cleanup); }; local $SIG{TERM} = sub { relay_signal ($pid, "TERM", $cleanup); }; alarm ($timeout * get_load_average () + 1) if defined ($timeout); if ($kill_on_failure) { # Filter output. my ($buf) = ""; my ($boots) = 0; local ($|) = 1; for (;;) { if (waitpid ($pid, WNOHANG) != 0) { # Subprocess died. Pass through any remaining data. print $buf while sysread ($in, $buf, 4096) > 0; last; } # Read and print out pipe data. my ($len) = length ($buf); waitpid ($pid, 0), last if sysread ($in, $buf, 4096, $len) <= 0; print substr ($buf, $len); # Remove full lines from $buf and scan them for keywords. while ((my $idx = index ($buf, "\n")) >= 0) { local $_ = substr ($buf, 0, $idx + 1, ''); next if defined ($cause); if (/(Kernel PANIC|User process ABORT)/ ) { $cause = "\L$1\E"; alarm (5); } elsif (/Pintos booting/ && ++$boots > 1) { $cause = "triple fault"; alarm (5); } elsif (/FAILED/) { $cause = "test failure"; alarm (5); } } } } else { waitpid ($pid, 0); } alarm (0); &$cleanup (); if (WIFSIGNALED ($?) && WTERMSIG ($?) == SIGVTALRM ()) { seek (STDOUT, 0, 2); print "\nTIMEOUT after $timeout seconds of host CPU time\n"; exit 0; } return $?; } } # relay_signal($pid, $signal, &$cleanup) # # Relays $signal to $pid and then reinvokes it for us with the default # handler. Also cleans up temporary files and invokes $cleanup. sub relay_signal { my ($pid, $signal, $cleanup) = @_; kill $signal, $pid; eval { File::Temp::cleanup() }; # Not defined in old File::Temp. &$cleanup (); $SIG{$signal} = 'DEFAULT'; kill $signal, getpid (); } # timeout($pid, $cause, &$cleanup) # # Interrupts $pid and dies with a timeout error message, # after invoking $cleanup. sub timeout { my ($pid, $cause, $cleanup) = @_; kill "INT", $pid; waitpid ($pid, 0); &$cleanup (); seek (STDOUT, 0, 2); if (!defined ($cause)) { my ($load_avg) = `uptime` =~ /(load average:.*)$/i; print "\nTIMEOUT after ", time () - $start_time, " seconds of wall-clock time"; print " - $load_avg" if defined $load_avg; print "\n"; } else { print "Simulation terminated due to $cause.\n"; } exit 0; } # Returns the system load average over the last minute. # If the load average is less than 1.0 or cannot be determined, returns 1.0. sub get_load_average { my ($avg) = `uptime` =~ /load average:\s*([^,]+),/; return $avg >= 1.0 ? $avg : 1.0; } # Calls setitimer to set a timeout, then execs what was passed to us. sub exec_setitimer { if (defined $timeout) { if ($ ge 5.8.0) { eval " use Time::HiRes qw(setitimer ITIMER_VIRTUAL); setitimer (ITIMER_VIRTUAL, $timeout, 0); "; } else { { exec ("setitimer-helper", $timeout, @_); }; exit 1 if !$!{ENOENT}; print STDERR "warning: setitimer-helper is not installed, so ", "CPU time limit will not be enforced\n"; } } exec (@_); exit (1); } sub SIGVTALRM { use Config; my $i = 0; foreach my $name (split(' ', $Config{sig_name})) { return $i if $name eq 'VTALRM'; $i++; } return 0; } # find_in_path ($program) # # Searches for $program in $ENV{PATH}. # Returns $program if found, otherwise undef. sub find_in_path { my ($program) = @_; -x "$_/$program" and return $program foreach split (':', $ENV{PATH}); return; }
10cm
trunk/10cm/pintos/src/utils/.svn/text-base/pintos.svn-base
Perl
oos
29,493
#define _GNU_SOURCE 1 #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stropts.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <termios.h> #include <unistd.h> static void fail_io (const char *msg, ...) __attribute__ ((noreturn)) __attribute__ ((format (printf, 1, 2))); /* Prints MSG, formatting as with printf(), plus an error message based on errno, and exits. */ static void fail_io (const char *msg, ...) { va_list args; va_start (args, msg); vfprintf (stderr, msg, args); va_end (args); if (errno != 0) fprintf (stderr, ": %s", strerror (errno)); putc ('\n', stderr); exit (EXIT_FAILURE); } /* If FD is a terminal, configures it for noncanonical input mode with VMIN and VTIME set as indicated. If FD is not a terminal, has no effect. */ static void make_noncanon (int fd, int vmin, int vtime) { if (isatty (fd)) { struct termios termios; if (tcgetattr (fd, &termios) < 0) fail_io ("tcgetattr"); termios.c_lflag &= ~(ICANON | ECHO); termios.c_cc[VMIN] = vmin; termios.c_cc[VTIME] = vtime; if (tcsetattr (fd, TCSANOW, &termios) < 0) fail_io ("tcsetattr"); } } /* Make FD non-blocking if NONBLOCKING is true, or blocking if NONBLOCKING is false. */ static void make_nonblocking (int fd, bool nonblocking) { int flags = fcntl (fd, F_GETFL); if (flags < 0) fail_io ("fcntl"); if (nonblocking) flags |= O_NONBLOCK; else flags &= ~O_NONBLOCK; if (fcntl (fd, F_SETFL, flags) < 0) fail_io ("fcntl"); } /* Handle a read or write on *FD, which is the pty if FD_IS_PTY is true, that returned end-of-file or error indication RETVAL. The system call is named CALL, for use in error messages. Returns true if processing may continue, false if we're all done. */ static bool handle_error (ssize_t retval, int *fd, bool fd_is_pty, const char *call) { if (fd_is_pty) { if (retval < 0) { if (errno == EIO) { /* Slave side of pty has been closed. */ return false; } else fail_io (call); } else return true; } else { if (retval == 0) { close (*fd); *fd = -1; return true; } else fail_io (call); } } /* Copies data from stdin to PTY and from PTY to stdout until no more data can be read or written. */ static void relay (int pty, int dead_child_fd) { struct pipe { int in, out; char buf[BUFSIZ]; size_t size, ofs; bool active; }; struct pipe pipes[2]; /* Make PTY, stdin, and stdout non-blocking. */ make_nonblocking (pty, true); make_nonblocking (STDIN_FILENO, true); make_nonblocking (STDOUT_FILENO, true); /* Configure noncanonical mode on PTY and stdin to avoid waiting for end-of-line. We want to minimize context switching on PTY (for efficiency) and minimize latency on stdin to avoid a laggy user experience. */ make_noncanon (pty, 16, 1); make_noncanon (STDIN_FILENO, 1, 0); memset (pipes, 0, sizeof pipes); pipes[0].in = STDIN_FILENO; pipes[0].out = pty; pipes[1].in = pty; pipes[1].out = STDOUT_FILENO; while (pipes[0].in != -1 || pipes[1].in != -1) { fd_set read_fds, write_fds; int retval; int i; FD_ZERO (&read_fds); FD_ZERO (&write_fds); for (i = 0; i < 2; i++) { struct pipe *p = &pipes[i]; /* Don't do anything with the stdin->pty pipe until we have some data for the pty->stdout pipe. If we get too eager, Bochs will throw away our input. */ if (i == 0 && !pipes[1].active) continue; if (p->in != -1 && p->size + p->ofs < sizeof p->buf) FD_SET (p->in, &read_fds); if (p->out != -1 && p->size > 0) FD_SET (p->out, &write_fds); } FD_SET (dead_child_fd, &read_fds); do { retval = select (FD_SETSIZE, &read_fds, &write_fds, NULL, NULL); } while (retval < 0 && errno == EINTR); if (retval < 0) fail_io ("select"); if (FD_ISSET (dead_child_fd, &read_fds)) { /* Child died. Do final relaying. */ struct pipe *p = &pipes[1]; if (p->out == -1) return; make_nonblocking (STDOUT_FILENO, false); for (;;) { ssize_t n; /* Write buffer. */ while (p->size > 0) { n = write (p->out, p->buf + p->ofs, p->size); if (n < 0) fail_io ("write"); else if (n == 0) fail_io ("zero-length write"); p->ofs += n; p->size -= n; } p->ofs = 0; p->size = n = read (p->in, p->buf, sizeof p->buf); if (n <= 0) return; } } for (i = 0; i < 2; i++) { struct pipe *p = &pipes[i]; if (p->in != -1 && FD_ISSET (p->in, &read_fds)) { ssize_t n = read (p->in, p->buf + p->ofs + p->size, sizeof p->buf - p->ofs - p->size); if (n > 0) { p->active = true; p->size += n; if (p->size == BUFSIZ && p->ofs != 0) { memmove (p->buf, p->buf + p->ofs, p->size); p->ofs = 0; } } else if (!handle_error (n, &p->in, p->in == pty, "read")) return; } if (p->out != -1 && FD_ISSET (p->out, &write_fds)) { ssize_t n = write (p->out, p->buf + p->ofs, p->size); if (n > 0) { p->ofs += n; p->size -= n; if (p->size == 0) p->ofs = 0; } else if (!handle_error (n, &p->out, p->out == pty, "write")) return; } } } } static int dead_child_fd; static void sigchld_handler (int signo __attribute__ ((unused))) { if (write (dead_child_fd, "", 1) < 0) _exit (1); } int main (int argc __attribute__ ((unused)), char *argv[]) { int master, slave; char *name; pid_t pid; struct sigaction sa; int pipe_fds[2]; struct itimerval zero_itimerval, old_itimerval; if (argc < 2) { fprintf (stderr, "usage: squish-pty COMMAND [ARG]...\n" "Squishes both stdin and stdout into a single pseudoterminal,\n" "which is passed as stdout to run the specified COMMAND.\n"); return EXIT_FAILURE; } /* Open master side of pty and get ready to open slave. */ master = open ("/dev/ptmx", O_RDWR | O_NOCTTY); if (master < 0) fail_io ("open \"/dev/ptmx\""); if (grantpt (master) < 0) fail_io ("grantpt"); if (unlockpt (master) < 0) fail_io ("unlockpt"); /* Open slave side of pty. */ name = ptsname (master); if (name == NULL) fail_io ("ptsname"); slave = open (name, O_RDWR); if (slave < 0) fail_io ("open \"%s\"", name); /* System V implementations need STREAMS configuration for the slave. */ if (isastream (slave)) { if (ioctl (slave, I_PUSH, "ptem") < 0 || ioctl (slave, I_PUSH, "ldterm") < 0) fail_io ("ioctl"); } /* Arrange to get notified when a child dies, by writing a byte to a pipe fd. We really want to use pselect() and sigprocmask(), but Solaris 2.7 doesn't have it. */ if (pipe (pipe_fds) < 0) fail_io ("pipe"); dead_child_fd = pipe_fds[1]; memset (&sa, 0, sizeof sa); sa.sa_handler = sigchld_handler; sigemptyset (&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction (SIGCHLD, &sa, NULL) < 0) fail_io ("sigaction"); /* Save the virtual interval timer, which might have been set by the process that ran us. It really should be applied to our child process. */ memset (&zero_itimerval, 0, sizeof zero_itimerval); if (setitimer (ITIMER_VIRTUAL, &zero_itimerval, &old_itimerval) < 0) fail_io ("setitimer"); pid = fork (); if (pid < 0) fail_io ("fork"); else if (pid != 0) { /* Running in parent process. */ int status; close (slave); relay (master, pipe_fds[0]); /* If the subprocess has died, die in the same fashion. In particular, dying from SIGVTALRM tells the pintos script that we ran out of CPU time. */ if (waitpid (pid, &status, WNOHANG) > 0) { if (WIFEXITED (status)) return WEXITSTATUS (status); else if (WIFSIGNALED (status)) raise (WTERMSIG (status)); } return 0; } else { /* Running in child process. */ if (setitimer (ITIMER_VIRTUAL, &old_itimerval, NULL) < 0) fail_io ("setitimer"); if (dup2 (slave, STDOUT_FILENO) < 0) fail_io ("dup2"); if (close (pipe_fds[0]) < 0 || close (pipe_fds[1]) < 0 || close (slave) < 0 || close (master) < 0) fail_io ("close"); execvp (argv[1], argv + 1); fail_io ("exec"); } }
10cm
trunk/10cm/pintos/src/utils/squish-pty.c
C
oos
9,614
#include <errno.h> #include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <unistd.h> int main (int argc, char *argv[]) { const char *program_name = argv[0]; double timeout; if (argc < 3) { fprintf (stderr, "setitimer-helper: runs a program with a virtual CPU limit\n" "usage: %s TIMEOUT PROGRAM [ARG...]\n" " where TIMEOUT is the virtual CPU limit, in seconds,\n" " and remaining arguments specify the program to run\n" " and its argument.\n", program_name); return EXIT_FAILURE; } timeout = strtod (argv[1], NULL); if (timeout >= 0.0 && timeout < LONG_MAX) { struct itimerval it; it.it_interval.tv_sec = 0; it.it_interval.tv_usec = 0; it.it_value.tv_sec = timeout; it.it_value.tv_usec = (timeout - floor (timeout)) * 1000000; if (setitimer (ITIMER_VIRTUAL, &it, NULL) < 0) fprintf (stderr, "%s: setitimer: %s\n", program_name, strerror (errno)); } else fprintf (stderr, "%s: invalid timeout value \"%s\"\n", program_name, argv[1]); execvp (argv[2], &argv[2]); fprintf (stderr, "%s: couldn't exec \"%s\": %s\n", program_name, argv[2], strerror (errno)); return EXIT_FAILURE; }
10cm
trunk/10cm/pintos/src/utils/setitimer-helper.c
C
oos
1,390
#! /bin/sh # Path to GDB macros file. Customize for your site. GDBMACROS=/usr/class/cs140/pintos/pintos/src/misc/gdb-macros # Choose correct GDB. if command -v i386-elf-gdb >/dev/null 2>&1; then GDB=i386-elf-gdb else GDB=gdb fi # Run GDB. if test -f "$GDBMACROS"; then exec $GDB -x "$GDBMACROS" "$@" else echo "*** $GDBMACROS does not exist ***" echo "*** Pintos GDB macros will not be available ***" exec $GDB "$@" fi
10cm
trunk/10cm/pintos/src/utils/pintos-gdb
Shell
oos
429
all: setitimer-helper squish-pty squish-unix CC = gcc CFLAGS = -Wall -W LDFLAGS = -lm setitimer-helper: setitimer-helper.o squish-pty: squish-pty.o squish-unix: squish-unix.o clean: rm -f *.o setitimer-helper squish-pty squish-unix
10cm
trunk/10cm/pintos/src/utils/Makefile
Makefile
oos
236
# -*- makefile -*- all: include Make.vars DIRS = $(sort $(addprefix build/,$(KERNEL_SUBDIRS) $(TEST_SUBDIRS) lib/user)) all grade check: $(DIRS) build/Makefile cd build && $(MAKE) $@ $(DIRS): mkdir -p $@ build/Makefile: ../Makefile.build cp $< $@ build/%: $(DIRS) build/Makefile cd build && $(MAKE) $* clean: rm -rf build
10cm
trunk/10cm/pintos/src/Makefile.kernel
Makefile
oos
333
# -*- makefile -*- SRCDIR = ../.. all: os.dsk include ../../Make.config include ../Make.vars include ../../tests/Make.tests # Compiler and assembler options. os.dsk: CPPFLAGS += -I$(SRCDIR)/lib/kernel # Core kernel. threads_SRC = threads/init.c # Main program. threads_SRC += threads/thread.c # Thread management core. threads_SRC += threads/switch.S # Thread switch routine. threads_SRC += threads/interrupt.c # Interrupt core. threads_SRC += threads/intr-stubs.S # Interrupt stubs. threads_SRC += threads/synch.c # Synchronization. threads_SRC += threads/palloc.c # Page allocator. threads_SRC += threads/malloc.c # Subpage allocator. threads_SRC += threads/start.S # Startup code. # Device driver code. devices_SRC = devices/timer.c # Timer device. devices_SRC += devices/kbd.c # Keyboard device. devices_SRC += devices/vga.c # Video device. devices_SRC += devices/serial.c # Serial port device. devices_SRC += devices/disk.c # IDE disk device. devices_SRC += devices/input.c # Serial and keyboard input. devices_SRC += devices/intq.c # Interrupt queue. devices_SRC += devices/rtc.c # Real-time clock. # Library code shared between kernel and user programs. lib_SRC = lib/debug.c # Debug helpers. lib_SRC += lib/random.c # Pseudo-random numbers. lib_SRC += lib/stdio.c # I/O library. lib_SRC += lib/stdlib.c # Utility functions. lib_SRC += lib/string.c # String functions. lib_SRC += lib/arithmetic.c # 64-bit arithmetic for GCC. lib_SRC += lib/ustar.c # Unix standard tar format utilities. # Kernel-specific library code. lib/kernel_SRC = lib/kernel/debug.c # Debug helpers. lib/kernel_SRC += lib/kernel/list.c # Doubly-linked lists. lib/kernel_SRC += lib/kernel/bitmap.c # Bitmaps. lib/kernel_SRC += lib/kernel/hash.c # Hash tables. lib/kernel_SRC += lib/kernel/console.c # printf(), putchar(). # User process code. userprog_SRC = userprog/process.c # Process loading. userprog_SRC += userprog/pagedir.c # Page directories. userprog_SRC += userprog/exception.c # User exception handler. userprog_SRC += userprog/syscall.c # System call handler. userprog_SRC += userprog/gdt.c # GDT initialization. userprog_SRC += userprog/tss.c # TSS management. # No virtual memory code yet. vm_SRC = vm/frame.c # Some file. vm_SRC += vm/swap.c # Some file. # Filesystem code. filesys_SRC = filesys/filesys.c # Filesystem core. filesys_SRC += filesys/free-map.c # Free sector bitmap. filesys_SRC += filesys/file.c # Files. filesys_SRC += filesys/directory.c # Directories. filesys_SRC += filesys/inode.c # File headers. filesys_SRC += filesys/fsutil.c # Utilities. filesys_SRC += filesys/cache.c # Buffer Cache SOURCES = $(foreach dir,$(KERNEL_SUBDIRS),$($(dir)_SRC)) OBJECTS = $(patsubst %.c,%.o,$(patsubst %.S,%.o,$(SOURCES))) DEPENDS = $(patsubst %.o,%.d,$(OBJECTS)) threads/kernel.lds.s: CPPFLAGS += -P threads/kernel.lds.s: threads/kernel.lds.S threads/loader.h kernel.o: threads/kernel.lds.s $(OBJECTS) $(LD) -T $< -o $@ $(OBJECTS) kernel.bin: kernel.o $(OBJCOPY) -O binary -R .note -R .comment -S $< $@.tmp dd if=$@.tmp of=$@ bs=4096 conv=sync rm $@.tmp threads/loader.o: threads/loader.S kernel.bin $(CC) -c $< -o $@ $(ASFLAGS) $(CPPFLAGS) $(DEFINES) -DKERNEL_LOAD_PAGES=`perl -e 'print +(-s "kernel.bin") / 4096;'` loader.bin: threads/loader.o $(LD) -N -e start -Ttext 0x7c00 --oformat binary -o $@ $< os.dsk: loader.bin kernel.bin cat $^ > $@ clean:: rm -f $(OBJECTS) $(DEPENDS) rm -f threads/loader.o threads/kernel.lds.s threads/loader.d rm -f kernel.o kernel.lds.s rm -f kernel.bin loader.bin os.dsk rm -f bochsout.txt bochsrc.txt rm -f results grade Makefile: $(SRCDIR)/Makefile.build cp $< $@ -include $(DEPENDS)
10cm
trunk/10cm/pintos/src/Makefile.build
Makefile
oos
3,699
# -*- makefile -*- $(PROGS): CPPFLAGS += -I$(SRCDIR)/lib/user -I. # Linker flags. $(PROGS): LDFLAGS += -nostdlib -static -Wl,-T,$(LDSCRIPT) $(PROGS): LDSCRIPT = $(SRCDIR)/lib/user/user.lds # Library code shared between kernel and user programs. lib_SRC = lib/debug.c # Debug code. lib_SRC += lib/random.c # Pseudo-random numbers. lib_SRC += lib/stdio.c # I/O library. lib_SRC += lib/stdlib.c # Utility functions. lib_SRC += lib/string.c # String functions. lib_SRC += lib/arithmetic.c # 64-bit arithmetic for GCC. lib_SRC += lib/ustar.c # Unix standard tar format utilities. # User level only library code. lib/user_SRC = lib/user/debug.c # Debug helpers. lib/user_SRC += lib/user/syscall.c # System calls. lib/user_SRC += lib/user/console.c # Console code. LIB_OBJ = $(patsubst %.c,%.o,$(patsubst %.S,%.o,$(lib_SRC) $(lib/user_SRC))) LIB_DEP = $(patsubst %.o,%.d,$(LIB_OBJ)) LIB = lib/user/entry.o libc.a PROGS_SRC = $(foreach prog,$(PROGS),$($(prog)_SRC)) PROGS_OBJ = $(patsubst %.c,%.o,$(patsubst %.S,%.o,$(PROGS_SRC))) PROGS_DEP = $(patsubst %.o,%.d,$(PROGS_OBJ)) all: $(PROGS) define TEMPLATE $(1)_OBJ = $(patsubst %.c,%.o,$(patsubst %.S,%.o,$($(1)_SRC))) $(1): $$($(1)_OBJ) $$(LIB) $$(LDSCRIPT) $$(CC) $$(LDFLAGS) $$($(1)_OBJ) $$(LIB) -o $$@ endef $(foreach prog,$(PROGS),$(eval $(call TEMPLATE,$(prog)))) libc.a: $(LIB_OBJ) rm -f $@ ar r $@ $^ ranlib $@ clean:: rm -f $(PROGS) $(PROGS_OBJ) $(PROGS_DEP) rm -f $(LIB_DEP) $(LIB_OBJ) lib/user/entry.[do] libc.a .PHONY: all clean -include $(LIB_DEP) $(PROGS_DEP)
10cm
trunk/10cm/pintos/src/Makefile.userprog
Makefile
oos
1,551
/* cat.c Compares two files. */ #include <stdio.h> #include <syscall.h> int main (int argc, char *argv[]) { int fd[2]; if (argc != 3) { printf ("usage: cmp A B\n"); return EXIT_FAILURE; } /* Open files. */ fd[0] = open (argv[1]); if (fd[0] < 0) { printf ("%s: open failed\n", argv[1]); return EXIT_FAILURE; } fd[1] = open (argv[2]); if (fd[1] < 0) { printf ("%s: open failed\n", argv[1]); return EXIT_FAILURE; } /* Compare data. */ for (;;) { int pos; char buffer[2][1024]; int bytes_read[2]; int min_read; int i; pos = tell (fd[0]); bytes_read[0] = read (fd[0], buffer[0], sizeof buffer[0]); bytes_read[1] = read (fd[1], buffer[1], sizeof buffer[1]); min_read = bytes_read[0] < bytes_read[1] ? bytes_read[0] : bytes_read[1]; if (min_read == 0) break; for (i = 0; i < min_read; i++) if (buffer[0][i] != buffer[1][i]) { printf ("Byte %d is %02hhx ('%c') in %s but %02hhx ('%c') in %s\n", pos + i, buffer[0][i], buffer[0][i], argv[1], buffer[1][i], buffer[1][i], argv[2]); return EXIT_FAILURE; } if (min_read < bytes_read[1]) printf ("%s is shorter than %s\n", argv[1], argv[2]); else if (min_read < bytes_read[0]) printf ("%s is shorter than %s\n", argv[2], argv[1]); } printf ("%s and %s are identical\n", argv[1], argv[2]); return EXIT_SUCCESS; }
10cm
trunk/10cm/pintos/src/examples/cmp.c
C
oos
1,572