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
package org.vaadin.appfoundation.example.i18n; import org.vaadin.appfoundation.example.Page; public class I18nIntro extends Page { private static final long serialVersionUID = -8458896728089293287L; public I18nIntro() { super("i18n intro text"); } }
007lee-test
src/org/vaadin/appfoundation/example/i18n/I18nIntro.java
Java
asf20
274
package org.vaadin.appfoundation.example.i18n.data; import org.vaadin.appfoundation.i18n.FieldTranslation; public class Customer { @FieldTranslation(tuid = "name") private String name; @FieldTranslation(tuid = "email") private String email; @FieldTranslation(tuid = "phone") private String phone; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setPhone(String phone) { this.phone = phone; } public String getPhone() { return phone; } }
007lee-test
src/org/vaadin/appfoundation/example/i18n/data/Customer.java
Java
asf20
730
package org.vaadin.appfoundation.example.i18n; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; public class UpdatingTranslationsFile extends Page { private static final long serialVersionUID = -4620887553412342431L; public UpdatingTranslationsFile() { super("updating translations file text"); addCodeExample(Examples.I18N_ORIGINAL_XML, "update trans file code 1 caption"); addWikiText("updating translations file text2"); addCodeExample(Examples.I18N_FILE_UPDATER, "update trans file code 2 caption"); addWikiText("updating translations file text3"); addCodeExample(Examples.I18N_UPDATED_XML, "update trans file code 3 caption"); addWikiText("updating translations file text4"); addCodeExample(Examples.I18N_LOAD_TRANSLATIONS, "update trans file code 4 caption"); } }
007lee-test
src/org/vaadin/appfoundation/example/i18n/UpdatingTranslationsFile.java
Java
asf20
975
package org.vaadin.appfoundation.example.i18n; import org.vaadin.appfoundation.example.Page; public class TranslationsFile extends Page { private static final long serialVersionUID = 7919159338285917176L; public TranslationsFile() { super("translations file text"); } }
007lee-test
src/org/vaadin/appfoundation/example/i18n/TranslationsFile.java
Java
asf20
295
package org.vaadin.appfoundation.example.i18n; import java.util.Locale; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.example.i18n.data.Customer; import org.vaadin.appfoundation.i18n.I18nForm; import org.vaadin.appfoundation.i18n.Lang; import com.vaadin.data.Item; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.util.BeanItem; import com.vaadin.ui.Panel; import com.vaadin.ui.Select; public class FieldTranslations extends Page { private static final long serialVersionUID = 2329869742045540584L; public FieldTranslations() { super("field translations text"); addCodeExample(Examples.I18N_CUSTOMER_POJO, "customer pojo"); addCodeExample(Examples.I18N_CUSTOMER_POJO_TRANSLATIONS, "customer pojo translations"); addWikiText("field translations text2"); addForm(); addCodeExample(Examples.I18N_FORM, "show code"); } private void addForm() { Panel panel = new Panel(); final Customer customer = new Customer(); customer.setName("John Doe"); customer.setPhone("+123 456 7890"); customer.setEmail("john@some.site"); final I18nForm form = new I18nForm(Customer.class); Select select = new Select(); select.addContainerProperty("name", String.class, null); select.setItemCaptionPropertyId("name"); Item item = select.addItem("en"); item.getItemProperty("name").setValue(Lang.getMessage("en language")); item = select.addItem("de"); item.getItemProperty("name").setValue(Lang.getMessage("de language")); select.setImmediate(true); select.addListener(new ValueChangeListener() { private static final long serialVersionUID = -1667702475800410396L; @Override public void valueChange(ValueChangeEvent event) { Object value = event.getProperty().getValue(); Lang.setLocale(value.equals("en") ? Locale.ENGLISH : Locale.GERMAN); BeanItem<Customer> customerItem = new BeanItem<Customer>( customer); form.setItemDataSource(customerItem); Lang.setLocale(Locale.ENGLISH); } }); select.select("en"); panel.addComponent(select); panel.addComponent(form); getContent().addComponent(panel); } }
007lee-test
src/org/vaadin/appfoundation/example/i18n/FieldTranslations.java
Java
asf20
2,580
package org.vaadin.appfoundation.example.i18n; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; public class GettingMessages extends Page { private static final long serialVersionUID = 987190244067153965L; public GettingMessages() { super("getting messages text"); addCodeExample(Examples.I18N_EXAMPLE_XML, "example translation xml"); addWikiText("getting messages text2"); addCodeExample(Examples.I18N_GET_MSG_TEXT_FIELD, "show code"); addWikiText("getting messages text3"); addCodeExample(Examples.I18N_GET_MSG_WITH_PARAM, "show code"); addWikiText("getting messages text4"); addCodeExample(Examples.I18N_GET_MSG_VIA_LANG, "show code"); } }
007lee-test
src/org/vaadin/appfoundation/example/i18n/GettingMessages.java
Java
asf20
784
package org.vaadin.appfoundation.example; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.example.components.CodeExample; import org.vaadin.appfoundation.i18n.Lang; import org.vaadin.appfoundation.view.AbstractView; import ys.wikiparser.WikiParser; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; public abstract class Page extends AbstractView<VerticalLayout> { private static final long serialVersionUID = 7964249978981814597L; public Page(String tuid) { super(new VerticalLayout()); addWikiText(tuid); } protected void addCodeExample(Examples example, String captionTuid) { CodeExample codeExample = new CodeExample(example); codeExample.setWidth("100%"); if (captionTuid != null) { codeExample.setDefaultCaption(Lang.getMessage(captionTuid)); } getContent().addComponent(codeExample); } protected void addWikiText(String tuid) { getContent().addComponent( new Label(WikiParser.renderXHTML(Lang.getMessage(tuid)), Label.CONTENT_XHTML)); } @Override public void activated(Object... params) { // TODO Auto-generated method stub } @Override public void deactivated(Object... params) { // TODO Auto-generated method stub } }
007lee-test
src/org/vaadin/appfoundation/example/Page.java
Java
asf20
1,387
package MODELO; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JEditorPane; public class ModeloCategoria extends Conexion{ private String codigo; private String descripcion; private String status; public ModeloCategoria() { super(); } public boolean registar(){ getConexion(); boolean sw= false; String tira="INSERT INTO Categoria (codigo, descripcion, status) VALUES(?,?,?)"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); stam.setString(2, getDescripcion().toUpperCase()); stam.setString(3, getStatus()); ejecutarPrepare(stam); sw= true; } catch (SQLException ex) { Logger.getLogger(ModeloCategoria.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public boolean consultar(){ getConexion(); boolean sw= false; String tira="SELECT * FROM Categoria WHERE codigo=? AND status='A'"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); ResultSet rs= consultarPrepare(stam); if (rs.next()){ sw = true; setDescripcion(rs.getString("descripcion")); setCodigo(rs.getString("codigo")); setStatus(rs.getString("status")); } } catch (SQLException ex) { Logger.getLogger(ModeloCategoria.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public boolean actualizar(){ getConexion(); boolean sw = false; String tira="UPDATE Categoria SET descripcion =? WHERE codigo=? AND status = 'A'"; try{ PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1,getDescripcion()); stam.setString(2, getCodigo()); ejecutarPrepare(stam); sw = true; } catch (SQLException ex) { Logger.getLogger(ModeloCategoria.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public Vector<ModeloCategoria> listar(){ Vector<ModeloCategoria> v = new Vector<ModeloCategoria>(); String tira="SELECT * FROM Categoria WHERE status='A'"; getConexion(); try { ResultSet rs = getConexion().createStatement().executeQuery(tira); while (rs.next()){ ModeloCategoria i = new ModeloCategoria(); i.setDescripcion(rs.getString("descripcion")); i.setCodigo(rs.getString("codigo")); i.setStatus(rs.getString("status")); v.add(i); } } catch (SQLException ex) { Logger.getLogger(ModeloCategoria.class.getName()).log(Level.SEVERE, null, ex); } return v; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
03-09-cuartaentrega
javaBurguer/src/MODELO/ModeloCategoria.java
Java
asf20
3,484
package MODELO; import java.lang.String; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; public class ModeloProducto extends Conexion{ private String codigo; private String cod_categoria; private String descripcion; private String status; private double precio; public ModeloProducto(){ super(); } public boolean registar(){ getConexion(); boolean sw = false; String tira="INSERT INTO Producto (codigo, Cod_Categoria, descripcion, precio, status ) VALUES(?,?,?,?,?)"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); stam.setString(2, getCod_categoria()); stam.setString(3, getDescripcion().toLowerCase()); stam.setDouble(4, getPrecio()); stam.setString(5, getStatus()); ejecutarPrepare(stam); sw = true; } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public void registarIngredientes(Vector<String> codigos,Vector<Double> cantidades){ getConexion(); for (int i = 0; i < cantidades.size(); i++){ String sql="INSERT INTO IngredienteXProducto (cod_ing, cod_pro, cantidad, status) VALUES(?,?,?,'A')"; try { PreparedStatement stam = generarPreparedStatement(sql); stam.setString(1, codigos.elementAt(i)); stam.setString(2,getCodigo()); stam.setDouble(3, cantidades.elementAt(i)); ejecutarPrepare(stam); } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } } } public Vector<ModeloProducto> listar(){ Vector<ModeloProducto> v = new Vector<ModeloProducto>(); String tira="SELECT * FROM Producto WHERE status='A'"; getConexion(); try { ResultSet rs = consultar(tira); while (rs.next()){ ModeloProducto i = new ModeloProducto(); i.setDescripcion(rs.getString("descripcion")); i.setCodigo(rs.getString("codigo")); i.setPrecio(rs.getFloat("precio")); i.setStatus(rs.getString("status")); i.setCod_categoria(rs.getString("cod_categoria")); v.add(i); } } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return v; } public Vector<String []> ingredientesMasUsados(boolean orden){ Vector<String []> v = new Vector<String []>(); String tira="SELECT cantidades , descripcion , codigo FROM Ingrediente,(SELECT SUM(cantidad) AS cantidades,cod_ing AS cod_TablaAux FROM IngredientexProducto GROUP BY cod_ing) TablaAux WHERE Ingrediente.codigo=TablaAux.cod_TablaAux ORDER BY cantidades "; if(orden) tira+= "asc"; else tira+= "desc"; getConexion(); try { ResultSet rs = consultar(tira); while (rs.next()){ String [] s = {rs.getString(2), ""+rs.getDouble(1)}; v.add(s); } } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return v; } public Vector<String []> listarVentas(boolean orden){ Vector<String []> v = new Vector<String []>(); String tira="SELECT descripcion, (precio*TablaAux.cantidades), TablaAux.cantidades, codigo FROM Producto, (SELECT sum(ProductoXOrden.cantidad) as cantidades, ProductoXOrden.cod_pro AS cod_TablaAux FROM ProductoXOrden GROUP BY ProductoXOrden.cod_pro) TablaAux WHERE TablaAux.cod_TablaAux=codigo AND status='A' ORDER BY(TablaAux.cantidades,(precio*TablaAux.cantidades)) "; if(orden) tira+= "asc"; else tira+= "desc"; getConexion(); try{ ResultSet rs= consultar(tira); while (rs.next()){ String [] s = new String [] {rs.getString(1), ""+rs.getDouble(2), ""+rs.getDouble(3), rs.getString(4)}; v.add(s); } } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return v; } public boolean revisarStockIngredientes(int cantidad){ Vector<ModeloIngrediente> v = new Vector<ModeloIngrediente>(); Vector<Double> d = new Vector<Double>(); String tira="SELECT Ingrediente.codigo,IngredientexProducto.cantidad FROM Ingrediente,IngredientexProducto,Producto WHERE Ingrediente.status='A' AND Producto.status='A' AND Ingrediente.codigo=IngredientexProducto.cod_ing AND Producto.codigo=IngredientexProducto.cod_pro AND Producto.codigo=?"; getConexion(); try{ PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); ResultSet rs =consultarPrepare(stam); while(rs.next()){ ModeloIngrediente i = new ModeloIngrediente(); i.setCodigo(rs.getString(1)); d.add(rs.getDouble(2)); v.add(i); } } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } for (int i = 0; i < v.size(); i++) if(!(v.elementAt(i).revisarStock(d.elementAt(i)*cantidad))){ return false; } return true; } public void actualizarStockIngredientes(){ Vector<ModeloIngrediente> v = new Vector<ModeloIngrediente>(); Vector<Double> d = new Vector<Double>(); String tira="SELECT Ingrediente.codigo,IngredientexProducto.cantidad FROM Ingrediente,IngredientexProducto,Producto WHERE Ingrediente.status='A' AND Producto.status='A' AND Ingrediente.codigo=IngredientexProducto.cod_ing AND Producto.codigo=IngredientexProducto.cod_pro AND Producto.codigo=?"; getConexion(); try{ PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); ResultSet rs =consultarPrepare(stam); while(rs.next()){ ModeloIngrediente i = new ModeloIngrediente(); i.setCodigo(rs.getString(1)); d.add(rs.getDouble(2)); v.add(i); } } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } for (int i = 0; i < v.size(); i++){ v.elementAt(i).consultar(); v.elementAt(i).setStock(v.elementAt(i).getStock()-d.elementAt(i)); v.elementAt(i).restarStock(); } } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getCod_categoria() { return cod_categoria; } public void setCod_categoria(String cod_categoria) { this.cod_categoria = cod_categoria; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public double getPrecio() { return precio; } public void setPrecio(double precio) { this.precio = precio; } }
03-09-cuartaentrega
javaBurguer/src/MODELO/ModeloProducto.java
Java
asf20
7,448
package MODELO; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import MODELO.ModeloIngrediente; public class ModeloIngrediente extends Conexion { private String codigo; private String descripcion; private String status; private double stock; public ModeloIngrediente() { super(); } public boolean registar(){ getConexion(); boolean sw = false; String tira="INSERT INTO Ingrediente (codigo, descripcion, stock, status) VALUES(?,?,?,?)"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); stam.setString(2, getDescripcion().toUpperCase()); stam.setDouble(3, getStock()); stam.setString(4, getStatus()); ejecutarPrepare(stam); sw= true; } catch (SQLException ex) { Logger.getLogger(ModeloCategoria.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public boolean actualizar(){ getConexion(); boolean sw = false; String tira="UPDATE Ingrediente SET stock =? WHERE codigo=? AND status = 'A'"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(2, getCodigo()); stam.setDouble(1, getStock()); ejecutarPrepare(stam); sw= true; } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public boolean consultar(){ getConexion(); boolean sw = false; String tira="SELECT * FROM Ingrediente WHERE codigo=? AND status='A'"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); ResultSet rs= consultarPrepare(stam); if (rs.next()){ sw = true; setDescripcion(rs.getString("descripcion")); setCodigo(rs.getString("codigo")); setStatus(rs.getString("status")); setStock(rs.getFloat("stock")); } } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public Vector<ModeloIngrediente> listar(){ Vector<ModeloIngrediente> v = new Vector<ModeloIngrediente>(); String tira="SELECT * FROM Ingrediente WHERE status='A'"; getConexion(); try { ResultSet rs= consultar(tira); while (rs.next()){ ModeloIngrediente i = new ModeloIngrediente(); i.setDescripcion(rs.getString("descripcion")); i.setCodigo(rs.getString("codigo")); i.setStatus(rs.getString("status")); i.setStock(rs.getFloat("stock")); v.add(i); } } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } return v; } public boolean revisarStock(double porcion){ consultar(); if((getStock()-porcion)>=0) return true; else return false; } public void restarStock(){ getConexion(); String tira="UPDATE Ingrediente SET stock =? WHERE codigo=? AND status = 'A'"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(2, getCodigo()); stam.setDouble(1, getStock()); ejecutarPrepare(stam); } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public double getStock() { return stock; } public void setStock(double stock) { this.stock = stock; } }
03-09-cuartaentrega
javaBurguer/src/MODELO/ModeloIngrediente.java
Java
asf20
4,347
package MODELO; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; public class ModeloOrden extends Conexion{ private String codigo, cedula, nombre, status; private double total; public ModeloOrden() { super(); } public boolean registar(){ boolean sw = false; getConexion(); String tira="INSERT INTO Orden (codigo, cedula, nombre, total ,status ) VALUES(?,?,?,?,?)"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); stam.setString(2, getCedula()); stam.setString(3, getNombre()); stam.setDouble(4, getTotal()); stam.setString(5, getStatus()); ejecutarPrepare(stam); sw = true; } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public void registarProductos(Vector<String> codigos,Vector<Double> cantidades){ getConexion(); for (int i = 0; i < codigos.size(); i++) { String tira="INSERT INTO ProductoxOrden (cod_ord, cod_pro, cantidad ) VALUES(?,?,?)"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); stam.setString(2,codigos.elementAt(i)); stam.setDouble(3, cantidades.elementAt(i)); ejecutarPrepare(stam); } catch (SQLException ex) { Logger.getLogger(ModeloOrden.class.getName()).log(Level.SEVERE, null, ex); } } } public Vector<String []> listarProductos(){ Vector<String []> v = new Vector<String []>(); getConexion(); String sql="SELECT Producto.descripcion , ProductoXOrden.cantidad FROM Producto,ProductoXOrden,Orden WHERE Orden.status='A' AND Producto.status='A' AND Producto.codigo=ProductoXOrden.cod_pro AND Orden.codigo=ProductoXOrden.cod_ord AND Orden.codigo=?"; try { PreparedStatement stam = generarPreparedStatement(sql); stam.setString(1, getCodigo()); ResultSet rs= consultarPrepare(stam); while (rs.next()){ String [] s = new String [] {rs.getString(1), ""+rs.getDouble(2)}; v.add(s); } } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return v; } public int contarOrdenes(){ getConexion(); String sql="SELECT COUNT(*) from Orden WHERE status='A'"; try { ResultSet rs = consultar(sql); while (rs.next()){ return rs.getInt(1)+1; } } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return 0; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getCedula() { return cedula; } public void setCedula(String cedula) { this.cedula = cedula; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } }
03-09-cuartaentrega
javaBurguer/src/MODELO/ModeloOrden.java
Java
asf20
3,747
package MODELO; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import MODELO.Conexion; public class Conexion { // La descripcion del driver de la BD private static String driver = "org.postgresql.Driver"; // La direccion URL de la BD private static String url = "jdbc:postgresql://localhost:5432/"; // El nombre de la BD private static String bd = "BD3-9"; // EL login del usuario para conectarse al servidor de BD private static String usuario = "SISTEMAS"; // EL password del usuario para conectarse al servidor de BD private static String password = "654321"; private static Connection conexion; /** * Metodo utilizado para Obtener una conexion a BD * @return Un objeto tipo Connection que representa una conexion a la BD */ protected static Connection getConexion() { try{ if (conexion == null || conexion.isClosed()) { // Cargo el driver en memoria Class.forName(driver); // Establezco la conexion conexion=DriverManager.getConnection(url+bd,usuario,password); } } catch(SQLException e){ e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return conexion; } /** * Metodo consultar * @param String tiraSQL * @return ResultSet */ public static ResultSet consultar(String tiraSQL) { getConexion(); ResultSet resultado = null; try { Statement sentencia= conexion.createStatement(); resultado = sentencia.executeQuery(tiraSQL); } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return resultado; } /** * Metodo ejecutar * @param String TiraSQL * @return boolean */ public static boolean ejecutar(String tiraSQL) { getConexion(); boolean ok = false; try { Statement sentencia = conexion.createStatement(); int i = sentencia.executeUpdate(tiraSQL); if (i > 0) { ok = true; } sentencia.close (); } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return ok; } public static ResultSet consultarPrepare(PreparedStatement statement) { getConexion(); ResultSet resultado = null; try { resultado = statement.executeQuery(); } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return resultado; } /** * Metodo ejecutar * @param String TiraSQL * @return boolean */ public static boolean ejecutarPrepare(PreparedStatement statement) { getConexion(); boolean ok = false; try { int i = statement.executeUpdate(); if (i > 0) { ok = true; } } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return ok; } protected PreparedStatement generarPreparedStatement(String sql){ PreparedStatement statement = null; try { statement = conexion.prepareStatement(sql); } catch (SQLException ex) { Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex); } return statement; } }
03-09-cuartaentrega
javaBurguer/src/MODELO/Conexion.java
Java
asf20
4,076
import CONTROLADOR.ControladorMenuPrincipal; import VISTA.MenuPrincipal; /* Integrantes: Lilianny Rodriguez C.I.: 19.323.400 Jose Leonardo Jerez C.I.: */ public class Principal { public static void main(String[] args) { new ControladorMenuPrincipal(); } }
03-09-cuartaentrega
javaBurguer/src/Principal.java
Java
asf20
268
package VISTA; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.util.Date; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.SwingUtilities; import MODELO.ModeloIngrediente; import MODELO.ModeloProducto; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmOrdenes extends javax.swing.JFrame { private JPanel pnlOrdenes; private JLabel jLabel2; private JLabel jLabel1; private JComboBox cmbCantidad; private JLabel fecha; private JTable tblProductoOrden; private JScrollPane scpCatalogo; private JPanel pnlLlenarOrden; private JTextField txtEscribirNombres; private JTable tblProductoOrdenes; private JScrollPane scpProductoOrdenes; private JButton btnCancelarOrden; private JButton btnOkOrden; private JLabel lblBsTotal; private JLabel lblTotalMonto; private JLabel lblTotal; private JLabel lblMontoImpuesto; private JButton btnAgregar; private JButton btnRetirar; private JLabel lblNombres; private JTextField txtCedula; private JLabel lblCedula; private JLabel lblNro; private JLabel lblNroOrden; /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { frmOrdenes inst = new frmOrdenes(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); } public frmOrdenes() { super("Registro de Ordenes"); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { pnlOrdenes = new JPanel(); getContentPane().add(pnlOrdenes, BorderLayout.CENTER); pnlOrdenes.setLayout(null); pnlOrdenes.setBackground(new java.awt.Color(255,255,255)); pnlOrdenes.setPreferredSize(new java.awt.Dimension(1210, 516)); { lblNroOrden = new JLabel(); pnlOrdenes.add(lblNroOrden); lblNroOrden.setText("Nro de Orden:"); lblNroOrden.setBounds(21, 7, 118, 24); } { lblNro = new JLabel(); pnlOrdenes.add(lblNro); lblNro.setBounds(145, 12, 130, 19); lblNro.setBackground(new java.awt.Color(229,229,229)); } { lblCedula = new JLabel(); pnlOrdenes.add(lblCedula); lblCedula.setText("Cedula:"); lblCedula.setBounds(21, 72, 99, 30); } { txtCedula = new JTextField(); pnlOrdenes.add(txtCedula); txtCedula.setBounds(157, 79, 171, 23); } { lblNombres = new JLabel(); pnlOrdenes.add(lblNombres); lblNombres.setText("Nombres:"); lblNombres.setBounds(21, 117, 107, 24); } { txtEscribirNombres = new JTextField(); pnlOrdenes.add(txtEscribirNombres); txtEscribirNombres.setBounds(157, 119, 284, 22); } { pnlLlenarOrden = new JPanel(); pnlLlenarOrden.setBorder(BorderFactory.createTitledBorder("Carga de Producto")); pnlOrdenes.add(pnlLlenarOrden); pnlLlenarOrden.setLayout(null); pnlLlenarOrden.setBounds(21, 165, 1169, 294); pnlLlenarOrden.setBackground(new java.awt.Color(228,196,116)); { scpCatalogo = new JScrollPane(); pnlLlenarOrden.add(scpCatalogo); scpCatalogo.setBounds(661, 50, 492, 151); scpCatalogo.setBackground(new java.awt.Color(255,255,255)); { TableModel tblProductoOrdenModel = new DefaultTableModel( new String[][] { { "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" } }, new String[] { "Cantidad", "Descripcion", "Monto" }); tblProductoOrden = new JTable(); scpCatalogo.setViewportView(tblProductoOrden); tblProductoOrden.setModel(tblProductoOrdenModel); tblProductoOrden.setBounds(17, 28, 682, 138); tblProductoOrden.setPreferredSize(new java.awt.Dimension(472, 135)); } } { btnRetirar = new JButton(); pnlLlenarOrden.add(btnRetirar); btnRetirar.setText("Retirar"); btnRetirar.setBounds(535, 163, 102, 31); btnRetirar.setActionCommand("Retirar"); } { btnAgregar = new JButton(); pnlLlenarOrden.add(btnAgregar); btnAgregar.setText("Agregar"); btnAgregar.setBounds(535, 121, 102, 31); btnAgregar.setActionCommand("Agregar"); } { lblMontoImpuesto = new JLabel(); pnlLlenarOrden.add(lblMontoImpuesto); lblMontoImpuesto.setBounds(1077, 259, 75, 23); } { lblTotal = new JLabel(); pnlLlenarOrden.add(lblTotal); lblTotal.setText("Total:"); lblTotal.setBounds(809, 259, 97, 23); } { lblTotalMonto = new JLabel(); pnlLlenarOrden.add(lblTotalMonto); lblTotalMonto.setBounds(912, 259, 84, 23); } { lblBsTotal = new JLabel(); pnlLlenarOrden.add(lblBsTotal); lblBsTotal.setText("Bs"); lblBsTotal.setBounds(1008, 259, 70, 23); } { scpProductoOrdenes = new JScrollPane(); pnlLlenarOrden.add(scpProductoOrdenes); scpProductoOrdenes.setBounds(17, 50, 492, 151); { TableModel tblScrollProductoOrdenesModel = new DefaultTableModel( new String[][] { { "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" } }, new String[] { "Codigo", "Descripcion", "Precio Unitario" }); tblProductoOrdenes = new JTable(); scpProductoOrdenes.setViewportView(tblProductoOrdenes); tblProductoOrdenes.setModel(tblScrollProductoOrdenesModel); tblProductoOrdenes.setPreferredSize(new java.awt.Dimension(489, 144)); } } { ComboBoxModel cmbCantidadModel = new DefaultComboBoxModel( new String[] { "Item One", "Item Two" }); cmbCantidad = new JComboBox(); pnlLlenarOrden.add(cmbCantidad); cmbCantidad.setBounds(535, 73, 102, 31); int i =1; while(i<=100){ cmbCantidad.addItem(i); i++; } } { jLabel1 = new JLabel(); pnlLlenarOrden.add(jLabel1); jLabel1.setText("Cantidad"); jLabel1.setBounds(558, 43, 65, 24); } } { btnOkOrden = new JButton(); pnlOrdenes.add(btnOkOrden); btnOkOrden.setText("OK"); btnOkOrden.setBounds(946, 481, 117, 36); btnOkOrden.setActionCommand("OK"); } { btnCancelarOrden = new JButton(); pnlOrdenes.add(btnCancelarOrden); btnCancelarOrden.setText("Cancelar"); btnCancelarOrden.setBounds(1074, 481, 116, 36); btnCancelarOrden.setActionCommand("Cancelar"); } { fecha = new JLabel(); pnlOrdenes.add(fecha); fecha.setBounds(157, 37, 171, 21); } { jLabel2 = new JLabel(); pnlOrdenes.add(jLabel2); jLabel2.setText("Fecha:"); jLabel2.setBounds(22, 37, 118, 24); } } pack(); this.setSize(1210, 570); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public JLabel getLblTotalMonto() { return lblTotalMonto; } public void setLblTotalMonto(JLabel lblTotalMonto) { this.lblTotalMonto = lblTotalMonto; } public JTable getTblProductoOrden() { return tblProductoOrden; } public void setTblProductoOrden(JTable tblProductoOrden) { this.tblProductoOrden = tblProductoOrden; } public JTextField getTxtEscribirNombres() { return txtEscribirNombres; } public void setTxtEscribirNombres(JTextField txtEscribirNombres) { this.txtEscribirNombres = txtEscribirNombres; } public JTable getTblProductoOrdenes() { return tblProductoOrdenes; } public void setTblProductoOrdenes(JTable tblProductoOrdenes) { this.tblProductoOrdenes = tblProductoOrdenes; } public JTextField getTxtCedula() { return txtCedula; } public void setTxtCedula(JTextField txtCedula) { this.txtCedula = txtCedula; } public Vector<String []> getInfoTabla(){ Vector<String []> v = new Vector<String[]>(); for (int i = 0; i < tblProductoOrden.getRowCount(); i++){ if(!tblProductoOrden.getValueAt(i, 0).equals("")) {String [] s = new String [] {""+tblProductoOrden.getValueAt(i, 0),""+tblProductoOrden.getValueAt(i, 1),""+tblProductoOrden.getValueAt(i, 2)}; v.add(s);} else break; } return v; } public void addListener(ActionListener actionListener){ this.btnAgregar.addActionListener(actionListener); this.btnCancelarOrden.addActionListener(actionListener); this.btnOkOrden.addActionListener(actionListener); this.btnRetirar.addActionListener(actionListener); } public void limpiar(int num) { txtCedula.setText(""); txtEscribirNombres.setText(""); lblTotalMonto.setText(""); lblNro.setText(""+num); cmbCantidad.setSelectedIndex(0); Date d = new Date(); fecha.setText(""+d.toLocaleString()); TableModel m = tblProductoOrden.getModel(); int i =0; while(i< tblProductoOrden.getRowCount()) { m.setValueAt("", i, 0); m.setValueAt("", i, 1); m.setValueAt("", i, 2); i++; } } public void mostrarMensaje(String mensaje) { JOptionPane.showMessageDialog(this, mensaje); } public void quitar() { int i = tblProductoOrden.getSelectedRow(); if(i!=-1){ tblProductoOrden.setValueAt("", i, 1); tblProductoOrden.setValueAt("", i, 0); tblProductoOrden.setValueAt("", i, 2); calcularTotal(); } else mostrarMensaje("Selecione una fila"); } public void agregar(ModeloProducto m) { int i =0; while(i< tblProductoOrden.getRowCount()) { if(tblProductoOrden.getValueAt(i,0).equals("")){ tblProductoOrden.setValueAt(m.getDescripcion(), i, 1); tblProductoOrden.setValueAt(cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex()), i, 0); double precio = m.getPrecio() *(Integer)cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex()); tblProductoOrden.setValueAt(precio, i, 2); break; } else if(tblProductoOrden.getValueAt(i,1).equals(m.getDescripcion())) { double precio = m.getPrecio() *(Integer)cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex()); tblProductoOrden.setValueAt(precio, i, 2); break; } i++; } calcularTotal(); } public void calcularTotal() { int i =0; double total =0; while(i< tblProductoOrden.getRowCount()) { if(tblProductoOrden.getValueAt(i,0).equals("")){ break; } else total+=(Double)tblProductoOrden.getValueAt(i, 2); i++; } lblTotalMonto.setText(""+total); } public boolean contar() { int i =0; int cont = 0; while(i< tblProductoOrden.getRowCount()) { if(tblProductoOrden.getValueAt(i,0).equals("")){ cont++; } i++; } return (cont==tblProductoOrden.getRowCount()); } public JLabel getLblNro() { return lblNro; } public void setLblNro(JLabel lblNro) { this.lblNro = lblNro; } public Integer cantidad() { return (Integer)cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex()); } public void setCmbCantidad(JComboBox cmbCantidad) { this.cmbCantidad = cmbCantidad; } }
03-09-cuartaentrega
javaBurguer/src/VISTA/frmOrdenes.java
Java
asf20
12,595
package VISTA; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.SwingUtilities; import MODELO.ModeloIngrediente; import bean.JTextFieldValidator; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmProductos extends javax.swing.JFrame { private JPanel pnlProductos; private JLabel lblCategoriaProducto; private JTextField txtDescripcionProducto; private JLabel lblDescripcionProducto; private JTextField txtCodigoProducto; private JLabel lblCodigoProducto; private JLabel jLabel1; private JComboBox cmbCantidad; private JButton btnRetirarReceta; private JButton btnAgregarReceta; private JTable tblReceta; private JScrollPane scpReceta; private JTable tblIngredientes; private JScrollPane scpIngredientes; private JPanel pnlIngredientes; private JButton btnCancelarProducto; private JButton btnOkProducto; private JLabel lblBsProducto; private JTextField txtPrecioProducto; private JLabel lblPrecioProducto; private JComboBox cmbCategoriaProducto; private JPanel pnlDatosProductos; /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { frmProductos inst = new frmProductos(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); } public frmProductos() { super("Registro de Productos"); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { pnlProductos = new JPanel(); getContentPane().add(pnlProductos, BorderLayout.CENTER); pnlProductos.setLayout(null); pnlProductos.setBackground(new java.awt.Color(255,255,255)); pnlProductos.setPreferredSize(new java.awt.Dimension(980, 696)); { pnlDatosProductos = new JPanel(); pnlDatosProductos.setBorder(BorderFactory.createTitledBorder("Datos")); pnlProductos.add(pnlDatosProductos); pnlDatosProductos.setLayout(null); pnlDatosProductos.setBounds(18, 39, 985, 595); pnlDatosProductos.setBackground(new java.awt.Color(228,196,116)); { lblCodigoProducto = new JLabel(); pnlDatosProductos.add(lblCodigoProducto); lblCodigoProducto.setText("Codigo:"); lblCodigoProducto.setBounds(17, 35, 63, 26); } { txtCodigoProducto = new JTextFieldValidator(JTextFieldValidator.SOLO_NUMEROS); pnlDatosProductos.add(txtCodigoProducto); txtCodigoProducto.setBounds(118, 34, 194, 28); } { lblDescripcionProducto = new JLabel(); pnlDatosProductos.add(lblDescripcionProducto); lblDescripcionProducto.setText("Descripcion:"); lblDescripcionProducto.setBounds(360, 35, 92, 26); } { txtDescripcionProducto = new JTextField(); pnlDatosProductos.add(txtDescripcionProducto); txtDescripcionProducto.setBounds(483, 32, 193, 28); } { lblCategoriaProducto = new JLabel(); pnlDatosProductos.add(lblCategoriaProducto); lblCategoriaProducto.setText("Categoria:"); lblCategoriaProducto.setBounds(17, 80, 91, 26); } { ComboBoxModel cmbCategoriaProductoModel = new DefaultComboBoxModel( new String[] { "Item One", "Item Two" }); cmbCategoriaProducto = new JComboBox(); pnlDatosProductos.add(cmbCategoriaProducto); cmbCategoriaProducto.setModel(cmbCategoriaProductoModel); cmbCategoriaProducto.setBounds(120, 79, 194, 28); } { lblPrecioProducto = new JLabel(); pnlDatosProductos.add(lblPrecioProducto); lblPrecioProducto.setText("Precio Unitario:"); lblPrecioProducto.setBounds(360, 79, 117, 29); } { txtPrecioProducto = new JTextFieldValidator(JTextFieldValidator.SOLO_NUMEROS); pnlDatosProductos.add(txtPrecioProducto); txtPrecioProducto.setBounds(483, 78, 126, 28); } { lblBsProducto = new JLabel(); pnlDatosProductos.add(lblBsProducto); lblBsProducto.setText("Bs"); lblBsProducto.setBounds(628, 78, 48, 28); } { btnOkProducto = new JButton(); pnlDatosProductos.add(btnOkProducto); btnOkProducto.setText("OK"); btnOkProducto.setBounds(629, 542, 113, 31); btnOkProducto.setActionCommand("OK"); } { btnCancelarProducto = new JButton(); pnlDatosProductos.add(btnCancelarProducto); btnCancelarProducto.setText("Cancelar"); btnCancelarProducto.setBounds(765, 542, 112, 31); btnCancelarProducto.setActionCommand("Cancelar"); } { pnlIngredientes = new JPanel(); pnlDatosProductos.add(pnlIngredientes); pnlIngredientes.setBackground(new java.awt.Color(237,206,149)); pnlIngredientes.setBorder(BorderFactory.createTitledBorder("Receta")); pnlIngredientes.setLayout(null); pnlIngredientes.setBounds(29, 126, 916, 395); { scpIngredientes = new JScrollPane(); pnlIngredientes.add(scpIngredientes); scpIngredientes.setBounds(17, 32, 243, 195); { TableModel tblIngredientesModel = new DefaultTableModel( new String[][] { { "", "" }, { "", "" } ,{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" }}, new String[] { "Codigo", "Descripcion" }); tblIngredientes = new JTable(); scpIngredientes.setViewportView(tblIngredientes); tblIngredientes.setModel(tblIngredientesModel); tblIngredientes.setPreferredSize(new java.awt.Dimension(240,183)); } } { scpReceta = new JScrollPane(); pnlIngredientes.add(scpReceta); scpReceta.setBounds(348, 32, 551, 195); { TableModel tblRecetaModel = new DefaultTableModel( new String[][] { { "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" } }, new String[] { "Codigo", "Descripcion", "Cantidad" }); tblReceta = new JTable(); scpReceta.setViewportView(tblReceta); tblReceta.setModel(tblRecetaModel); tblReceta.setPreferredSize(new java.awt.Dimension(548, 170)); } } { btnAgregarReceta = new JButton(); pnlIngredientes.add(btnAgregarReceta); btnAgregarReceta.setText("Agregar a Receta"); btnAgregarReceta.setBounds(53, 259, 207, 36); btnAgregarReceta.setActionCommand("Agregar"); } { btnRetirarReceta = new JButton(); pnlIngredientes.add(btnRetirarReceta); btnRetirarReceta.setText("Retirar de Receta"); btnRetirarReceta.setBounds(53, 317, 207, 36); btnRetirarReceta.setActionCommand("Retirar"); } { ComboBoxModel cmbCantidadModel = new DefaultComboBoxModel( new String[] { "Item One", "Item Two" }); cmbCantidad = new JComboBox(); pnlIngredientes.add(cmbCantidad); int i =1; while(i<=100){ cmbCantidad.addItem(i); i++; } cmbCantidad.setBounds(266, 77, 76, 22); } { jLabel1 = new JLabel(); pnlIngredientes.add(jLabel1); jLabel1.setText("Cantidad"); jLabel1.setBounds(271, 41, 65, 24); } } } } pack(); this.setSize(1037, 687); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public Vector<String []> getInfoTabla(){ Vector<String []> v = new Vector<String[]>(); for (int i = 0; i < tblReceta.getRowCount(); i++){ if(!tblReceta.getValueAt(i, 0).equals("")) {String [] s = new String [] {""+tblReceta.getValueAt(i, 0),""+tblReceta.getValueAt(i, 1),""+tblReceta.getValueAt(i, 2)}; v.add(s);} else break; } return v; } public JTable getTblIngredientes() { return tblIngredientes; } public void setTblIngredientes(JTable tblIngredientes) { this.tblIngredientes = tblIngredientes; } public JComboBox getCmbCategoriaProducto() { return cmbCategoriaProducto; } public void setCmbCategoriaProducto(JComboBox cmbCategoriaProducto) { this.cmbCategoriaProducto = cmbCategoriaProducto; } public void addListener(ActionListener actionListener){ this.btnAgregarReceta.addActionListener(actionListener); this.btnCancelarProducto.addActionListener(actionListener); this.btnOkProducto.addActionListener(actionListener); this.btnRetirarReceta.addActionListener(actionListener); } public void limpiar() { txtCodigoProducto.setText(""); txtDescripcionProducto.setText(""); txtPrecioProducto.setText(""); TableModel m = tblReceta.getModel(); int i =0; while(i< tblReceta.getRowCount()) { m.setValueAt("", i, 0); m.setValueAt("", i, 1); m.setValueAt("", i, 2); i++; } } public void mostrarMensaje(String mensaje) { JOptionPane.showMessageDialog(this, mensaje); } public JTextField getTxtDescripcionProducto() { return txtDescripcionProducto; } public void setTxtDescripcionProducto(JTextField txtDescripcionProducto) { this.txtDescripcionProducto = txtDescripcionProducto; } public JTextField getTxtCodigoProducto() { return txtCodigoProducto; } public void setTxtCodigoProducto(JTextField txtCodigoProducto) { this.txtCodigoProducto = txtCodigoProducto; } public JTextField getTxtPrecioProducto() { return txtPrecioProducto; } public void setTxtPrecioProducto(JTextField txtPrecioProducto) { this.txtPrecioProducto = txtPrecioProducto; } public void quitar() { int i = tblReceta.getSelectedRow(); if(i!=-1){ tblReceta.setValueAt("", i, 1); tblReceta.setValueAt("", i, 2); tblReceta.setValueAt("", i, 0); } else mostrarMensaje("Selecione una fila"); } public void agregar(ModeloIngrediente m) { int i =0; while(i< tblReceta.getRowCount()) { if(tblReceta.getValueAt(i,1).equals(m.getDescripcion())){ tblReceta.setValueAt(cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex()), i, 2); break; } else if(tblReceta.getValueAt(i,0).equals("")){ tblReceta.setValueAt(m.getDescripcion(), i, 1); tblReceta.setValueAt(cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex()), i, 2); tblReceta.setValueAt(m.getCodigo(), i, 0); break; } i++; } } public JTable getTblReceta() { return tblReceta; } public void setTblReceta(JTable tblReceta) { this.tblReceta = tblReceta; } public boolean contar() { int i =0; int cont = 0; while(i< tblReceta.getRowCount()) { if(tblReceta.getValueAt(i,0).equals("")){ cont++; } i++; } return (cont==tblReceta.getRowCount()); } }
03-09-cuartaentrega
javaBurguer/src/VISTA/frmProductos.java
Java
asf20
12,314
package VISTA; import java.awt.BorderLayout; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JViewport; import javax.swing.WindowConstants; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.SwingUtilities; import bean.JTextFieldValidator; import CONTROLADOR.ControladorCategorias; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmCategorias extends javax.swing.JFrame { private JPanel pnlCategorias; private JTextFieldValidator txtCodigo; private JButton btnModificarCategorias; private JButton btnCancelarCategorias; private JTable tblCategorias; private JScrollPane scpCategorias; private JButton btnOkCategorias; private JButton btnBuscar; private JTextField txtDescripcion; private JLabel lblDescripcion; private JLabel lblCodigo; private JPanel pnlDatosCategorias; private ControladorCategorias ctrlCategorias; public frmCategorias() { super("Registro de Categorias"); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { pnlCategorias = new JPanel(); getContentPane().add(pnlCategorias, BorderLayout.CENTER); pnlCategorias.setLayout(null); pnlCategorias.setBackground(new java.awt.Color(255,255,255)); pnlCategorias.setLayout(null); pnlCategorias.setPreferredSize(new java.awt.Dimension(436, 436)); { pnlDatosCategorias = new JPanel(); pnlDatosCategorias.setBorder(BorderFactory.createTitledBorder("Datos")); pnlCategorias.add(pnlDatosCategorias); pnlDatosCategorias.setLayout(null); pnlDatosCategorias.setBounds(62, 23, 437, 211); pnlDatosCategorias.setBackground(new java.awt.Color(228,196,116)); pnlDatosCategorias.setEnabled(false); { lblCodigo = new JLabel(); pnlDatosCategorias.add(lblCodigo); lblCodigo.setText("Codigo:"); lblCodigo.setBounds(17, 44, 70, 28); } { txtCodigo = new JTextFieldValidator(JTextFieldValidator.SOLO_NUMEROS); pnlDatosCategorias.add(txtCodigo); txtCodigo.setBounds(118, 44, 138, 25); } { lblDescripcion = new JLabel(); pnlDatosCategorias.add(lblDescripcion); lblDescripcion.setText("Descripcion:"); lblDescripcion.setBounds(17, 84, 89, 21); } { txtDescripcion = new JTextField(); pnlDatosCategorias.add(txtDescripcion); txtDescripcion.setBounds(118, 81, 169, 24); } { btnOkCategorias = new JButton(); pnlDatosCategorias.add(btnOkCategorias); btnOkCategorias.setText("OK"); btnOkCategorias.setBounds(22, 141, 104, 32); } { btnCancelarCategorias = new JButton(); pnlDatosCategorias.add(btnCancelarCategorias); btnCancelarCategorias.setText("Cancelar"); btnCancelarCategorias.setBounds(312, 143, 103, 32); btnCancelarCategorias.setActionCommand("Cancelar"); } { btnBuscar = new JButton(); pnlDatosCategorias.add(btnBuscar); btnBuscar.setText("Buscar"); btnBuscar.setActionCommand("Buscar"); btnBuscar.setBounds(287, 40, 99, 32); } { btnModificarCategorias = new JButton(); pnlDatosCategorias.add(btnModificarCategorias); btnModificarCategorias.setText("Modificar"); btnModificarCategorias.setBounds(166, 142, 103, 31); btnModificarCategorias.setActionCommand("Modificar"); } } { scpCategorias = new JScrollPane(); pnlCategorias.add(scpCategorias); scpCategorias.setBounds(62, 259, 437, 140); { TableModel tblCategoriasModel = new DefaultTableModel( new String[][] { { "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" } }, new String[] { "Codigo", "Descripcion" }); tblCategorias = new JTable(); scpCategorias.setViewportView(tblCategorias); tblCategorias.setModel(tblCategoriasModel); } } } pack(); this.setSize(575, 465); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addlistener(ActionListener actionlistener){ btnModificarCategorias.addActionListener(actionlistener); btnOkCategorias.addActionListener(actionlistener); btnCancelarCategorias.addActionListener(actionlistener); btnBuscar.addActionListener(actionlistener); } public JTextField getTxtCodigo() { return txtCodigo; } public JTextField getTxtDescripcion() { return txtDescripcion; } public void setTxtDescripcion(JTextField txtDescripcion) { this.txtDescripcion = txtDescripcion; } public JTable gettblCategorias(){ return tblCategorias; } public void bloquearNuevo(){ pnlDatosCategorias.setEnabled(false); } public void habilitarNuevo(){ pnlDatosCategorias.setEnabled(true); } public void limpiarCancelar(){ pnlDatosCategorias.setEnabled(true); txtCodigo.setText(""); txtDescripcion.setText(""); } public void bloquearCodigo(){ txtCodigo.setEnabled(false); } public void mostrarMensaje(String mensaje) { JOptionPane.showMessageDialog(this, mensaje); } }
03-09-cuartaentrega
javaBurguer/src/VISTA/frmCategorias.java
Java
asf20
6,297
package VISTA; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.border.LineBorder; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.SwingUtilities; import bean.JTextFieldValidator; import CONTROLADOR.ControladorIngredientes; import MODELO.ModeloIngrediente; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmIngredientes extends javax.swing.JFrame { private JPanel pnlIngredientes; private JLabel lblCodigoIngredientes; private JTextField txtDescripcionIngredientes; private JLabel lblStockMinimo; private JButton btnRegistrarNuevoIng; private JTable tblIngredientes; private JScrollPane scpCategorias; private JButton btnRegistrarCompra; private JButton btnCancelarNuevoIng; private JButton btnAceptar; private JButton btnCancelarEntrada; private JButton btnProcesar; private JLabel lblGuion; private JTextField txtCantidad; private JLabel lblCantidad; private JLabel lblDescripcionEntrada; private JLabel jLabel1; private JPanel pnlEntradaIngrediente; private JScrollPane scpIngredientes; private JPanel pnlNuevoIngrediente; private JTextFieldValidator txtStockMinimo; private JLabel lblDescripcion; private JTextFieldValidator txtCodigoIngrediente; private ControladorIngredientes ctrlIngredientes; private DefaultTableModel modelo; public frmIngredientes() { super("Registro de Ingredientes"); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { pnlIngredientes = new JPanel(); getContentPane().add(pnlIngredientes, BorderLayout.CENTER); pnlIngredientes.setLayout(null); pnlIngredientes.setBackground(new java.awt.Color(255,255,255)); pnlIngredientes.setPreferredSize(new java.awt.Dimension(1107, 601)); { pnlNuevoIngrediente = new JPanel(); pnlNuevoIngrediente.setBorder(BorderFactory.createTitledBorder("Nuevo Ingrediente")); pnlIngredientes.add(pnlNuevoIngrediente); pnlNuevoIngrediente.setLayout(null); pnlNuevoIngrediente.setBounds(19, 14, 912, 174); pnlNuevoIngrediente.setBackground(new java.awt.Color(228,196,116)); { txtStockMinimo = new JTextFieldValidator(JTextFieldValidator.SOLO_NUMEROS); pnlNuevoIngrediente.add(txtStockMinimo); txtStockMinimo.setBounds(140, 89, 140, 27); txtStockMinimo.setEnabled(false); } { lblStockMinimo = new JLabel(); pnlNuevoIngrediente.add(lblStockMinimo); lblStockMinimo.setText("Stock:"); lblStockMinimo.setBounds(43, 87, 99, 29); } { txtDescripcionIngredientes = new JTextField(); pnlNuevoIngrediente.add(txtDescripcionIngredientes); txtDescripcionIngredientes.setBounds(540, 45, 194, 29); txtDescripcionIngredientes.setEnabled(false); } { lblDescripcion = new JLabel(); pnlNuevoIngrediente.add(lblDescripcion); lblDescripcion.setText("Descripcion:"); lblDescripcion.setBounds(352, 45, 93, 26); } { txtCodigoIngrediente = new JTextFieldValidator( JTextFieldValidator.SOLO_NUMEROS); pnlNuevoIngrediente.add(txtCodigoIngrediente); txtCodigoIngrediente.setBounds(140, 42, 140, 27); txtCodigoIngrediente.setEnabled(false); } { lblCodigoIngredientes = new JLabel(); pnlNuevoIngrediente.add(lblCodigoIngredientes); lblCodigoIngredientes.setText("Codigo:"); lblCodigoIngredientes.setBounds(43, 41, 97, 27); } { btnAceptar = new JButton(); pnlNuevoIngrediente.add(btnAceptar); btnAceptar.setText("Aceptar"); btnAceptar.setBounds(765, 32, 112, 32); btnAceptar.setActionCommand("Aceptar"); btnAceptar.setEnabled(false); } { btnCancelarNuevoIng = new JButton(); pnlNuevoIngrediente.add(btnCancelarNuevoIng); btnCancelarNuevoIng.setText("Cancelar"); btnCancelarNuevoIng.setBounds(765, 85, 112, 31); btnCancelarNuevoIng.setActionCommand("Cancelar"); btnCancelarNuevoIng.setEnabled(false); } } { scpIngredientes = new JScrollPane(); pnlIngredientes.add(scpIngredientes); scpIngredientes.setBounds(19, 220, 762, 195); { scpCategorias = new JScrollPane(); scpIngredientes.setViewportView(scpCategorias); scpCategorias.setBounds(18, 260, 471, 140); { TableModel tblCategoriasModel = new DefaultTableModel( new String[][] { { "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" } }, new String[] { "Codigo", "Ingrediente", "Stock" }); tblIngredientes = new JTable(); scpCategorias.setViewportView(tblIngredientes); tblIngredientes.setModel(tblCategoriasModel); } } } { pnlEntradaIngrediente = new JPanel(); pnlEntradaIngrediente.setBorder(BorderFactory.createTitledBorder("Entrada de Ingredientes")); pnlIngredientes.add(pnlEntradaIngrediente); pnlEntradaIngrediente.setVisible(false); pnlEntradaIngrediente.setLayout(null); pnlEntradaIngrediente.setBounds(19, 449, 915, 126); pnlEntradaIngrediente.setBackground(new java.awt.Color(228,196,116)); { jLabel1 = new JLabel(); pnlEntradaIngrediente.add(jLabel1); jLabel1.setText("Descripcion:"); jLabel1.setBounds(17, 39, 98, 24); } { lblDescripcionEntrada = new JLabel(); pnlEntradaIngrediente.add(lblDescripcionEntrada); lblDescripcionEntrada.setBounds(199, 44, 158, 24); } { lblCantidad = new JLabel(); pnlEntradaIngrediente.add(lblCantidad); lblCantidad.setText("Cantidad a Ingresar:"); lblCantidad.setBounds(17, 75, 182, 32); } { txtCantidad = new JTextFieldValidator(JTextFieldValidator.SOLO_NUMEROS); pnlEntradaIngrediente.add(txtCantidad); txtCantidad.setBounds(199, 80, 139, 29); } { lblGuion = new JLabel(); pnlEntradaIngrediente.add(lblGuion); lblGuion.setBounds(304, 84, 38, 15); lblGuion.setFont(new java.awt.Font("Bitstream Charter",1,28)); } { btnProcesar = new JButton(); pnlEntradaIngrediente.add(btnProcesar); btnProcesar.setText("Procesar"); btnProcesar.setBounds(499, 42, 173, 36); btnProcesar.setActionCommand("Procesar"); } { btnCancelarEntrada = new JButton(); pnlEntradaIngrediente.add(btnCancelarEntrada); btnCancelarEntrada.setText("Cancelar Entrada"); btnCancelarEntrada.setBounds(688, 42, 170, 36); btnCancelarEntrada.setActionCommand("CancelarE"); } } { btnRegistrarCompra = new JButton(); pnlIngredientes.add(btnRegistrarCompra); btnRegistrarCompra.setText("Realizar Compra"); btnRegistrarCompra.setBounds(814, 328, 154, 38); btnRegistrarCompra.setActionCommand("Compra"); } { btnRegistrarNuevoIng = new JButton(); pnlIngredientes.add(btnRegistrarNuevoIng); btnRegistrarNuevoIng.setText("Registrar Nuevo"); btnRegistrarNuevoIng.setBounds(814, 252, 154, 42); } } pack(); this.setSize(994, 622); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addListener(ActionListener actionListener){ this.btnCancelarEntrada.addActionListener(actionListener); this.btnCancelarNuevoIng.addActionListener(actionListener); this.btnRegistrarCompra.addActionListener(actionListener); this.btnRegistrarNuevoIng.addActionListener(actionListener); this.btnProcesar.addActionListener(actionListener); this.btnAceptar.addActionListener(actionListener); } public JTable getTblIngredientes() { return tblIngredientes; } public void setTblIngredientes(JTable tblIngredientes) { this.tblIngredientes = tblIngredientes; } public void limpiarNuevo(){ this.txtDescripcionIngredientes.setText(""); this.txtStockMinimo.setText(""); this.txtCodigoIngrediente.setText(""); } public void limpiarEntrada(){ this.txtCantidad.setText(""); this.lblDescripcionEntrada.setText(""); } public void bloquearNuevo(){ this.txtCodigoIngrediente.setEnabled(false); this.txtDescripcionIngredientes.setEnabled(false); this.txtStockMinimo.setEnabled(false); this.btnAceptar.setEnabled(false); this.btnCancelarNuevoIng.setEnabled(false); } public void habilitarNuevo(){ this.txtCodigoIngrediente.setEnabled(true); this.txtDescripcionIngredientes.setEnabled(true); this.txtStockMinimo.setEnabled(true); this.btnAceptar.setEnabled(true); this.btnCancelarNuevoIng.setEnabled(true); } public void bloquearEntrada(){ this.txtCantidad.setEnabled(false); this.pnlEntradaIngrediente.setVisible(false); } public void habilitarEntrada(){ this.txtCantidad.setEnabled(true); this.pnlEntradaIngrediente.setVisible(true); } public JTextField getTxtDescripcionIngredientes() { return txtDescripcionIngredientes; } public JTextField getTxtStockMinimo() { return txtStockMinimo; } public JTextField getTxtCodigoIngrediente() { return txtCodigoIngrediente; } public JTextField getTxtCantidad() { return txtCantidad; } public void mostrarMensaje(String mensaje) { JOptionPane.showMessageDialog(this, mensaje); } public JLabel getLblDescripcionEntrada() { return lblDescripcionEntrada; } public void setLblDescripcionEntrada(JLabel lblDescripcionEntrada) { this.lblDescripcionEntrada = lblDescripcionEntrada; } }
03-09-cuartaentrega
javaBurguer/src/VISTA/frmIngredientes.java
Java
asf20
10,684
package VISTA; import java.awt.BorderLayout; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.WindowConstants; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.SwingUtilities; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmListados extends javax.swing.JFrame { private JPanel pnlListados; private JPanel pnlListadoIngredientes; private JPanel pnlOrden; private JScrollPane scpProductoOrdenes; private JTable tblProductoOrdenes; private JRadioButton rbtnDescendente; private ButtonGroup buttonGroup3; private ButtonGroup buttonGroup2; private ButtonGroup buttonGroup1; private JButton btnCancelar; private JButton btnCargarListados; private JRadioButton rbtnMas; private JRadioButton rbtnAscendente; private JRadioButton rbtnProductos; private JRadioButton rbtnIngredientes; private JPanel pnlFiltro; private JPanel pnlListadoVentas; private DefaultTableModel modeloIngrediente,modeloProducto,modeloMas; /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { frmListados inst = new frmListados(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); } public frmListados() { super("Listados"); initGUI(); modeloIngrediente= new DefaultTableModel(null, new String[] { "Ingrediente", "Stock en Almacen" }); modeloProducto= new DefaultTableModel(null, new String[] { "Producto", "Total Generado","Cantidad Vendida" }); modeloMas= new DefaultTableModel(null, new String[] { "Ingrediente", "Cantidade Usada" }); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { pnlListados = new JPanel(); getContentPane().add(pnlListados, BorderLayout.CENTER); pnlListados.setLayout(null); pnlListados.setBackground(new java.awt.Color(255,255,255)); pnlListados.setPreferredSize(new java.awt.Dimension(774, 467)); { pnlListadoVentas = new JPanel(); pnlListadoVentas.setBorder(BorderFactory.createTitledBorder("Listados")); pnlListados.add(pnlListadoVentas); pnlListadoVentas.setLayout(null); pnlListadoVentas.setBounds(29, 12, 728, 211); pnlListadoVentas.setBackground(new java.awt.Color(228,196,116)); { pnlFiltro = new JPanel(); pnlFiltro.setBorder(BorderFactory.createTitledBorder("Selecione")); pnlListadoVentas.add(pnlFiltro); pnlFiltro.setLayout(null); pnlFiltro.setBounds(89, 32, 329, 152); pnlFiltro.setBackground(new java.awt.Color(255,255,255)); { rbtnIngredientes = new JRadioButton(); pnlFiltro.add(rbtnIngredientes); rbtnIngredientes.setText("Listado de Ingredientes"); rbtnIngredientes.setBounds(35, 30, 272, 30); rbtnIngredientes.setBackground(new java.awt.Color(255,255,255)); rbtnIngredientes.setActionCommand("Ingredientes"); getButtonGroup1().add(rbtnIngredientes); } { rbtnProductos = new JRadioButton(); pnlFiltro.add(rbtnProductos); rbtnProductos.setText("Listado de Productos Vendidos"); rbtnProductos.setBounds(35, 67, 278, 30); rbtnProductos.setBackground(new java.awt.Color(255,255,255)); rbtnProductos.setActionCommand("Productos"); getButtonGroup1().add(rbtnProductos); } { rbtnMas = new JRadioButton(); pnlFiltro.add(rbtnMas); rbtnMas.setText("Listado de Ingredientes mas Usados"); rbtnMas.setBounds(35, 104, 278, 30); rbtnMas.setBackground(new java.awt.Color(255,255,255)); rbtnMas.setActionCommand("Mas"); getButtonGroup1().add(rbtnMas); } } { pnlOrden = new JPanel(); pnlOrden.setBorder(BorderFactory.createTitledBorder("Orden")); pnlListadoVentas.add(pnlOrden); pnlOrden.setLayout(null); pnlOrden.setBounds(438, 36, 285, 148); pnlOrden.setBackground(new java.awt.Color(255,255,255)); { rbtnAscendente = new JRadioButton(); pnlOrden.add(rbtnAscendente); rbtnAscendente.setText("Ascendente"); rbtnAscendente.setBounds(64, 34, 171, 30); rbtnAscendente.setBackground(new java.awt.Color(255,255,255)); rbtnAscendente.setActionCommand("Asc"); getButtonGroup2().add(rbtnAscendente); } { rbtnDescendente = new JRadioButton(); pnlOrden.add(rbtnDescendente); rbtnDescendente.setText("Descendente"); rbtnDescendente.setBounds(64, 71, 171, 30); rbtnDescendente.setBackground(new java.awt.Color(255,255,255)); rbtnDescendente.setActionCommand("Asc"); getButtonGroup2().add(rbtnDescendente); } } } { pnlListadoIngredientes = new JPanel(); pnlListadoIngredientes.setBorder(BorderFactory.createTitledBorder("Listado")); pnlListados.add(pnlListadoIngredientes); pnlListadoIngredientes.setLayout(null); pnlListadoIngredientes.setBounds(29, 259, 728, 184); pnlListadoIngredientes.setBackground(new java.awt.Color(228,196,116)); pnlListadoIngredientes.add(getScpProductoOrdenes()); } { btnCargarListados = new JButton(); pnlListados.add(btnCargarListados); btnCargarListados.setText("Generar"); btnCargarListados.setBounds(272, 455, 107, 34); btnCargarListados.setActionCommand("Generar"); } { btnCancelar = new JButton(); pnlListados.add(btnCancelar); btnCancelar.setText("Cancelar"); btnCancelar.setBounds(410, 455, 107, 34); btnCancelar.setActionCommand("Cancelar"); } } pack(); this.setSize(784, 530); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } private JScrollPane getScpProductoOrdenes() { if(scpProductoOrdenes == null) { scpProductoOrdenes = new JScrollPane(); scpProductoOrdenes.setBounds(17, 20, 694, 147); scpProductoOrdenes.setViewportView(getTblProductoOrdenes()); } return scpProductoOrdenes; } private JTable getTblProductoOrdenes() { if(tblProductoOrdenes == null) { tblProductoOrdenes = new JTable(); // tblProductoOrdenes.setModel(tblProductoOrdenesModel); tblProductoOrdenes.setPreferredSize(new java.awt.Dimension(489,144)); } return tblProductoOrdenes; } public void addListener(ActionListener actionListener){ this.btnCancelar.addActionListener(actionListener); this.btnCargarListados.addActionListener(actionListener); this.rbtnAscendente.addActionListener(actionListener); this.rbtnDescendente.addActionListener(actionListener); this.rbtnIngredientes.addActionListener(actionListener); this.rbtnMas.addActionListener(actionListener); this.rbtnProductos.addActionListener(actionListener); } public DefaultTableModel getModeloIngrediente() { return modeloIngrediente; } public void setModeloIngrediente(DefaultTableModel modeloIngrediente) { this.modeloIngrediente = modeloIngrediente; } public DefaultTableModel getModeloProducto() { return modeloProducto; } public void setModeloProducto(DefaultTableModel modeloProducto) { this.modeloProducto = modeloProducto; } public DefaultTableModel getModeloMas() { return modeloMas; } public void setModeloMas(DefaultTableModel modeloMas) { this.modeloMas = modeloMas; } public void setTblProductoOrdenes(JTable tblProductoOrdenes) { this.tblProductoOrdenes = tblProductoOrdenes; } public JTable getProductoOrdenes() { return tblProductoOrdenes; } public void mostrarMensaje(String mensaje) { JOptionPane.showMessageDialog(this, mensaje); } private ButtonGroup getButtonGroup1() { if(buttonGroup1 == null) { buttonGroup1 = new ButtonGroup(); } return buttonGroup1; } private ButtonGroup getButtonGroup2() { if(buttonGroup2 == null) { buttonGroup2 = new ButtonGroup(); } return buttonGroup2; } }
03-09-cuartaentrega
javaBurguer/src/VISTA/frmListados.java
Java
asf20
8,741
package VISTA; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.WindowConstants; import javax.swing.SwingUtilities; import CONTROLADOR.ControladorMenuPrincipal; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class MenuPrincipal extends javax.swing.JFrame { private JPanel pnlMenuPrincipal; private JPanel pnlConfiguracion; private JButton btnIngredientes; private JButton btnProductos; private JButton btnListados; private JButton btnGenerarOrdenes; private JButton btnCategorias; /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { MenuPrincipal inst = new MenuPrincipal(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); } public MenuPrincipal() { super("Menu Principal"); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { pnlMenuPrincipal = new JPanel(); getContentPane().add(pnlMenuPrincipal, BorderLayout.CENTER); pnlMenuPrincipal.setLayout(null); pnlMenuPrincipal.setBackground(new java.awt.Color(255,255,255)); pnlMenuPrincipal.setLayout(null); pnlMenuPrincipal.setPreferredSize(new java.awt.Dimension(763, 353)); { pnlConfiguracion = new JPanel(); pnlMenuPrincipal.add(pnlConfiguracion); pnlConfiguracion.setLayout(null); pnlConfiguracion.setBounds(21, 25, 710, 137); pnlConfiguracion.setBackground(new java.awt.Color(228,196,116)); pnlConfiguracion.setBorder(BorderFactory.createTitledBorder("Configuraciones")); { btnIngredientes = new JButton(); pnlConfiguracion.add(btnIngredientes); btnIngredientes.setText("Ingredientes"); btnIngredientes.setBounds(77, 32, 205, 34); btnIngredientes.setActionCommand("Ingredientes"); } { btnProductos = new JButton(); pnlConfiguracion.add(btnProductos); btnProductos.setText("Productos"); btnProductos.setBounds(410, 32, 205, 34); btnProductos.setActionCommand("Productos"); } { btnCategorias = new JButton(); pnlConfiguracion.add(btnCategorias); btnCategorias.setText("Categorias"); btnCategorias.setBounds(245, 77, 205, 34); btnCategorias.setActionCommand("Categorias"); } } { btnGenerarOrdenes = new JButton(); pnlMenuPrincipal.add(btnGenerarOrdenes); btnGenerarOrdenes.setText("Generar Ordenes"); btnGenerarOrdenes.setBounds(21, 193, 710, 58); btnGenerarOrdenes.setActionCommand("Ordenes"); } { btnListados = new JButton(); pnlMenuPrincipal.add(btnListados); btnListados.setText("Listados"); btnListados.setBounds(21, 273, 710, 58); btnListados.setActionCommand("Listados"); } } pack(); this.setSize(765, 388); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addListener(ActionListener actionListener){ this.btnIngredientes.addActionListener(actionListener); this.btnProductos.addActionListener(actionListener); this.btnCategorias.addActionListener(actionListener); this.btnGenerarOrdenes.addActionListener(actionListener); this.btnListados.addActionListener(actionListener); } }
03-09-cuartaentrega
javaBurguer/src/VISTA/MenuPrincipal.java
Java
asf20
4,004
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package CONTROLADOR; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JOptionPane; import MODELO.ModeloIngrediente; import MODELO.ModeloProducto; import VISTA.frmListados; /** * * @author usuario */ public class ControladorListados implements ActionListener { private frmListados frmListado; private ModeloIngrediente modeloIngrediente; private ModeloProducto modeloProducto; private boolean ordenar,ingrediente,producto,mas; public static void main(String[] args) { new ControladorListados(); } public ControladorListados() { frmListado= new frmListados(); frmListado.setVisible(true); modeloIngrediente= new ModeloIngrediente(); modeloProducto = new ModeloProducto(); frmListado.addListener(this); cancelar(); } private void cancelar() { ordenar=false; ingrediente=false; producto=false; mas=false; frmListado.getModeloIngrediente().setRowCount(0); frmListado.getModeloMas().setRowCount(0); frmListado.getModeloProducto().setRowCount(0); } public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand().equals("Generar")){ if(ingrediente){ listaIngrediente(); //cancelar(); } else if(producto){ listarProductos(); //cancelar(); } else if(mas){ listarMas(); //cancelar(); } else frmListado.mostrarMensaje("Debe selecionar el Listado que desea ver"); } else if(ae.getActionCommand().equals("Asc")){ ordenar = true; } else if(ae.getActionCommand().equals("Des")){ ordenar = false; } else if(ae.getActionCommand().equals("Ingredientes")){ ingrediente=true; mas=false; producto=false; } else if(ae.getActionCommand().equals("Productos")){ producto=true; mas=false; ingrediente=false; } else if(ae.getActionCommand().equals("Mas")){ mas =true; ingrediente=false; producto=false; } else if(ae.getActionCommand().equals("Cancelar")){ cancelar(); } } private void listarMas() { frmListado.getModeloIngrediente().setRowCount(0); frmListado.getModeloMas().setRowCount(0); frmListado.getModeloProducto().setRowCount(0); Vector<String []> v = modeloProducto.ingredientesMasUsados(ordenar); frmListado.getProductoOrdenes().setModel(frmListado.getModeloMas()); Vector f= null; for (String [] s : v) { f =new Vector(); for (String string : s) { f.add(string); } frmListado.getModeloMas().addRow(f); } } private void listarProductos() { frmListado.getModeloIngrediente().setRowCount(0); frmListado.getModeloMas().setRowCount(0); frmListado.getModeloProducto().setRowCount(0); Vector<String []> v = modeloProducto.listarVentas(ordenar); frmListado.getProductoOrdenes().setModel(frmListado.getModeloProducto()); Vector f = null; for (String [] s : v) { f =new Vector(); for (String string : s) { f.add(string); } frmListado.getModeloProducto().addRow(f); } } private void listaIngrediente() { frmListado.getModeloIngrediente().setRowCount(0); frmListado.getModeloMas().setRowCount(0); frmListado.getModeloProducto().setRowCount(0); Vector<ModeloIngrediente> v = modeloIngrediente.listar(); frmListado.getProductoOrdenes().setModel(frmListado.getModeloIngrediente()); Vector f; for (ModeloIngrediente m : v) { f =new Vector(); f.add(m.getDescripcion()); f.add(m.getStock()); frmListado.getModeloIngrediente().addRow(f); } } }
03-09-cuartaentrega
javaBurguer/src/CONTROLADOR/ControladorListados.java
Java
asf20
4,078
package CONTROLADOR; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.Vector; import javax.swing.table.TableModel; import MODELO.ModeloCategoria; import MODELO.ModeloIngrediente; import MODELO.ModeloProducto; import VISTA.frmProductos; public class ControladorProductos implements ActionListener{ private facadeControladorProductos facade; private Vector<ModeloIngrediente> ingredientes; private List<ModeloCategoria> categorias; public static void main(String[] args) { new ControladorProductos(); } //Implementacion del Patron Estructural Facade public ControladorProductos() { this.facade = new facadeControladorProductos(); this.facade.setVisible(true); facade.addListener(this); cargarTabla(); cargarCombo(); } private void cargarTabla() { TableModel m = facade.getTblIngredientesTblMODEL(); int i =0; while(i< facade.getTblIngredientesTblROW()){ m.setValueAt("", i, 0); m.setValueAt("", i, 1); i++; } ingredientes = new ModeloIngrediente().listar(); i =0; for (ModeloIngrediente modelo: ingredientes) { m.setValueAt(modelo.getCodigo(), i, 0); m.setValueAt(modelo.getDescripcion(), i, 1); i++; } } private void cargarCombo() { facade.getCmbCategoriaProductoREMOVE(); categorias = new ModeloCategoria().listar(); for (ModeloCategoria modelo: categorias) { facade.getCmbCategoriaProductoADD(modelo.getDescripcion()); } } @Override public void actionPerformed(ActionEvent evt) { if(evt.getActionCommand().equals("Cancelar")){ facade.limpiar(); } else if(evt.getActionCommand().equals("OK")){ if(!facade.getTxtCodigoProductoEMPTY() && !facade.getTxtDescripcionProductoEMPTY() && !facade.getTxtPrecioProductoEMPTY()) if(!facade.contar()) { facade.setCodigo(facade.getTxtCodigoProducto()); facade.setDescripcion(facade.getTxtDescripcionProducto()); facade.setStatus("A"); facade.setPrecio(Double.parseDouble(facade.getTxtPrecioProducto())); if(facade.registrar()){ Vector<String> v = new Vector<String>(); Vector<Double> c = new Vector<Double>(); Vector<String []> vAux = facade.getInfoTabla(); for (String[] strings : vAux) { v.add(buscarIngrediente(strings[1]).getCodigo()); c.add(Double.parseDouble(strings[2])); } facade.registrarIngredientes(v, c); facade.limpiar(); facade.mostrarMensaje("Producto registrado"); } else facade.mostrarMensaje("Codigo registrado"); } else facade.mostrarMensaje("No ha registrado ingredientes"); else facade.mostrarMensaje("Campos vacios"); } else if(evt.getActionCommand().equals("Agregar")){ if(facade.getTblIngredientesSELECTROW()!=-1){ String des = (String)facade.getTblIngredientesGETVALUE(); facade.agregar(buscarIngrediente(des)); } else facade.mostrarMensaje("Selecionar un Ingrediente"); } else if(evt.getActionCommand().equals("Quitar")){ facade.quitar(); } } public ModeloIngrediente buscarIngrediente(String descripicion){ for (int i = 0; i < ingredientes.size(); i++){ if(ingredientes.elementAt(i).getDescripcion().equals(descripicion)) return ingredientes.elementAt(i); }return null; } }
03-09-cuartaentrega
javaBurguer/src/CONTROLADOR/ControladorProductos.java
Java
asf20
3,336
package CONTROLADOR; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import VISTA.*; public class ControladorMenuPrincipal implements ActionListener { private MenuPrincipal frmMenuPrincipal; public ControladorMenuPrincipal() { this.frmMenuPrincipal = new MenuPrincipal(); this.frmMenuPrincipal.addListener(this); this.frmMenuPrincipal.setVisible(true); } public void actionPerformed(ActionEvent evt) { if(evt.getActionCommand().equals("Ingredientes")){ new ControladorIngredientes(); } else if(evt.getActionCommand().equals("Productos")){ new ControladorProductos(); } else if(evt.getActionCommand().equals("Categorias")){ new ControladorCategorias(); } else if(evt.getActionCommand().equals("Ordenes")){ new ControladorOrden(); } else if(evt.getActionCommand().equals("Listados")){ new ControladorListados(); } }//end actionPerformed }
03-09-cuartaentrega
javaBurguer/src/CONTROLADOR/ControladorMenuPrincipal.java
Java
asf20
918
package CONTROLADOR; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.table.TableModel; import MODELO.ModeloCategoria; import VISTA.frmCategorias; public class ControladorCategorias implements ActionListener{ private ModeloCategoria modelo; private frmCategorias frmCategorias; public static void main(String[] args) { new ControladorCategorias(); } public ControladorCategorias() { modelo = new ModeloCategoria(); this.frmCategorias = new frmCategorias(); this.frmCategorias.setVisible(true); this.frmCategorias.addlistener(this); cargarTabla(); } //Implementacion del Patron de Comportamiento Iterator private void cargarTabla() { TableModel m = frmCategorias.gettblCategorias().getModel(); int i =0; Vector<ModeloCategoria> v = modelo.listar(); ListIterator<ModeloCategoria> iteradorCategoria = v.listIterator(); while (iteradorCategoria.hasNext()) { ModeloCategoria categoria = iteradorCategoria.next(); m.setValueAt(categoria.getCodigo(), i, 0); m.setValueAt(categoria.getDescripcion(), i, 1); i++; } } @Override public void actionPerformed(ActionEvent evt) { if(evt.getActionCommand().equals("Nuevo")){ frmCategorias.habilitarNuevo(); } else if(evt.getActionCommand().equals("Modificar")){ if(!frmCategorias.getTxtCodigo().getText().isEmpty() && !frmCategorias.getTxtDescripcion().getText().isEmpty()) { modelo.setCodigo(frmCategorias.getTxtCodigo().getText()); modelo.setDescripcion(frmCategorias.getTxtDescripcion().getText()); modelo.setStatus("A"); if(modelo.actualizar()){ frmCategorias.limpiarCancelar(); cargarTabla(); frmCategorias.mostrarMensaje("Categoria actualizada"); } else frmCategorias.mostrarMensaje("Codigo registrado"); } else frmCategorias.mostrarMensaje("Campos vacios"); } else if(evt.getActionCommand().equals("Buscar")){ if(!frmCategorias.getTxtCodigo().getText().isEmpty()) { modelo.setCodigo(frmCategorias.getTxtCodigo().getText()); if(modelo.consultar()){ frmCategorias.bloquearCodigo(); frmCategorias.getTxtDescripcion().setText(modelo.getDescripcion()); } else frmCategorias.mostrarMensaje("Codigo no registrado"); } else frmCategorias.mostrarMensaje("Campos vacios"); } else if(evt.getActionCommand().equals("OK")){ if(!frmCategorias.getTxtCodigo().getText().isEmpty() && !frmCategorias.getTxtDescripcion().getText().isEmpty()) { modelo.setCodigo(frmCategorias.getTxtCodigo().getText()); modelo.setDescripcion(frmCategorias.getTxtDescripcion().getText()); modelo.setStatus("A"); if(modelo.registar()){ frmCategorias.limpiarCancelar(); cargarTabla(); frmCategorias.mostrarMensaje("Categoria registrada"); } else frmCategorias.mostrarMensaje("Codigo registrado"); } else frmCategorias.mostrarMensaje("Campos vacios"); } else if(evt.getActionCommand().equals("Cancelar")){ frmCategorias.limpiarCancelar(); } } public void okCategorias(){ } public void okModificarCategorias(boolean modificar){ if(modificar == true){ } } public void eliminarCategorias(){ frmCategorias.gettblCategorias().getSelectedRow(); } }
03-09-cuartaentrega
javaBurguer/src/CONTROLADOR/ControladorCategorias.java
Java
asf20
3,485
package CONTROLADOR; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.table.TableModel; import MODELO.ModeloIngrediente; import MODELO.ModeloProducto; import VISTA.frmProductos; public class facadeControladorProductos { ModeloProducto modeloProducto = new ModeloProducto(); frmProductos frmProductos = new frmProductos(); public void setCodigo(String codigo){ modeloProducto.setCodigo(codigo); } public void setDescripcion(String descripcion){ modeloProducto.setDescripcion(descripcion); } public void setStatus(String status){ modeloProducto.setStatus(status); } public void setPrecio(double precio){ modeloProducto.setPrecio(precio); } public boolean registrar(){ return modeloProducto.registar(); } public void registrarIngredientes(Vector<String> v, Vector<Double> c){ modeloProducto.registarIngredientes(v, c); } public void setVisible(boolean estado){ frmProductos.setVisible(estado); } public void addListener(ActionListener controlador){ frmProductos.addListener(controlador); } public TableModel getTblIngredientesTblMODEL(){ return frmProductos.getTblIngredientes().getModel(); } public int getTblIngredientesTblROW(){ return frmProductos.getTblIngredientes().getRowCount(); } public int getTblIngredientesSELECTROW(){ return frmProductos.getTblIngredientes().getSelectedRow(); } public Object getTblIngredientesGETVALUE(){ return frmProductos.getTblIngredientes().getValueAt(getTblIngredientesSELECTROW(), 1); } public void getCmbCategoriaProductoREMOVE(){ frmProductos.getCmbCategoriaProducto().removeAllItems(); } public void getCmbCategoriaProductoADD(String descripcion){ frmProductos.getCmbCategoriaProducto().addItem(descripcion); } public void limpiar(){ frmProductos.limpiar(); } public boolean getTxtCodigoProductoEMPTY(){ return frmProductos.getTxtCodigoProducto().getText().isEmpty(); } public boolean getTxtDescripcionProductoEMPTY(){ return frmProductos.getTxtDescripcionProducto().getText().isEmpty(); } public boolean getTxtPrecioProductoEMPTY(){ return frmProductos.getTxtPrecioProducto().getText().isEmpty(); } public String getTxtCodigoProducto(){ return frmProductos.getTxtCodigoProducto().getText(); } public String getTxtDescripcionProducto(){ return frmProductos.getTxtDescripcionProducto().getText(); } public String getTxtPrecioProducto(){ return frmProductos.getTxtPrecioProducto().getText(); } public boolean contar(){ return frmProductos.contar(); } public Vector<String []> getInfoTabla(){ return frmProductos.getInfoTabla(); } public void mostrarMensaje(String mensaje){ frmProductos.mostrarMensaje(mensaje); } public void agregar(ModeloIngrediente ingrediente){ frmProductos.agregar(ingrediente); } public void quitar(){ frmProductos.quitar(); } }
03-09-cuartaentrega
javaBurguer/src/CONTROLADOR/facadeControladorProductos.java
Java
asf20
2,849
package CONTROLADOR; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.table.TableModel; import MODELO.ModeloCategoria; import MODELO.ModeloIngrediente; import MODELO.ModeloOrden; import MODELO.ModeloProducto; import VISTA.frmOrdenes; public class ControladorOrden implements ActionListener{ private frmOrdenes frmOrdenes; private ModeloOrden modeloOrden; private Vector<ModeloProducto> productos; public static void main(String[] args) { new ControladorOrden(); } public ControladorOrden() { this.frmOrdenes = new frmOrdenes(); this.frmOrdenes.setVisible(true); frmOrdenes.addListener(this); this.modeloOrden = new ModeloOrden(); cargarTabla(); frmOrdenes.limpiar(modeloOrden.contarOrdenes()); } private void cargarTabla() { TableModel m = frmOrdenes.getTblProductoOrdenes().getModel(); int i =0; while(i< frmOrdenes.getTblProductoOrdenes().getRowCount()) { m.setValueAt("", i, 0); m.setValueAt("", i, 1); i++; } productos = new ModeloProducto().listar(); i =0; for (ModeloProducto modelo: productos) { m.setValueAt(modelo.getCodigo(), i, 0); m.setValueAt(modelo.getDescripcion(), i, 1); m.setValueAt(modelo.getPrecio(), i, 2); i++; } } @Override public void actionPerformed(ActionEvent evt) { if(evt.getActionCommand().equals("Cancelar")){ frmOrdenes.limpiar(modeloOrden.contarOrdenes()); } else if(evt.getActionCommand().equals("OK")){ if(!frmOrdenes.getTxtCedula().getText().isEmpty() && !frmOrdenes.getTxtEscribirNombres().getText().isEmpty()) if(!frmOrdenes.contar()) { modeloOrden.setCodigo (frmOrdenes.getLblNro().getText()); modeloOrden.setCedula(frmOrdenes.getTxtCedula().getText()); modeloOrden.setNombre(frmOrdenes.getTxtEscribirNombres().getText()); modeloOrden.setStatus("A"); modeloOrden.setTotal((Double.parseDouble(frmOrdenes.getLblNro().getText()))); if(modeloOrden.registar()){ Vector<String> v = new Vector<String>(); Vector<Double> c = new Vector<Double>(); Vector<String []> vAux = frmOrdenes.getInfoTabla(); for (String[] strings : vAux) { ModeloProducto m = buscarProducto(strings[1]); v.add(m.getCodigo()); c.add(Double.parseDouble(strings[0])); int i =0; while(i<Integer.parseInt(strings[0])){ m.actualizarStockIngredientes(); i++; } } modeloOrden.registarProductos(v, c); frmOrdenes.limpiar(modeloOrden.contarOrdenes()); frmOrdenes.mostrarMensaje("Orden registrado"); } else frmOrdenes.mostrarMensaje("Codigo registrado"); } else frmOrdenes.mostrarMensaje("No ha registrado productos"); else frmOrdenes.mostrarMensaje("Campos vacios"); } else if(evt.getActionCommand().equals("Agregar")){ if(frmOrdenes.getTblProductoOrdenes().getSelectedRow()!=-1){ ModeloProducto m = new ModeloProducto(); m.setCodigo((String)frmOrdenes.getTblProductoOrdenes().getValueAt(frmOrdenes.getTblProductoOrdenes().getSelectedRow(), 0)); if(m.revisarStockIngredientes((frmOrdenes.cantidad()))){ String des = (String)frmOrdenes.getTblProductoOrdenes().getValueAt(frmOrdenes.getTblProductoOrdenes().getSelectedRow(), 1); frmOrdenes.agregar(buscarProducto(des)); } else frmOrdenes.mostrarMensaje("No tenemos stock pra cubrir su orden"); } else frmOrdenes.mostrarMensaje("Selecionar un Ingrediente"); } else if(evt.getActionCommand().equals("Retirar")){ frmOrdenes.quitar(); } } public ModeloProducto buscarProducto(String descripicion){ for (int i = 0; i < productos.size(); i++) if(productos.elementAt(i).getDescripcion().equals(descripicion)) return productos.elementAt(i); return null; } }
03-09-cuartaentrega
javaBurguer/src/CONTROLADOR/ControladorOrden.java
Java
asf20
3,854
package CONTROLADOR; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.table.TableModel; import MODELO.ModeloCategoria; import MODELO.ModeloIngrediente; import VISTA.frmIngredientes; public class ControladorIngredientes implements ActionListener{ private frmIngredientes frmIngredientes; private ModeloIngrediente modeloIngrediente; public static void main(String[] args) { new ControladorIngredientes(); } public ControladorIngredientes() { this.frmIngredientes = new frmIngredientes(); this.frmIngredientes.setVisible(true); frmIngredientes.addListener(this); this.modeloIngrediente = new ModeloIngrediente(); cargarTabla(); } public void cargarTabla() { TableModel m = frmIngredientes.getTblIngredientes().getModel(); int i =0; while(i< frmIngredientes.getTblIngredientes().getRowCount()) { m.setValueAt("", i, 0); m.setValueAt("", i, 1); m.setValueAt("", i, 2); i++; } Vector<ModeloIngrediente> v = modeloIngrediente.listar(); i =0; for (ModeloIngrediente modelo: v) { m.setValueAt(modelo.getCodigo(), i, 0); m.setValueAt(modelo.getDescripcion(), i, 1); m.setValueAt(modelo.getStock(), i, 2); i++; } } public void actionPerformed(ActionEvent evt) { if(evt.getActionCommand().equals("Cancelar")){ frmIngredientes.limpiarNuevo(); frmIngredientes.bloquearNuevo(); frmIngredientes.limpiarEntrada(); frmIngredientes.bloquearEntrada(); cargarTabla(); } else if (evt.getActionCommand().equals("Registrar Nuevo")){ frmIngredientes.habilitarNuevo(); } else if(evt.getActionCommand().equals("Aceptar")){ if(!frmIngredientes.getTxtCodigoIngrediente().getText().isEmpty() && !frmIngredientes.getTxtStockMinimo().getText().isEmpty() && !frmIngredientes.getTxtDescripcionIngredientes().getText().isEmpty()) { modeloIngrediente.setCodigo(frmIngredientes.getTxtCodigoIngrediente().getText()); modeloIngrediente.setDescripcion(frmIngredientes.getTxtDescripcionIngredientes().getText()); modeloIngrediente.setStatus("A"); modeloIngrediente.setStock(Double.parseDouble(frmIngredientes.getTxtStockMinimo().getText())); if(modeloIngrediente.registar()){ frmIngredientes.limpiarNuevo(); cargarTabla(); frmIngredientes.mostrarMensaje("Ingrediente registrado"); } else frmIngredientes.mostrarMensaje("Codigo registrado"); } else frmIngredientes.mostrarMensaje("Campos vacios"); } else if(evt.getActionCommand().equals("Compra")){ if(!frmIngredientes.getTxtCodigoIngrediente().getText().isEmpty()){ modeloIngrediente.setCodigo(frmIngredientes.getTxtCodigoIngrediente().getText()); modeloIngrediente.setStatus("A"); if(modeloIngrediente.consultar()){ frmIngredientes.getTxtStockMinimo().setText(""+modeloIngrediente.getStock()); frmIngredientes.getLblDescripcionEntrada().setText(modeloIngrediente.getDescripcion()); frmIngredientes.habilitarEntrada(); } else frmIngredientes.mostrarMensaje("Codigo registrado"); } else frmIngredientes.mostrarMensaje("Codigo vacio"); } else if(evt.getActionCommand().equals("CancelarE")){ frmIngredientes.limpiarEntrada(); frmIngredientes.bloquearEntrada(); } else if(evt.getActionCommand().equals("Procesar")){ if(!frmIngredientes.getTxtCodigoIngrediente().getText().isEmpty() && !frmIngredientes.getTxtCantidad().getText().isEmpty()) { modeloIngrediente.setCodigo(frmIngredientes.getTxtCodigoIngrediente().getText()); modeloIngrediente.setStatus("A"); modeloIngrediente.setStock(modeloIngrediente.getStock() + Double.parseDouble(frmIngredientes.getTxtCantidad().getText())); if(modeloIngrediente.actualizar()){ frmIngredientes.limpiarEntrada(); frmIngredientes.limpiarNuevo(); frmIngredientes.bloquearEntrada(); cargarTabla(); frmIngredientes.mostrarMensaje("Compra registrada"); } else frmIngredientes.mostrarMensaje("Codigo registrado"); } else frmIngredientes.mostrarMensaje("Campos vacios"); } } }
03-09-cuartaentrega
javaBurguer/src/CONTROLADOR/ControladorIngredientes.java
Java
asf20
4,181
#!/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 pi4j.email.SampleMain $* java -classpath $CP pi4j.email.LedControllerMain $*
12nosanshiro-pi4j-sample
PI4J.email/run
Shell
mit
226
@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%;D:\Cloud\WebSocket.fallback\src\main\javax\lib\json.jar :: :: -Dverbose=true :: java -classpath %CP% pi4j.email.SampleMain %* java -classpath %CP% pi4j.email.SampleMain %* @endlocal
12nosanshiro-pi4j-sample
PI4J.email/run.bat
Batchfile
mit
336
package pi4j.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 OneLed yellowLed = null; private OneLed greenLed = null; private GpioPinDigitalInput button = null; private RaspberryPIEventListener caller = null; public GPIOController(RaspberryPIEventListener listener) { this.caller = listener; this.gpio = GpioFactory.getInstance(); this.yellowLed = new OneLed(this.gpio, RaspiPin.GPIO_01, "yellow"); this.greenLed = new OneLed(this.gpio, RaspiPin.GPIO_04, "green"); this.button = this.gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN); this.button.addListener(new GpioPinListenerDigital() { @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { caller.manageEvent(event); } }); } public void shutdown() { this.gpio.shutdown(); } public void switchYellow(boolean on) { if (on) yellowLed.on(); else yellowLed.off(); } public void switchGreen(boolean on) { if (on) greenLed.on(); else greenLed.off(); } }
12nosanshiro-pi4j-sample
PI4J.email/src/pi4j/gpio/GPIOController.java
Java
mit
1,486
package pi4j.gpio; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; public interface RaspberryPIEventListener { public void manageEvent(GpioPinDigitalStateChangeEvent event); }
12nosanshiro-pi4j-sample
PI4J.email/src/pi4j/gpio/RaspberryPIEventListener.java
Java
mit
194
package pi4j.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 OneLed { private GpioPinDigitalOutput led = null; private String name; public OneLed(GpioController gpio, Pin pin, String name) { this.name = name; led = gpio.provisionDigitalOutputPin(pin, "Led", PinState.LOW); } public void on() { if ("true".equals(System.getProperty("verbose", "false"))) System.out.println(this.name + " is on."); led.high(); } public void off() { if ("true".equals(System.getProperty("verbose", "false"))) System.out.println(this.name + " is off."); led.low(); } }
12nosanshiro-pi4j-sample
PI4J.email/src/pi4j/gpio/OneLed.java
Java
mit
738
package pi4j.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
PI4J.email/src/pi4j/email/EmailReceiver.java
Java
mit
14,382
package pi4j.email; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.json.JSONObject; 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
PI4J.email/src/pi4j/email/SampleMain.java
Java
mit
4,588
package pi4j.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
PI4J.email/src/pi4j/email/EmailSender.java
Java
mit
7,783
package pi4j.email; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.json.JSONObject; import pi4j.gpio.GPIOController; import pi4j.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 pi4j.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 */ 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 pi4j.email.PIControllerMain -verbose -send:google -receive:yahoo -help"); System.exit(0); } } PIControllerMain lmc = new PIControllerMain(); GPIOController piController = new GPIOController(lmc); EmailReceiver receiver = new EmailReceiver(providerReceive); // For Google, pop must be explicitely enabled at the account level try { System.out.println("Waiting for instructions."); 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-green-on".equals(operation)) { System.out.println("Turning green on"); piController.switchGreen(true); } else if ("turn-green-off".equals(operation)) { System.out.println("Turning green off"); piController.switchGreen(false); } else if ("turn-yellow-on".equals(operation)) { System.out.println("Turning yellow on"); piController.switchYellow(true); } else if ("turn-yellow-off".equals(operation)) { System.out.println("Turning yellow off"); piController.switchYellow(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
PI4J.email/src/pi4j/email/PIControllerMain.java
Java
mit
4,482
#!/bin/bash echo 7 segment display CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP sevensegdisplay.samples.AllCharSample
12nosanshiro-pi4j-sample
SevenSegDisplay/run.allchars
Shell
mit
133
#!/bin/bash echo 7 segment display CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP sevensegdisplay.samples.OnOffSample
12nosanshiro-pi4j-sample
SevenSegDisplay/run.onoff
Shell
mit
131
#!/bin/bash echo 7 segment display CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP sevensegdisplay.samples.InteractiveSample
12nosanshiro-pi4j-sample
SevenSegDisplay/run.inter
Shell
mit
137
#!/bin/bash echo 7 segment display CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP sevensegdisplay.samples.ClockSample
12nosanshiro-pi4j-sample
SevenSegDisplay/run.clock
Shell
mit
131
#!/bin/bash echo 7 segment display CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP sevensegdisplay.samples.CPUTempSample
12nosanshiro-pi4j-sample
SevenSegDisplay/run.temp
Shell
mit
133
package sevensegdisplay; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class SevenSegment { private LEDBackPack display = null; private final static int[] digits = { 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, // 0..9 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71 }; // A..F public final static Map<String, Byte> ALL_CHARS = new HashMap<>(); // 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02, /* ! " # $ % & ' */ // 0x80, 0x0f, 0x80, 0x80, 0x04, 0x40, 0x80, 0x80, /* ( ) * + , - . / */ // 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, /* 0 1 2 3 4 5 6 7 */ // 0x7F, 0x6F, 0x80, 0x80, 0x80, 0x48, 0x80, 0x27, /* 8 9 : ; < = > ? */ // 0x80, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71, 0x3d, /* @ A B C D E F G */ // 0x76, 0x30, 0x1E, 0x76, 0x38, 0x15, 0x37, 0x3f, /* H I J K L M N O */ // 0x73, 0x67, 0x31, 0x6d, 0x78, 0x3e, 0x1C, 0x2A, /* P Q R S T U V W */ // 0x76, 0x6e, 0x5b, 0x39, 0x80, 0x0F, 0x80, 0x08, /* X Y Z [ \ ] ^ _ */ // 0x80, 0x5f, 0x7c, 0x58, 0x5e, 0x7b, 0x71, 0x6F, /* ` a b c d e f g */ // 0x74, 0x30, 0x0E, 0x76, 0x06, 0x15, 0x54, 0x5c, /* h i j k l m n o */ // 0x73, 0x67, 0x50, 0x6d, 0x78, 0x1c, 0x1c, 0x2A, /* p q r s t u v w */ // 0x76, 0x6e, 0x5b, 0x39, 0x80, 0x0F, 0x80, 0x08 /* x y z { | } ~ */ static { // FYI, 0x80 is the dot, displayed instead of "undisplayable" characters. ALL_CHARS.put(" ", (byte)0x00); ALL_CHARS.put("!", (byte)0x80); ALL_CHARS.put("\"", (byte)0x80); ALL_CHARS.put("#", (byte)0x80); ALL_CHARS.put("$", (byte)0x80); ALL_CHARS.put("%", (byte)0x80); ALL_CHARS.put("&", (byte)0x80); ALL_CHARS.put("'", (byte)0x02); ALL_CHARS.put("(", (byte)0x39); ALL_CHARS.put(")", (byte)0x0f); ALL_CHARS.put("*", (byte)0x80); ALL_CHARS.put("+", (byte)0x80); ALL_CHARS.put(",", (byte)0x04); ALL_CHARS.put("-", (byte)0x40); ALL_CHARS.put(".", (byte)0x80); ALL_CHARS.put("0", (byte)0x3f); ALL_CHARS.put("1", (byte)0x06); ALL_CHARS.put("2", (byte)0x5b); ALL_CHARS.put("3", (byte)0x4f); ALL_CHARS.put("4", (byte)0x66); ALL_CHARS.put("5", (byte)0x6d); ALL_CHARS.put("6", (byte)0x7d); ALL_CHARS.put("7", (byte)0x07); ALL_CHARS.put("8", (byte)0x7f); ALL_CHARS.put("9", (byte)0x6f); ALL_CHARS.put(":", (byte)0x80); ALL_CHARS.put(";", (byte)0x80); ALL_CHARS.put("<", (byte)0x80); ALL_CHARS.put("=", (byte)0x48); ALL_CHARS.put(">", (byte)0x80); ALL_CHARS.put("?", (byte)0x27); ALL_CHARS.put("@", (byte)0x80); ALL_CHARS.put("A", (byte)0x77); ALL_CHARS.put("B", (byte)0x7c); ALL_CHARS.put("C", (byte)0x39); ALL_CHARS.put("D", (byte)0x5e); ALL_CHARS.put("E", (byte)0x79); ALL_CHARS.put("F", (byte)0x71); ALL_CHARS.put("G", (byte)0x3d); ALL_CHARS.put("H", (byte)0x76); ALL_CHARS.put("I", (byte)0x30); ALL_CHARS.put("J", (byte)0x1e); ALL_CHARS.put("K", (byte)0x76); ALL_CHARS.put("L", (byte)0x38); ALL_CHARS.put("M", (byte)0x15); ALL_CHARS.put("N", (byte)0x37); ALL_CHARS.put("O", (byte)0x3f); ALL_CHARS.put("P", (byte)0x73); ALL_CHARS.put("Q", (byte)0x67); ALL_CHARS.put("R", (byte)0x31); ALL_CHARS.put("S", (byte)0x6d); ALL_CHARS.put("T", (byte)0x78); ALL_CHARS.put("U", (byte)0x3e); ALL_CHARS.put("V", (byte)0x1c); ALL_CHARS.put("W", (byte)0x2a); ALL_CHARS.put("X", (byte)0x76); ALL_CHARS.put("Y", (byte)0x6e); ALL_CHARS.put("Z", (byte)0x5b); ALL_CHARS.put("[", (byte)0x39); ALL_CHARS.put("\\", (byte)0x80); ALL_CHARS.put("]", (byte)0x0f); ALL_CHARS.put("^", (byte)0x80); ALL_CHARS.put("_", (byte)0x08); ALL_CHARS.put("`", (byte)0x80); ALL_CHARS.put("a", (byte)0x5f); ALL_CHARS.put("b", (byte)0x7c); ALL_CHARS.put("c", (byte)0x58); ALL_CHARS.put("d", (byte)0x5e); ALL_CHARS.put("e", (byte)0x7b); ALL_CHARS.put("f", (byte)0x71); ALL_CHARS.put("g", (byte)0x6f); ALL_CHARS.put("h", (byte)0x74); ALL_CHARS.put("i", (byte)0x30); ALL_CHARS.put("j", (byte)0x0e); ALL_CHARS.put("k", (byte)0x76); ALL_CHARS.put("l", (byte)0x06); ALL_CHARS.put("m", (byte)0x15); ALL_CHARS.put("n", (byte)0x54); ALL_CHARS.put("o", (byte)0x5c); ALL_CHARS.put("p", (byte)0x73); ALL_CHARS.put("q", (byte)0x67); ALL_CHARS.put("r", (byte)0x50); ALL_CHARS.put("s", (byte)0x6d); ALL_CHARS.put("t", (byte)0x78); ALL_CHARS.put("u", (byte)0x1c); ALL_CHARS.put("v", (byte)0x1c); ALL_CHARS.put("w", (byte)0x2a); ALL_CHARS.put("x", (byte)0x76); ALL_CHARS.put("y", (byte)0x6e); ALL_CHARS.put("z", (byte)0x5b); ALL_CHARS.put("{", (byte)0x39); ALL_CHARS.put("|", (byte)0x30); ALL_CHARS.put("}", (byte)0x0f); ALL_CHARS.put("~", (byte)0x80); } public SevenSegment() { display = new LEDBackPack(0x70); } public SevenSegment(int addr) { display = new LEDBackPack(addr, false); } public SevenSegment(int addr, boolean b) { display = new LEDBackPack(addr, b); } /* * Sets a digit using the raw 16-bit value */ public void writeDigitRaw(int charNumber, int value) throws IOException { if (charNumber > 7) return; // Set the appropriate digit this.display.setBufferRow(charNumber, value); } public void writeDigitRaw(int charNumber, String value) throws IOException { if (charNumber > 7) return; if (value.trim().length() > 1) return; // Set the appropriate digit int byteValue = ALL_CHARS.get(value); this.display.setBufferRow(charNumber, byteValue); } /* * Sets a single decimal or hexademical value (0..9 and A..F) */ public void writeDigit(int charNumber, int value) throws IOException { writeDigit(charNumber, value, false); } public void writeDigit(int charNumber, int value, boolean dot) throws IOException { if (charNumber > 7) return; if (value > 0xF) return; // Set the appropriate digit this.display.setBufferRow(charNumber, digits[value] | (dot?0x1 << 7:0x0)); } /* * Enables or disables the colon character */ public void setColon() throws IOException { setColon(true); } public void setColon(boolean state) throws IOException { // Warning: This function assumes that the colon is character '2', // which is the case on 4 char displays, but may need to be modified // if another display type is used if (state) this.display.setBufferRow(2, 0xFFFF); else this.display.setBufferRow(2, 0); } public void clear() throws IOException { this.display.clear(); } }
12nosanshiro-pi4j-sample
SevenSegDisplay/src/sevensegdisplay/SevenSegment.java
Java
mit
6,824
package sevensegdisplay.samples; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import sevensegdisplay.SevenSegment; public class AllCharInteractiveSample { 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; } private static SevenSegment segment = new SevenSegment(0x70, true); public static void main(String[] args) throws IOException { boolean go = true; System.out.println("Enter 'quit' to quit..."); while (go) { String input = userInput("Enter a string (up to 4 char) > "); if ("quit".equalsIgnoreCase(input)) go = false; else { String[] row = { " ", " ", " ", " " }; for (int i=0; i<Math.min(input.length(), 4); i++) { String one = input.substring(i, i+1); Byte b = SevenSegment.ALL_CHARS.get(one); if (b != null) row[i] = one; else { System.out.println(one + " not in the list."); row[i] = " "; } } fullDisplay(row); } } System.out.println("Bye"); segment.clear(); } private static void fullDisplay(String[] row) throws IOException { segment.writeDigitRaw(0, row[0]); segment.writeDigitRaw(1, row[1]); segment.writeDigitRaw(3, row[2]); segment.writeDigitRaw(4, row[3]); } }
12nosanshiro-pi4j-sample
SevenSegDisplay/src/sevensegdisplay/samples/AllCharInteractiveSample.java
Java
mit
1,833
package sevensegdisplay.samples; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import sevensegdisplay.SevenSegment; public class InteractiveSample { 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 IOException { SevenSegment segment = new SevenSegment(0x70, true); boolean go = true; System.out.println("Enter 'quit' to quit..."); while (go) { String input = userInput("Number to display [0..F] > "); if ("quit".equalsIgnoreCase(input)) go = false; else { int digit = 0; boolean digitOk = true; try { digit = Integer.parseInt(input, 16); if (digit < 0 ||digit > 0xF) { System.out.println("Invalid digit"); digitOk = false; } } catch (NumberFormatException nfe) { System.out.println(nfe.toString()); digitOk = false; } if (digitOk) { input = userInput("Position [0..7] > "); int pos = 0; boolean posOk = true; try { pos = Integer.parseInt(input); if (pos < 0 || pos > 7) { posOk = false; System.out.println("Invalid position"); } } catch (NumberFormatException nfe) { System.out.println(nfe.toString()); posOk = false; } if (digitOk && posOk) { segment.writeDigit(pos, digit); // Display } } } } System.out.println("Bye"); segment.clear(); } }
12nosanshiro-pi4j-sample
SevenSegDisplay/src/sevensegdisplay/samples/InteractiveSample.java
Java
mit
2,200
package sevensegdisplay.samples; import com.pi4j.system.SystemInfo; import java.io.IOException; import sevensegdisplay.SevenSegment; public class CPUTempSample { private static boolean go = true; private static void setGo(boolean b) { go = b; } public static void main(String[] args) throws IOException, InterruptedException { SevenSegment segment = new SevenSegment(0x70, true); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { setGo(false); } }); while (go) { float cpuTemp = SystemInfo.getCpuTemperature(); // Notice the digit index: 0, 1, 3, 4. 2 is the column ":" int one = (int)cpuTemp / 10; int two = ((int)cpuTemp) % 10; int three = ((int)( 10 * cpuTemp) % 10); int four = ((int)(100 * cpuTemp) % 10); // System.out.println(one + " " + two + "." + three + " " + four); segment.writeDigit(0, one); segment.writeDigit(1, two, true); segment.writeDigit(3, three); segment.writeDigit(4, four); // System.out.println("Temp:" + cpuTemp); try { Thread.sleep(1000L); } catch (InterruptedException ie){} } segment.clear(); } }
12nosanshiro-pi4j-sample
SevenSegDisplay/src/sevensegdisplay/samples/CPUTempSample.java
Java
mit
1,447
package sevensegdisplay.samples; import java.io.IOException; import sevensegdisplay.SevenSegment; public class OnOffSample { public static void main(String[] args) throws IOException { SevenSegment segment = new SevenSegment(0x70, true); for (int i=0; i<5; i++) { // Notice the digit index: 0, 1, 3, 4. 2 is the column ":" segment.writeDigit(0, 8, true); segment.writeDigit(1, 8, true); segment.writeDigit(3, 8, true); segment.writeDigit(4, 8, true); segment.setColon(); try { Thread.sleep(1000L); } catch (InterruptedException ie){} segment.clear(); try { Thread.sleep(1000L); } catch (InterruptedException ie){} } } }
12nosanshiro-pi4j-sample
SevenSegDisplay/src/sevensegdisplay/samples/OnOffSample.java
Java
mit
700
package sevensegdisplay.samples; import java.io.IOException; import sevensegdisplay.SevenSegment; public class CounterSample { public static void main(String[] args) throws IOException { SevenSegment segment = new SevenSegment(0x70, true); long before = System.currentTimeMillis(); for (int i=0; i<10000; i++) { // Notice the digit index: 0, 1, 3, 4. 2 is the column ":" segment.writeDigit(0, (i / 1000)); // 1000th segment.writeDigit(1, (i / 100) % 10); // 100th segment.writeDigit(3, (i / 10) % 10); // 10th segment.writeDigit(4, i % 10); // Ones // try { Thread.sleep(10L); } catch (InterruptedException ie){} } long after = System.currentTimeMillis(); System.out.println("Took " + Long.toString(after - before) + " ms."); try { Thread.sleep(1000L); } catch (InterruptedException ie){} segment.clear(); } }
12nosanshiro-pi4j-sample
SevenSegDisplay/src/sevensegdisplay/samples/CounterSample.java
Java
mit
902
package sevensegdisplay.samples; import java.io.IOError; import java.io.IOException; import java.util.Set; import sevensegdisplay.SevenSegment; public class AllCharSample { private static SevenSegment segment = new SevenSegment(0x70, true); public static void main(String[] args) throws IOException { String[] displayed = { " ", " ", " ", " " }; Set<String> allChars = SevenSegment.ALL_CHARS.keySet(); for (String c : allChars) { System.out.println("--> " + c); displayed = scrollLeft(displayed, c); fullDisplay(displayed); try { Thread.sleep(500L); } catch (InterruptedException ie){} } try { Thread.sleep(3000L); } catch (InterruptedException ie){} for (int i=0; i<4; i++) { fullDisplay(new String[] { "C", "A", "F", "E" }); try { Thread.sleep(1000L); } catch (InterruptedException ie){} fullDisplay(new String[] { "B", "A", "B", "E" }); try { Thread.sleep(1000L); } catch (InterruptedException ie){} } segment.clear(); } private static String[] scrollLeft(String[] row, String c) { String[] newSa = row.clone(); for (int i=0; i<row.length - 1; i++) newSa[i] = row[i+1]; newSa[row.length - 1] = c; return newSa; } private static void fullDisplay(String[] row) throws IOException { segment.writeDigitRaw(0, row[0]); segment.writeDigitRaw(1, row[1]); segment.writeDigitRaw(3, row[2]); segment.writeDigitRaw(4, row[3]); } }
12nosanshiro-pi4j-sample
SevenSegDisplay/src/sevensegdisplay/samples/AllCharSample.java
Java
mit
1,493
package sevensegdisplay.samples; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import sevensegdisplay.SevenSegment; public class ClockSample { public static void main(String[] args) throws IOException { final SevenSegment segment = new SevenSegment(0x70, true); System.out.println("Press CTRL+C to exit"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { segment.clear(); System.out.println("\nBye"); } catch (IOException ioe) { ioe.printStackTrace(); } } }); // Continually update the time on a 4 char, 7-segment display while (true) { Calendar now = GregorianCalendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles")); int hour = now.get(Calendar.HOUR); int minute = now.get(Calendar.MINUTE); int second = now.get(Calendar.SECOND); // Set hours segment.writeDigit(0, (hour / 10)); // Tens segment.writeDigit(1, hour % 10); // Ones // Set minutes segment.writeDigit(3, (minute / 10)); // Tens segment.writeDigit(4, minute % 10); // Ones // Toggle colon segment.setColon(second % 2 != 0); // Toggle colon at 1Hz // Wait one second try { Thread.sleep(1000L); } catch (InterruptedException ie){} } } }
12nosanshiro-pi4j-sample
SevenSegDisplay/src/sevensegdisplay/samples/ClockSample.java
Java
mit
1,992
package sevensegdisplay; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import java.io.IOException; /* * I2C Required for this one */ public class LEDBackPack { /* Prompt> sudo i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: 70 -- -- -- -- -- -- -- */ // This next addresses is returned by "sudo i2cdetect -y 1", see above. public final static int LEDBACKPACK_ADDRESS = 0x70; private boolean verbose = false; private I2CBus bus; private I2CDevice ledBackpack; // Registers public final static int HT16K33_REGISTER_DISPLAY_SETUP = 0x80; public final static int HT16K33_REGISTER_SYSTEM_SETUP = 0x20; public final static int HT16K33_REGISTER_DIMMING = 0xE0; // Blink rate public final static int HT16K33_BLINKRATE_OFF = 0x00; public final static int HT16K33_BLINKRATE_2HZ = 0x01; public final static int HT16K33_BLINKRATE_1HZ = 0x02; public final static int HT16K33_BLINKRATE_HALFHZ = 0x03; // Display buffer (8x16-bits). // 1st digit, 2nd digit, column, 3rd digit, 4th digit, ?, ?, ? Probably for the 8x8 led matrix private int[] buffer = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 }; public LEDBackPack() { this(LEDBACKPACK_ADDRESS); } public LEDBackPack(int address) { this(address, false); } public LEDBackPack(int address, boolean v) { this.verbose = v; try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself ledBackpack = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); //Turn the oscillator on ledBackpack.write(HT16K33_REGISTER_SYSTEM_SETUP | 0x01, (byte)0x00); // Turn blink off this.setBlinkRate(HT16K33_BLINKRATE_OFF); // Set maximum brightness this.setBrightness(15); // Clear the screen this.clear(); } catch (IOException ioe) { ioe.printStackTrace(); } } /* * Sets the brightness level from 0..15 */ private void setBrightness(int brightness) throws IOException { if (brightness > 15) brightness = 15; ledBackpack.write(HT16K33_REGISTER_DIMMING | brightness, (byte)0x00); } /* * Sets the blink rate */ private void setBlinkRate(int blinkRate) throws IOException { if (blinkRate > HT16K33_BLINKRATE_HALFHZ) blinkRate = HT16K33_BLINKRATE_OFF; ledBackpack.write(HT16K33_REGISTER_DISPLAY_SETUP | 0x01 | (blinkRate << 1), (byte)0x00); } /* * Updates a single 16-bit entry in the 8*16-bit buffer */ public void setBufferRow(int row, int value) throws IOException { setBufferRow(row, value, true); } public void setBufferRow(int row, int value, boolean update) throws IOException { if (row > 7) return; // Prevent buffer overflow this.buffer[row] = value; // value # & 0xFFFF if (update) this.writeDisplay(); // Update the display } /* * Returns a copy of the raw buffer contents */ public int[] getBuffer() { int[] bufferCopy = buffer.clone(); return bufferCopy; } /* * Updates the display memory */ private void writeDisplay() throws IOException { byte[] bytes = new byte[2 * buffer.length]; for (int i=0; i<buffer.length; i++) { int item = buffer[i]; bytes[2 * i] = (byte)(item & 0xFF); bytes[(2 * i) + 1] = (byte)((item >> 8) & 0xFF); } ledBackpack.write(0x00, bytes, 0, bytes.length); } /* * Clears the display memory */ public void clear() throws IOException { clear(true); } public void clear(boolean update) throws IOException { this.buffer = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }; // Reset. Bam! if (update) this.writeDisplay(); } }
12nosanshiro-pi4j-sample
SevenSegDisplay/src/sevensegdisplay/LEDBackPack.java
Java
mit
4,481
#!/bin/bash echo 7 segment display CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP sevensegdisplay.samples.CounterSample
12nosanshiro-pi4j-sample
SevenSegDisplay/run.counter
Shell
mit
133
#!/bin/bash echo 7 segment display CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP sevensegdisplay.samples.AllCharInteractiveSample
12nosanshiro-pi4j-sample
SevenSegDisplay/run.allchars.inter
Shell
mit
144
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # sudo java -cp $CP raspisamples.PWM3ColorLed
12nosanshiro-pi4j-sample
RasPISamples/pwm3cled
Shell
mit
204
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # sudo $JAVA_HOME/bin/java -cp $CP raspisamples.RealPWMLed
12nosanshiro-pi4j-sample
RasPISamples/pwmled.02
Shell
mit
217
#!/bin/bash PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:../ADC/classes #CP=$CP:../SevenSegDisplay/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # sudo java -cp $CP raspisamples.servo.StandardServo
12nosanshiro-pi4j-sample
RasPISamples/servo.cal
Shell
mit
266
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes # CP=$CP:../SevenSegDisplay/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # CP=$CP:./lib/json.jar # sudo java -cp $CP raspisamples.log.net.WeatherDataFileLogging $*
12nosanshiro-pi4j-sample
RasPISamples/weather.file.logger
Shell
mit
285
#!/bin/bash PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:../ADC/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # sudo java -cp $CP -Dverbose=true raspisamples.PanTilt
12nosanshiro-pi4j-sample
RasPISamples/pantilt
Shell
mit
234
<!DOCTYPE HTML> <html> <head> <link rel="stylesheet" href="css/stylesheet.css" type="text/css"/> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <div id="container"></div> <script src="http://www.html5canvastutorials.com/libraries/three.min.js"></script> <script src="lm.threejs.client.js"></script> <script type="text/javascript"> var response = {}; var statusFld; window.onload = function() { statusFld = document.getElementById("status"); }; </script> <script defer="defer"> var angularSpeedAroundZ = 0; // yaw var angularSpeedAroundY = 0; // roll var angularSpeedAroundX = 0; // pitch // revolutions per second var angularSpeed = 0.2; var lastTime = 0; // this function is executed on each animation frame function animate(){ // update var time = (new Date()).getTime(); var timeDiff = time - lastTime; var angleChangeX = angularSpeedAroundX * timeDiff * 2 * Math.PI / 1000; var angleChangeY = angularSpeedAroundY * timeDiff * 2 * Math.PI / 1000; var angleChangeZ = angularSpeedAroundZY * timeDiff * 2 * Math.PI / 1000; cube.rotation.x += angleChangeX; cube.rotation.y += angleChangeY; cube.rotation.z += angleChangeZ; lastTime = time; // render renderer.render(scene, camera); // request new frame requestAnimationFrame(function(){ animate(); }); } // renderer var renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // camera var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000); camera.position.z = 500; // scene var scene = new THREE.Scene(); // cube var cube = new THREE.Mesh(new THREE.CubeGeometry(200, 200, 200), new THREE.MeshNormalMaterial()); cube.overdraw = true; scene.add(cube); // start animation animate(); </script> <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> </body> </html>
12nosanshiro-pi4j-sample
RasPISamples/node/cube.three.js.html
HTML
mit
2,436
/** * An object of type SimpleRotator can be used to implement a trackball-like mouse rotation * of a WebGL scene about the origin. Only the first parameter to the constructor is required. * When an object is created, mouse event handlers are set up on the canvas to respond to rotation. * The class defines the following methods for an object rotator of type SimpleRotator: * rotator.setView(viewDirectionVector, viewUpVector, viewDistance) set up the view, where the * parameters are optional and are used in the same way as the corresponding parameters in the constructor; * rotator.setViewDistance(viewDistance) sets the distance of the viewer from the origin without * changing the direction of view; * rotator.getViewDistance() returns the viewDistance; * rotator.getViewMatrix() returns a Float32Array representing the viewing transformation matrix * for the current view, suitable for use with gl.uniformMatrix4fv or for further transformation with * the glmatrix library mat4 class; * rotator.getViewMatrixArray() returns the view transformation matrix as a regular JavaScript * array, but still represents as a 1D array of 16 elements, in column-major order. * * @param canvas the HTML canvas element used for WebGL drawing. The user will rotate the * scene by dragging the mouse on this canvas. This parameter is required. * @param callback if present must be a function, which is called whenever the rotation changes. * It is typically the function that draws the scene * @param viewDirectionVector if present must be an array of three numbers, not all zero. The * view is from the direction of this vector towards the origin (0,0,0). If not present, * the value [0,0,10] is used. * @param viewUpVector if present must be an array of three numbers. Gives a vector that will * be seen as pointing upwards in the view. If not present, the value is [0,1,0]. * @param viewDistance if present must be a positive number. Gives the distance of the viewer * from the origin. If not present, the length of viewDirectionVector is used. */ function SimpleRotator(canvas, callback, viewDirectionVector, viewUpVector, viewDistance) { var unitx = new Array(3); var unity = new Array(3); var unitz = new Array(3); var viewZ; this.setView = function( viewDirectionVector, viewUpVector, viewDistance ) { var viewpoint = viewDirectionVector || [0,0,10]; var viewup = viewUpVector || [0,1,0]; if (viewDistance && typeof viewDistance == "number") viewZ = viewDistance; else viewZ = length(viewpoint); copy(unitz,viewpoint); normalize(unitz, unitz); copy(unity,unitz); scale(unity, unity, dot(unitz,viewup)); subtract(unity,viewup,unity); normalize(unity,unity); cross(unitx,unity,unitz); } this.getViewMatrix = function (){ return new Float32Array( this.getViewMatrixArray() ); } this.getViewMatrixArray = function() { return [ unitx[0], unity[0], unitz[0], 0, unitx[1], unity[1], unitz[1], 0, unitx[2], unity[2], unitz[2], 0, 0, 0, -viewZ, 1 ]; } this.getViewDistance = function() { return viewZ; } this.setViewDistance = function(viewDistance) { viewZ = viewDistance; } function applyTransvection(e1, e2) { // rotate vector e1 onto e2 function reflectInAxis(axis, source, destination) { var s = 2 * (axis[0] * source[0] + axis[1] * source[1] + axis[2] * source[2]); destination[0] = s*axis[0] - source[0]; destination[1] = s*axis[1] - source[1]; destination[2] = s*axis[2] - source[2]; } normalize(e1,e1); normalize(e2,e2); var e = [0,0,0]; add(e,e1,e2); normalize(e,e); var temp = [0,0,0]; reflectInAxis(e,unitz,temp); reflectInAxis(e1,temp,unitz); reflectInAxis(e,unitx,temp); reflectInAxis(e1,temp,unitx); reflectInAxis(e,unity,temp); reflectInAxis(e1,temp,unity); } var centerX = canvas.width/2; var centerY = canvas.height/2; var radius = Math.min(centerX,centerY); var radius2 = radius*radius; var prevx,prevy; var prevRay = [0,0,0]; var dragging = false; function doMouseDown(evt) { if (dragging) return; dragging = true; document.addEventListener("mousemove", doMouseDrag, false); document.addEventListener("mouseup", doMouseUp, false); var box = canvas.getBoundingClientRect(); prevx = window.pageXOffset + evt.clientX - box.left; prevy = window.pageYOffset + evt.clientY - box.top; } function doMouseDrag(evt) { if (!dragging) return; var box = canvas.getBoundingClientRect(); console.log(">>> DEBUG >>> Mouse X:" + evt.clientX + ", Y:" + evt.clientY); var x = window.pageXOffset + evt.clientX - box.left; var y = window.pageYOffset + evt.clientY - box.top; var ray1 = toRay(prevx,prevy); var ray2 = toRay(x,y); applyTransvection(ray1,ray2); prevx = x; prevy = y; if (callback) { callback(); } } function doMouseUp(evt) { if (dragging) { document.removeEventListener("mousemove", doMouseDrag, false); document.removeEventListener("mouseup", doMouseUp, false); dragging = false; } } function toRay(x,y) { var dx = x - centerX; var dy = centerY - y; var vx = dx * unitx[0] + dy * unity[0]; // The mouse point as a vector in the image plane. var vy = dx * unitx[1] + dy * unity[1]; var vz = dx * unitx[2] + dy * unity[2]; var dist2 = vx*vx + vy*vy + vz*vz; if (dist2 > radius2) { return [vx,vy,vz]; } else { var z = Math.sqrt(radius2 - dist2); return [vx+z*unitz[0], vy+z*unitz[1], vz+z*unitz[2]]; } } function dot(v,w) { return v[0]*w[0] + v[1]*w[1] + v[2]*w[2]; } function length(v) { return Math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); } function normalize(v,w) { var d = length(w); v[0] = w[0]/d; v[1] = w[1]/d; v[2] = w[2]/d; } function copy(v,w) { v[0] = w[0]; v[1] = w[1]; v[2] = w[2]; } function add(sum,v,w) { sum[0] = v[0] + w[0]; sum[1] = v[1] + w[1]; sum[2] = v[2] + w[2]; } function subtract(dif,v,w) { dif[0] = v[0] - w[0]; dif[1] = v[1] - w[1]; dif[2] = v[2] - w[2]; } function scale(ans,v,num) { ans[0] = v[0] * num; ans[1] = v[1] * num; ans[2] = v[2] * num; } function cross(c,v,w) { var x = v[1]*w[2] - v[2]*w[1]; var y = v[2]*w[0] - v[0]*w[2]; var z = v[0]*w[1] - v[1]*w[0]; c[0] = x; c[1] = y; c[2] = z; } this.setView(viewDirectionVector, viewUpVector, viewDistance); canvas.addEventListener("mousedown", doMouseDown, false); }
12nosanshiro-pi4j-sample
RasPISamples/node/webgl/simple-rotator.js
JavaScript
mit
6,884
/* * @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
RasPISamples/node/widgets/AnalogDisplay.js
JavaScript
mit
12,851
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Leap Motion / 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 displayRoll; var displayPitch; var displayYaw; var statusFld; window.onload = function() { displayRoll = new AnalogDisplay('rollCanvas', 100, 90, 30, 1, true, 40, -90); displayPitch = new AnalogDisplay('pitchCanvas', 100, 90, 30, 1, true, 40, -90); displayYaw = new AnalogDisplay('yawCanvas', 100, 90, 30, 1, true, 40, -90); statusFld = document.getElementById("status"); displayRoll.setValue(0); displayPitch.setValue(0); displayYaw.setValue(0); }; </script> </head> <body> <div> <table style="margin: auto;"> <tr> <td valign="top"><h2>Leap Motion on WebSocket</h2></td> </tr> <tr> <td align="left" colspan="3"> <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" colspan="3"><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="rollCanvas" width="240" height="220" title="Roll value"></canvas> </td> <td align="center" valign="top"> <canvas id="pitchCanvas" width="240" height="220" title="Pitch value"></canvas> </td> <td align="center" valign="top"> <canvas id="yawCanvas" width="240" height="220" title="Yaw value"></canvas> </td> </tr> <tr> <td align="center" valign="top">Roll</td> <td align="center" valign="top">Pitch</td> <td align="center" valign="top">Yaw</td> </tr> </table> </div> <hr> <script src="./lm.client.js"></script> </body> </html>
12nosanshiro-pi4j-sample
RasPISamples/node/leapmotion.html
HTML
mit
2,326
<!DOCTYPE html> <meta charset="UTF-8"> <html> <head> <title>WebGL Cube with Rotation</title> <link rel="stylesheet" href="css/stylesheet.css" type="text/css"/> <script type="x-shader/x-vertex" id="vshader"> attribute vec3 coords; uniform mat4 modelview; uniform mat4 projection; uniform bool lit; uniform vec3 normal; uniform mat3 normalMatrix; uniform vec4 color; varying vec4 vColor; void main() { vec4 coords = vec4(coords,1.0); vec4 transformedVertex = modelview * coords; gl_Position = projection * transformedVertex; if (lit) { vec3 unitNormal = normalize(normalMatrix*normal); float multiplier = abs(unitNormal.z); vColor = vec4( multiplier*color.r, multiplier*color.g, multiplier*color.b, color.a ); } else { vColor = color; } } </script> <script type="x-shader/x-fragment" id="fshader"> precision mediump float; varying vec4 vColor; void main() { gl_FragColor = vColor; } </script> <script type="text/javascript" src="webgl/gl-matrix-min.js"></script> <script type="text/javascript" src="webgl/simple-rotator.js"></script> <script type="text/javascript"> "use strict"; var gl; // The webgl context. var aCoords; // Location of the coords attribute variable in the shader program. var aCoordsBuffer; // Buffer to hold coords. var uColor; // Location of the color uniform variable in the shader program. var uProjection; // Location of the projection uniform matrix in the shader program. var uModelview; // Location of the modelview unifirm matrix in the shader program. var uNormal; // Location of the normal uniform in the shader program. var uLit; // Location of the lit uniform in the shader program. var uNormalMatrix; // Location of the normalMatrix uniform matrix in the shader program. var projection = mat4.create(); // projection matrix var modelview = mat4.create(); // modelview matrix var normalMatrix = mat3.create(); // matrix, derived from modelview matrix, for transforming normal vectors var rotator; // A SimpleRotator object to enable rotation by mouse dragging. /* Draws a WebGL primitive. The first parameter must be one of the constants * that specifiy primitives: gl.POINTS, gl.LINES, gl.LINE_LOOP, gl.LINE_STRIP, * gl.TRIANGLES, gl.TRIANGLE_STRIP, gl.TRIANGLE_FAN. The second parameter must * be an array of 4 numbers in the range 0.0 to 1.0, giving the RGBA color of * the color of the primitive. The third parameter must be an array of numbers. * The length of the array must be amultiple of 3. Each triple of numbers provides * xyz-coords for one vertex for the primitive. This assumes that uColor is the * location of a color uniform in the shader program, aCoords is the location of * the coords attribute, and aCoordsBuffer is a VBO for the coords attribute. */ function drawPrimitive( primitiveType, color, vertices ) { gl.enableVertexAttribArray(aCoords); gl.bindBuffer(gl.ARRAY_BUFFER,aCoordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STREAM_DRAW); gl.uniform4fv(uColor, color); gl.vertexAttribPointer(aCoords, 3, gl.FLOAT, false, 0, 0); gl.drawArrays(primitiveType, 0, vertices.length/3); } /* Draws a colored cube, along with a set of coordinate axes. * (Note that the use of the above drawPrimitive function is not an efficient * way to draw with WebGL. Here, the geometry is so simple that it doesn't matter.) */ function draw() { gl.clearColor(0,0,0,1); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); if (document.getElementById("persproj").checked) { mat4.perspective(projection, Math.PI/4, 1, 2, 10); } else { mat4.ortho(projection,-2.5, 2.5, -2.5, 2.5, 2, 10); } gl.uniformMatrix4fv(uProjection, false, projection ); var modelview = rotator.getViewMatrix(); gl.uniformMatrix4fv(uModelview, false, modelview ); mat3.normalFromMat4(normalMatrix, modelview); gl.uniformMatrix3fv(uNormalMatrix, false, normalMatrix); gl.uniform1i( uLit, 1 ); // Turn on lighting calculations for the cube. gl.uniform3f( uNormal, 0, 0, 1 ); drawPrimitive( gl.TRIANGLE_FAN, [1,0,0,1], [ -1,-1,1, 1,-1,1, 1,1,1, -1,1,1 ]); gl.uniform3f( uNormal, 0, 0, -1 ); drawPrimitive( gl.TRIANGLE_FAN, [0,1,0,1], [ -1,-1,-1, -1,1,-1, 1,1,-1, 1,-1,-1 ]); gl.uniform3f( uNormal, 0, 1, 0 ); drawPrimitive( gl.TRIANGLE_FAN, [0,0,1,1], [ -1,1,-1, -1,1,1, 1,1,1, 1,1,-1 ]); gl.uniform3f( uNormal, 0, -1, 0 ); drawPrimitive( gl.TRIANGLE_FAN, [1,1,0,1], [ -1,-1,-1, 1,-1,-1, 1,-1,1, -1,-1,1 ]); gl.uniform3f( uNormal, 1, 0, 0 ); drawPrimitive( gl.TRIANGLE_FAN, [1,0,1,1], [ 1,-1,-1, 1,1,-1, 1,1,1, 1,-1,1 ]); gl.uniform3f( uNormal, -1, 0, 0 ); drawPrimitive( gl.TRIANGLE_FAN, [0,1,1,1], [ -1,-1,-1, -1,-1,1, -1,1,1, -1,1,-1 ]); gl.uniform1i( uLit, 0 ); // The lines representing the coordinate axes are not lit. gl.lineWidth(4); drawPrimitive( gl.LINES, [1,0,0,1], [ -2,0,0, 2,0,0] ); drawPrimitive( gl.LINES, [0,1,0,1], [ 0,-2,0, 0,2,0] ); drawPrimitive( gl.LINES, [0,0,1,1], [ 0,0,-2, 0,0,2] ); gl.lineWidth(1); } /* Creates a program for use in the WebGL context gl, and returns the * identifier for that program. If an error occurs while compiling or * linking the program, an exception of type String is thrown. The error * string contains the compilation or linking error. If no error occurs, * the program identifier is the return value of the function. */ function createProgram(gl, vertexShaderSource, fragmentShaderSource) { var vsh = gl.createShader( gl.VERTEX_SHADER ); gl.shaderSource(vsh,vertexShaderSource); gl.compileShader(vsh); if ( ! gl.getShaderParameter(vsh, gl.COMPILE_STATUS) ) { throw "Error in vertex shader: " + gl.getShaderInfoLog(vsh); } var fsh = gl.createShader( gl.FRAGMENT_SHADER ); gl.shaderSource(fsh, fragmentShaderSource); gl.compileShader(fsh); if ( ! gl.getShaderParameter(fsh, gl.COMPILE_STATUS) ) { throw "Error in fragment shader: " + gl.getShaderInfoLog(fsh); } var prog = gl.createProgram(); gl.attachShader(prog,vsh); gl.attachShader(prog, fsh); gl.linkProgram(prog); if ( ! gl.getProgramParameter( prog, gl.LINK_STATUS) ) { throw "Link error in program: " + gl.getProgramInfoLog(prog); } return prog; } /* Gets the text content of an HTML element. This is used * to get the shader source from the script elements that contain * it. The parameter should be the id of the script element. */ function getTextContent( elementID ) { var element = document.getElementById(elementID); var fsource = ""; var node = element.firstChild; var str = ""; while (node) { if (node.nodeType == 3) // this is a text node str += node.textContent; node = node.nextSibling; } return str; } /** * Initializes the WebGL program including the relevant global variables * and the WebGL state. Creates a SimpleView3D object for viewing the * cube and installs a mouse handler that lets the user rotate the cube. */ function init() { try { var canvas = document.getElementById("glcanvas"); gl = canvas.getContext("webgl"); if ( ! gl ) { gl = canvas.getContext("experimental-webgl"); } if ( ! gl ) { throw "Could not create WebGL context."; } var vertexShaderSource = getTextContent("vshader"); var fragmentShaderSource = getTextContent("fshader"); var prog = createProgram(gl,vertexShaderSource,fragmentShaderSource); gl.useProgram(prog); aCoords = gl.getAttribLocation(prog, "coords"); uModelview = gl.getUniformLocation(prog, "modelview"); uProjection = gl.getUniformLocation(prog, "projection"); uColor = gl.getUniformLocation(prog, "color"); uLit = gl.getUniformLocation(prog, "lit"); uNormal = gl.getUniformLocation(prog, "normal"); uNormalMatrix = gl.getUniformLocation(prog, "normalMatrix"); aCoordsBuffer = gl.createBuffer(); gl.enable(gl.DEPTH_TEST); gl.enable(gl.CULL_FACE); // no need to draw back faces document.getElementById("persproj").checked = true; rotator = new SimpleRotator(canvas,draw); rotator.setView( [2,2,5], [0,1,0], 6 ); } catch (e) { document.getElementById("message").innerHTML = "Could not initialize WebGL: " + e; return; } draw(); } </script> </head> <body onload="init()" style="background-color:#DDD"> <h2>A Cube With Rotator</h2> <p id="message">Drag the mouse on the canvas to rotate the view.</p> <p> <input type="radio" name="projectionType" id="persproj" value="perspective" onchange="draw()"> <label for="persproj">Perspective projection</label> <input type="radio" name="projectionType" id="orthproj" value="orthogonal" onchange="draw()" style="margin-left:1cm"> <label for="orthproj">Orthogonal projection</label> <button onclick="rotator.setView( [2,2,5], [0,1,0], 6 ); draw()" style="margin-left:1cm">Reset View</button> </p> <noscript> <hr> <h3>This page requires Javascript and a web browser that supports WebGL</h3> <hr> </noscript> <div style="text-align: center;"> <canvas width="600" height="600" id="glcanvas" style="background-color:red"></canvas> </div> </body> </html>
12nosanshiro-pi4j-sample
RasPISamples/node/leapmotion.webgl.html
HTML
mit
10,066
body { color : blue; font-weight: normal; font-size: 10pt; font-family: Verdana, Helvetica, Geneva, Swiss, SunSans-Regular; background-position: top left; background-repeat: repeat } h1 { color: silver; font-style: italic; font-size: 26pt; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular; padding-left: 5pt } h2 { color: silver; font-size: 12pt; font-family: Verdana, Arial, Helvetica, Geneva, Swiss, SunSans-Regular } h3 { font-style: italic; font-weight: bold; font-size: 11pt; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular; } h4 { font-style: italic; font-weight: bold; font-size: 10pt; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular; } h5 { font-style: normal; font-weight: bold; font-size: 10pt; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular; } h6 { font-style: italic; font-weight: normal; font-size: 10pt; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular; } li { font-size: 10pt; font-weight: normal; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular } dt { font-size: 10pt; font-weight: bold; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular } dd { font-size: 10pt; font-weight: normal; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular } p { font-size: 10pt; font-weight: normal; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular } td { font-size: 10pt; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular } small { font-size: 8pt; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular } blockquote { font-style: italic; font-size: 10pt; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular } em { font-size: 10pt; font-style: italic; font-weight: bold; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular } pre { font-size: 9pt; font-family: Courier New, Helvetica, Geneva, Swiss, SunSans-Regular; background-color:lightGray; } address { font-size: 8pt; font-family: Arial, Helvetica, Geneva, Swiss, SunSans-Regular } .red { color:red; } a:link { color : #0000A0} a:active { color: #8080FF} a:visited { color : #8080FF}
12nosanshiro-pi4j-sample
RasPISamples/node/css/stylesheet.css
CSS
mit
2,299
/** * 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-leap-motion'; // 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); try { var mess = JSON.parse(message.utf8Data); console.log('P:' + mess.pitch + ', R:' + mess.roll + ', Y:' + mess.yaw); } catch (err) { console.log(">>> ERR >>> " + err + ' in ' + message.utf8Data); } //text: htmlEntities(message.utf8Data) var obj = { time: (new Date()).getTime(), text: 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
RasPISamples/node/server.js
JavaScript
mit
6,900
// App specific code var nbMessReceived = 0; var init = function() { ws.onopen = function() { try { var text; try { text = 'Message:'; } catch (err) { text = '<small>Connected</small>'; } promptFld.innerHTML = text; if (nbMessReceived === 0) statusFld.innerHTML = ""; statusFld.innerHTML += ((nbMessReceived === 0?"":"<br>") + "<small>" + (new Date()).format("d-M-Y H:i:s._ Z") + "</small>:<font color='blue'>" + ' Connection opened.' + "</font>"); statusFld.scrollTop = statusFld.scrollHeight; nbMessReceived++; } catch (err) {} }; ws.onerror = function(error) { if (nbMessReceived === 0) statusFld.innerHTML = ""; statusFld.innerHTML += ((nbMessReceived === 0?"":"<br>") + "<small>" + (new Date()).format("d-M-Y H:i:s._ Z") + "</small>:<font color='red'>" + error.err + "</font>"); statusFld.scrollTop = statusFld.scrollHeight; nbMessReceived++; }; ws.onmessage = function(message) // message/event { var json = {}; if (typeof(message.data) === 'string') { try { json = JSON.parse(message.data); } catch (e) { console.log(e); console.log('This doesn\'t look like a valid JSON: ' + message.data); } } //console.log("Split: type=" + json.type + ", data=" + json.data); if (json.type !== undefined && json.type === 'message' && typeof(json.data.text) === 'string') // it's a single message, text { var dt = new Date(); /** * Add message to the chat window */ var existing = contentFld.innerHTML; // Content already there var toDisplay = ""; try { toDisplay = json.data.text; } catch (err) {} contentFld.innerHTML = existing + ('At ' + + (dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':' + (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) + ': ' + toDisplay + '<br>'); contentFld.scrollTop = contentFld.scrollHeight; } else // Unexpected { var payload = {}; } }; ws.onclose = function() { if (nbMessReceived === 0) statusFld.innerHTML = ""; statusFld.innerHTML += ((nbMessReceived === 0?"":"<br>") + "<small>" + (new Date()).format("d-M-Y H:i:s._ Z") + "</small>:<font color='blue'>" + ' Connection closed' + "</font>"); promptFld.innerHTML = 'Connection closed'; }; }; var send = function(mess) { ws.send(mess); }; var getClass = function(obj) { if (obj && typeof obj === 'object' && Object.prototype.toString.call(obj) !== '[object Array]' && obj.constructor) { var arr = obj.constructor.toString().match(/function\s*(\w+)/); if (arr && arr.length === 2) { return arr[1]; } } return false; }; // Date formatting // Provide month names Date.prototype.getMonthName = function() { var month_names = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; return month_names[this.getMonth()]; }; // Provide month abbreviation Date.prototype.getMonthAbbr = function() { var month_abbrs = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; return month_abbrs[this.getMonth()]; }; // Provide full day of week name Date.prototype.getDayFull = function() { var days_full = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; return days_full[this.getDay()]; }; // Provide full day of week name Date.prototype.getDayAbbr = function() { var days_abbr = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat' ]; return days_abbr[this.getDay()]; }; // Provide the day of year 1-365 Date.prototype.getDayOfYear = function() { var onejan = new Date(this.getFullYear(),0,1); return Math.ceil((this - onejan) / 86400000); }; // Provide the day suffix (st,nd,rd,th) Date.prototype.getDaySuffix = function() { var d = this.getDate(); var sfx = ["th", "st", "nd", "rd"]; var val = d % 100; return (sfx[(val-20)%10] || sfx[val] || sfx[0]); }; // Provide Week of Year Date.prototype.getWeekOfYear = function() { var onejan = new Date(this.getFullYear(),0,1); return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7); }; // Provide if it is a leap year or not Date.prototype.isLeapYear = function() { var yr = this.getFullYear(); if ((parseInt(yr) % 4) === 0) { if (parseInt(yr) % 100 === 0) { if (parseInt(yr) % 400 !== 0) return false; if (parseInt(yr) % 400 === 0) return true; } if (parseInt(yr) % 100 !== 0) return true; } if ((parseInt(yr) % 4) !== 0) return false; }; // Provide Number of Days in a given month Date.prototype.getMonthDayCount = function() { var month_day_counts = [ 31, this.isLeapYear() ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]; return month_day_counts[this.getMonth()]; }; // format provided date into this.format format Date.prototype.format = function(dateFormat) { // break apart format string into array of characters dateFormat = dateFormat.split(""); var date = this.getDate(), month = this.getMonth(), hours = this.getHours(), minutes = this.getMinutes(), seconds = this.getSeconds(), milli = this.getTime() % 1000, tzOffset = - (this.getTimezoneOffset() / 60); var lpad = function(s, w, len) { var str = s; while (str.length < len) str = w + str; return str; }; // get all date properties ( based on PHP date object functionality ) var date_props = { d: date < 10 ? '0'+date : date, D: this.getDayAbbr(), j: this.getDate(), l: this.getDayFull(), S: this.getDaySuffix(), w: this.getDay(), z: this.getDayOfYear(), W: this.getWeekOfYear(), F: this.getMonthName(), m: month < 10 ? '0'+(month+1) : month+1, M: this.getMonthAbbr(), n: month+1, t: this.getMonthDayCount(), L: this.isLeapYear() ? '1' : '0', Y: this.getFullYear(), y: this.getFullYear()+''.substring(2,4), a: hours > 12 ? 'pm' : 'am', A: hours > 12 ? 'PM' : 'AM', g: hours % 12 > 0 ? hours % 12 : 12, G: hours > 0 ? hours : "12", h: hours % 12 > 0 ? hours % 12 : 12, H: hours < 10 ? '0' + hours : hours, i: minutes < 10 ? '0' + minutes : minutes, s: seconds < 10 ? '0' + seconds : seconds, Z: "UTC" + (tzOffset > 0 ?"+":"") + tzOffset, _: lpad(milli, '0', 3) }; // loop through format array of characters and add matching data else add the format character (:,/, etc.) var date_string = ""; for (var i=0; i<dateFormat.length; i++) { var f = dateFormat[i]; if (f.match(/[a-zA-Z|_]/g)) date_string += date_props[f] ? date_props[f] : ''; else date_string += f; } return date_string; };
12nosanshiro-pi4j-sample
RasPISamples/node/chat.client.js
JavaScript
mit
8,263
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>WebSocket 101</title> <link rel="stylesheet" href="css/stylesheet.css" type="text/css"/> <script type="text/javascript"> var URI_SUFFIX = "/websocket-101/ws-101-app"; var ws; var connectionStatus = "Connecting..."; var calledBy = document.location.toString(); var machine, port, secured; var regExp = new RegExp("(http|ws)(.?):[/]{2}([^/|^:]*):?(\\d*)/(.*)"); var matches = regExp.exec(calledBy); //scheme = matches[1]; secured = matches[2]; machine = matches[3]; port = matches[4]; //query = matches[5]; var reset = function() // Reset the screen { contentFld.innerHTML = ""; }; var resetStatus = function() { statusFld.innerHTML = ""; }; </script> <script type="text/javascript" src="chat.client.js"></script> <!-- Application definition --> <script type="text/javascript"> /* * Init the App here */ var contentFld, inputFld, statusFld, promptFld; window.onload = function() { contentFld = document.getElementById('content'); inputFld = document.getElementById('input'); statusFld = document.getElementById('status'); promptFld = document.getElementById('prompt'); try { var wsURI = "ws" + secured + "://" + machine + ":" + port + URI_SUFFIX; var config = setConfig(); if (config === undefined) ws = new WebSocket(wsURI); else ws = new WebSocket(wsURI, config); } catch (err) { var mess = 'WebSocket creation error:'; if (err.message !== undefined) mess += err.message; else mess += JSON.stringify(err); connectionStatus = "<font color='red'>Enable to connect.</font>"; if (statusFld !== undefined) statusFld.innerHTML = mess; else alert(mess); } init(); // in app.js promptFld.innerHTML = connectionStatus; }; var setConfig = function() { var config, enforceTransport, debugLevel; calledBy = document.location.toString(); if (calledBy.indexOf('?') > -1) { var queryString = calledBy.substring(calledBy.indexOf('?') + 1); var nvPair = queryString.split("&"); for (var i=0; i<nvPair.length; i++) { if (nvPair[i].indexOf('=') > -1) { var nv = nvPair[i].split('='); if ("transport" === nv[0]) enforceTransport = nv[1]; if ("debug" === nv[0]) debugLevel = parseInt(nv[1]); } } if (enforceTransport !== undefined || debugLevel !== undefined) { config = {}; if (enforceTransport !== undefined) config.transport = enforceTransport; if (debugLevel !== undefined) config.debug = debugLevel; } } return config; }; </script> </head> <body> <table width="100%"> <tr> <td valign="top"><h2>WebSocket 101</h2></td> <td align="right" valign="bottom"><a href="" onclick="javascript:reset(); return false;" title="Clear messages"><small>Reset</small></a></td> </tr> <tr> <td valign="top" colspan="2"> <div id="content" style="padding:5px; background:#ddd; border-radius:5px; overflow-y: scroll; border:1px solid #CCC; margin-top:10px; height: 160px;"></div> </td> </tr> <tr> <td align="left" colspan="2"> <div id="prompt" style="width:200px; display:block; float:left; margin-top:15px;">Connecting...</div> <input type="text" id="input" style="border-radius:2px; border:1px solid #ccc; margin-top:10px; padding:5px; width:400px;" placeholder="Type your message here"/> <button onclick="javascript:send(document.getElementById('input').value);">Send</button> </td> </tr> <tr> <td align="left" colspan="2"> <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" colspan="2"><a href="" onclick="javascript:resetStatus(); return false;" title="Clear status board"><small>Reset Status</small></a></td> </tr> </table> <hr> </body> </html>
12nosanshiro-pi4j-sample
RasPISamples/node/chat.html
HTML
mit
4,452
"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') { try { var leapmotion = JSON.parse(json.data.text); var valueRoll = leapmotion.roll; var valuePitch = leapmotion.pitch; var valueYaw = leapmotion.yaw; angularSpeedAroundZ = valueYaw * 0.01; // yaw angularSpeedAroundY = valueRoll * 0.01; // roll angularSpeedAroundX = valuePitch * 0.01; // pitch } catch (err) { console.log("Err:" + err + " for " + json.data.text); } } 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 every 3 sec })(); 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
RasPISamples/node/lm.threejs.client.js
JavaScript
mit
2,695
"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') { try { var leapmotion = JSON.parse(json.data.text); var valueRoll = leapmotion.roll; var valuePitch = leapmotion.pitch; var valueYaw = leapmotion.yaw; displayRoll.setValue(valueRoll); displayPitch.setValue(valuePitch); displayYaw.setValue(valueYaw); } catch (err) { console.log("Err:" + err + " for " + json.data.text); } } 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 every 3 sec })(); 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
RasPISamples/node/lm.client.js
JavaScript
mit
2,650
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>TiltPan Camera / 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 displayPitch; var displayYaw; var statusFld; var ud = 0; var lr = 0; window.onload = function() { displayPitch = new AnalogDisplay('pitchCanvas', 100, 90, 30, 1, true, 40, -90); displayYaw = new AnalogDisplay('yawCanvas', 100, 90, 30, 1, true, 40, -90); statusFld = document.getElementById("status"); displayPitch.setValue(ud); displayYaw.setValue(lr); }; var buildMessage = function() { // pitch & roll and not right, I know. var mess = { pitch: 0, yaw: -lr, roll: ud }; return JSON.stringify(mess); }; var reset = function() { ud = 0; lr = 0; sendMessage(buildMessage()); }; var up = function() { ud += 1; ud = Math.min(ud, 90); sendMessage(buildMessage()); }; var down = function() { ud -= 1; ud = Math.max(ud, -90); sendMessage(buildMessage()); }; var left = function() { lr -= 1; lr = Math.max(lr, -90); sendMessage(buildMessage()); }; var right = function() { lr += 1; lr = Math.min(lr, 90); sendMessage(buildMessage()); }; </script> </head> <body> <div> <table style="margin: auto;"> <tr> <td valign="top"><h2>TiltPan Camera pilot, on WebSocket</h2></td> </tr> <tr> <td align="left" colspan="2"> <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" colspan="2"><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="pitchCanvas" width="240" height="220" title="Up-Donw value"></canvas> </td> <td align="center" valign="top"> <canvas id="yawCanvas" width="240" height="220" title="Left-Right value"></canvas> </td> </tr> <tr> <td align="center" valign="top">Up/Down</td> <td align="center" valign="top">Left/Right</td> </tr> <tr> <td align="center" colspan="2"> <table> <tr> <td></td><td><button onclick="up();" title="Up" style="width: 50px; height: 50px;">&#8593;</button></td><td></td> </tr> <tr> <td><button onclick="left();" title="Left" style="width: 50px; height: 50px;">&#8592;</button></td> <td><button onclick="reset();" title="Reset" style="width: 50px; height: 50px;">0</button></td> <td><button onclick="right();" title="Right" style="width: 50px; height: 50px;">&#8594;</button></td> </tr> <tr> <td></td><td><button onclick="down();" title="Down" style="width: 50px; height: 50px;">&#8595;</button></td><td></td> </tr> </table> </td> </tr> </table> </div> <hr> <script src="./tilt.pan.client.js"></script> <address>Oliv fecit, AD 2014</address> </body> </html>
12nosanshiro-pi4j-sample
RasPISamples/node/servo.pilot.html
HTML
mit
3,657
"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') { try { var leapmotion = JSON.parse(json.data.text); var valueRoll = leapmotion.roll; // var valuePitch = leapmotion.pitch; var valueYaw = -leapmotion.yaw; displayPitch.setValue(valueRoll); displayYaw.setValue(valueYaw); } catch (err) { console.log("Err:" + err + " for " + json.data.text); } } 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 every 3 sec })(); 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
RasPISamples/node/tilt.pan.client.js
JavaScript
mit
2,609
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:../SevenSegDisplay/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # echo 2 devices on the I2C bus. # sudo java -cp $CP raspisamples.SevenSegBMP180
12nosanshiro-pi4j-sample
RasPISamples/sample.01
Shell
mit
273
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes # CP=$CP:../SevenSegDisplay/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # CP=$CP:./lib/json.jar # sudo java -cp $CP raspisamples.log.net.BMP180Logging $*
12nosanshiro-pi4j-sample
RasPISamples/bmp180.logger
Shell
mit
276
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # sudo $JAVA_HOME/bin/java -cp $CP raspisamples.Real4PWMLed
12nosanshiro-pi4j-sample
RasPISamples/pwmled.03
Shell
mit
218
package raspisamples; import raspisamples.adc.JoyStick; import raspisamples.adc.JoyStickClient; import raspisamples.servo.StandardServo; /* * Joystick read with ADC (MCP3008) * 2 Servos (UP/LR) */ public class PanTiltJoyStick { private static StandardServo ssUD = null, ssLR = null; private static JoyStick joyStick = null; public static void main(String[] args) { ssUD = new StandardServo(14); // 14 : Address on the board (1..15) ssLR = new StandardServo(15); // 15 : Address on the board (1..15) // Init/Reset ssUD.stop(); ssLR.stop(); ssUD.setAngle(0f); ssLR.setAngle(0f); StandardServo.waitfor(2000); JoyStickClient jsc = new JoyStickClient() { @Override public void setUD(int v) // 0..100 { float angle = (float)(v - 50) * (9f / 5f); // conversion from 1..100 to -90..+90 if ("true".equals(System.getProperty("verbose", "false"))) System.out.println("UD:" + v + ", -> " + angle + " deg."); ssUD.setAngle(angle); // -90..+90 } @Override public void setLR(int v) // 0..100 { float angle = (float)(v - 50) * (9f / 5f); // conversion from 1..100 to -90..+90 if ("true".equals(System.getProperty("verbose", "false"))) System.out.println("LR:" + v + ", -> " + angle + " deg."); ssLR.setAngle(angle); // -90..+90 } }; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { ssUD.setAngle(0f); ssLR.setAngle(0f); StandardServo.waitfor(500); ssUD.stop(); ssLR.stop(); System.out.println("\nBye (Ctrl+C)"); } }); try { joyStick = new JoyStick(jsc); } catch (Exception e) { e.printStackTrace(); } finally { ssUD.setAngle(0f); ssLR.setAngle(0f); StandardServo.waitfor(500); ssUD.stop(); ssLR.stop(); System.out.println("Bye"); } } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/PanTiltJoyStick.java
Java
mit
2,084
package raspisamples; 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; import raspisamples.pwm.PWMPin; public class PWM3ColorLed { 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 { final GpioController gpio = GpioFactory.getInstance(); final PWMPin pin00 = new PWMPin(RaspiPin.GPIO_00, "Blue", PinState.HIGH); final PWMPin pin01 = new PWMPin(RaspiPin.GPIO_01, "Green", PinState.HIGH); final PWMPin pin02 = new PWMPin(RaspiPin.GPIO_02, "Red", PinState.HIGH); System.out.println("Ready..."); Runtime.getRuntime().addShutdownHook(new Thread("Hook") { public void run() { try { System.out.println("\nQuitting"); pin00.stopPWM(); pin01.stopPWM(); pin02.stopPWM(); Thread.sleep(1000); // Last blink System.out.println("Bye-bye"); pin00.low(); Thread.sleep(500); pin00.high(); Thread.sleep(500); pin00.low(); gpio.shutdown(); } catch (Exception ex) { ex.printStackTrace(); } } }); Thread.sleep(1000); pin00.emitPWM(0); pin01.emitPWM(0); pin02.emitPWM(0); for (int vol=0; vol<100; vol++) { pin00.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin00.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } for (int vol=0; vol<100; vol++) { pin01.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin01.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } for (int vol=0; vol<100; vol++) { pin02.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin02.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } Thread one = new Thread() { public void run() { while (true) { final int sleep = (int)(20 * Math.random()); for (int vol=0; vol<100; vol++) { pin00.adjustPWMVolume(vol); try { Thread.sleep(sleep); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin00.adjustPWMVolume(vol); try { Thread.sleep(sleep); } catch (Exception ex) {} } } } }; Thread two = new Thread() { public void run() { while (true) { final int sleep = (int)(20 * Math.random()); for (int vol=0; vol<100; vol++) { pin01.adjustPWMVolume(vol); try { Thread.sleep(sleep); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin01.adjustPWMVolume(vol); try { Thread.sleep(sleep); } catch (Exception ex) {} } } } }; Thread three = new Thread() { public void run() { while (true) { final int sleep = (int)(20 * Math.random()); for (int vol=0; vol<100; vol++) { pin02.adjustPWMVolume(vol); try { Thread.sleep(sleep); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin02.adjustPWMVolume(vol); try { Thread.sleep(sleep); } catch (Exception ex) {} } } } }; one.start(); two.start(); three.start(); Thread me = Thread.currentThread(); synchronized (me) { try { me.wait(); } catch (InterruptedException ie) {} } System.out.println("Tcho!"); } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/PWM3ColorLed.java
Java
mit
4,821
package raspisamples; import adafruiti2c.sensor.AdafruitBMP180; import com.pi4j.system.SystemInfo; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import sevensegdisplay.SevenSegment; /* * Two devices on the I2C bus. * A BMP180, and a 7-segment backpack display HT16K33 * mounted serially (V3V, GND, SDA, SLC) */ public class SevenSegBMP180 { private static boolean go = true; private static long wait = 2000L; public static void main(String[] args) { final NumberFormat NF = new DecimalFormat("##00.00"); AdafruitBMP180 sensor = new AdafruitBMP180(); final SevenSegment segment = new SevenSegment(0x70, true); Runtime.getRuntime().addShutdownHook(new Thread("Hook") { public void run() { System.out.println("\nQuitting"); try { segment.clear(); } catch (Exception ex) {} System.out.println("Bye-bye"); go = false; } }); while (go) { float temp = 0; try { temp = sensor.readTemperature(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } System.out.println("Temperature: " + NF.format(temp) + " C"); try { displayString("TEMP", segment); try { Thread.sleep(wait); } catch (InterruptedException ie){} displayFloat(temp, segment); try { Thread.sleep(wait); } catch (InterruptedException ie){} } catch (IOException ex) { ex.printStackTrace(); } // Bonus : CPU Temperature try { float cpu = SystemInfo.getCpuTemperature(); System.out.println("CPU Temperature : " + cpu); System.out.println("CPU Core Voltage : " + SystemInfo.getCpuVoltage()); displayString("CPU ", segment); try { Thread.sleep(wait); } catch (InterruptedException ie){} displayFloat(cpu, segment); try { Thread.sleep(wait); } catch (InterruptedException ie){} } catch (InterruptedException ie) { ie.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } private static void displayFloat(float t, SevenSegment segment) throws IOException { int one = (int)t / 10; int two = ((int)t) % 10; int three = ((int)( 10 * t) % 10); int four = ((int)(100 * t) % 10); // System.out.println(one + " " + two + "." + three + " " + four); segment.writeDigit(0, one); segment.writeDigit(1, two, true); segment.writeDigit(3, three); segment.writeDigit(4, four); } private static void displayString(String row, SevenSegment segment) throws IOException { segment.writeDigitRaw(0, row.substring(0, 1)); segment.writeDigitRaw(1, row.substring(1, 2)); segment.writeDigitRaw(3, row.substring(2, 3)); segment.writeDigitRaw(4, row.substring(3, 4)); } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/SevenSegBMP180.java
Java
mit
2,994
package raspisamples; import java.io.InputStream; import raspisamples.servo.StandardServo; /* * Driven by keyboard entries. * 2 Servos (UP/LR) */ public class PanTilt { private static StandardServo ssUD = null, ssLR = null; public static void main(String[] args) throws Exception { ssUD = new StandardServo(14); // 14 : Address on the board (1..15) ssLR = new StandardServo(15); // 15 : Address on the board (1..15) // Init/Reset ssUD.stop(); ssLR.stop(); ssUD.setAngle(0f); ssLR.setAngle(0f); StandardServo.waitfor(2000); InputStream in = System.in; boolean go = true; float angleUD = 0f; float angleLR = 0f; System.out.println("Type [U]p, [D]own, [L]eft, [R]ight, or [Q]uit. (followed by [Return])"); boolean unmanaged = false; while (go) { unmanaged = false; if (in.available() > 0) { int b = in.read(); if (((char)b) == 'Q' || ((char)b) == 'q') go = false; else if (((char)b) == 'L' || ((char)b) == 'l') { angleLR -= (((char)b) == 'L' ? 10 : 1); ssLR.setAngle(angleLR); // -90..+90 } else if (((char)b) == 'R' || ((char)b) == 'r') { angleLR += (((char)b) == 'R' ? 10 : 1); ssLR.setAngle(angleLR); // -90..+90 } else if (((char)b) == 'U' || ((char)b) == 'u') // Inverted... { angleUD -= (((char)b) == 'U' ? 10 : 1); ssUD.setAngle(angleUD); // -90..+90 } else if (((char)b) == 'D' || ((char)b) == 'd') // Inverted... { angleUD += (((char)b) == 'D' ? 10 : 1); ssUD.setAngle(angleUD); // -90..+90 } else unmanaged = true; if (!unmanaged && go) { System.out.println("LR:" + angleLR + ", UD:" + angleUD); } } } // Reset to 0,0 before shutting down. ssUD.setAngle(0f); ssLR.setAngle(0f); StandardServo.waitfor(2000); ssUD.stop(); ssLR.stop(); System.out.println("Bye"); } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/PanTilt.java
Java
mit
2,120
package raspisamples.adc; public interface JoyStickClient { public void setUD(int v); public void setLR(int v); }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/adc/JoyStickClient.java
Java
mit
119
package raspisamples.adc; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; /* A two-channel listener */ public class JoyStick { private static ADCObserver.MCP3008_input_channels channel[] = null; private final int[] channelValues = new int[] { 0, 0 }; // (0..100) private JoyStickClient joyStickClient = null; private int prevUDValue = 0, prevLRValue = 0; public JoyStick(JoyStickClient jsc) throws Exception { System.out.println(">> Channel MCP3008 #0: Up-Down"); System.out.println(">> Channel MCP3008 #1: Left-Right"); joyStickClient = jsc; channel = new ADCObserver.MCP3008_input_channels[] { ADCObserver.MCP3008_input_channels.CH0, // UD ADCObserver.MCP3008_input_channels.CH1 // LR }; final ADCObserver obs = new ADCObserver(channel); ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { int ch = inputChannel.ch(); int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if ("true".equals(System.getProperty("verbose", "false"))) System.out.println("\tServo channel:" + ch + ", value " + newValue + ", vol. " + volume + " %."); channelValues[ch] = volume; if (ch == channel[0].ch() && volume != prevUDValue) joyStickClient.setUD(volume); if (ch == channel[1].ch() && volume != prevLRValue) joyStickClient.setLR(volume); } }); obs.start(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (obs != null) obs.stop(); } }); } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/adc/JoyStick.java
Java
mit
1,852
package raspisamples.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class HTTPClient { public static String getContent(String url) throws Exception { String ret = null; try { byte content[] = readURL(new URL(url)); ret = new String(content); } catch(Exception e) { throw e; } return ret; } private static byte[] readURL(URL url) throws Exception { byte content[] = null; try { URLConnection newURLConn = url.openConnection(); InputStream is = newURLConn.getInputStream(); byte aByte[] = new byte[2]; int nBytes; long started = System.currentTimeMillis(); int nbLoop = 1; while((nBytes = is.read(aByte, 0, 1)) != -1) { content = Utilities.appendByte(content, aByte[0]); if (content.length > (nbLoop * 1000)) { long now = System.currentTimeMillis(); long delta = now - started; double rate = (double)content.length / ((double)delta / 1000D); System.out.println("Downloading at " + rate + " bytes per second."); nbLoop++; } } } catch(IOException e) { System.err.println("ReadURL for " + url.toString() + "\nnewURLConn failed :\n" + e); throw e; } catch(Exception e) { System.err.println("Exception for: " + url.toString()); } return content; } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/util/HTTPClient.java
Java
mit
1,482
package raspisamples.util; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Desktop; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.Hashtable; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; public class Utilities { public static void copy(InputStream is, OutputStream os) throws IOException { synchronized (is) { synchronized (os) { byte[] buffer = new byte[256]; while (true) { int bytesRead = is.read(buffer); if (bytesRead == -1) break; os.write(buffer, 0, bytesRead); } } } } public static File findFileName(String str) throws Exception { File file = null; boolean go = true; int i = 1; while (go) { String newName = str + "_" + Integer.toString(i); File f = new File(newName); if (f.exists()) i++; else { file = f; go = false; } } return file; } /** * * @param filename * @param extension with the preceeding ".", like ".ptrn" * @return */ public static String makeSureExtensionIsOK(String filename, String extension) { if (!filename.toLowerCase().endsWith(extension)) filename += extension; return filename; } public static String makeSureExtensionIsOK(String filename, String[] extension, String defaultExtension) { boolean extensionExists = false; for (int i=0; i<extension.length; i++) { if (filename.toLowerCase().endsWith(extension[i].toLowerCase())) { extensionExists = true; break; } } if (!extensionExists) filename += defaultExtension; return filename; } public static String getMacAddress() throws IOException { String macAddress = null; if (System.getProperty("os.name").indexOf("Windows") > -1) { String command = "ipconfig /all"; Process pid = Runtime.getRuntime().exec(command); BufferedReader in = new BufferedReader(new InputStreamReader(pid.getInputStream())); while (true) { String line = in.readLine(); if (line == null) break; Pattern p = Pattern.compile(".*Physical Address.*: (.*)"); Matcher m = p.matcher(line); if (m.matches()) { macAddress = m.group(1); break; } } in.close(); } else macAddress = "Unknown"; return macAddress; } //@SuppressWarnings("unchecked") public static void addURLToClassPath(URL url) { try { URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); Class<?> c = /*(Class<URLClassLoader>)*/Class.forName("java.net.URLClassLoader"); Class<?>[] parameterTypes = new Class<?>[1]; parameterTypes[0] = /*(Class<?>)*/Class.forName("java.net.URL"); Method m = c.getDeclaredMethod("addURL", parameterTypes); m.setAccessible(true); Object[] args = new Object[1]; args[0] = url; m.invoke(urlClassLoader, args); } catch (Exception e) { throw new RuntimeException(e); } } public static void openInBrowser(String page) throws Exception { URI uri = new URI(page); try { // System.out.println("Opening in browser:[" + uri.toString() + "]"); Desktop.getDesktop().browse(uri); } catch (Exception ex) // UnsupportedOperationException ex) { String mess = ex.getMessage(); mess += ("\n\nUnsupported operation on your system. URL [" + uri.toString() + "] is in the clipboard.\nOpen your browser manually, and paste it in there (Ctrl+V)."); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); String path = uri.toString(); try { File f = new File(page); if (f.exists()) { path = f.getAbsolutePath(); if (File.separatorChar != '/') path = path.replace(File.separatorChar, '/'); if (!path.startsWith("/")) path = "/" + path; path = "file:" + path; } } catch (Exception ex2) { ex2.printStackTrace(); } StringSelection stringSelection = new StringSelection(path); clipboard.setContents(stringSelection, null); JOptionPane.showMessageDialog(null, mess, "Showing in Browser", JOptionPane.ERROR_MESSAGE); } // String os = System.getProperty("os.name"); // if (os.indexOf("Windows") > -1) // { // String cmd = ""; // if (page.indexOf(" ") != -1) // cmd = "cmd /k start \"" + page + "\""; // else // cmd = "cmd /k start " + page + ""; // System.out.println("Command:" + cmd); // Runtime.getRuntime().exec(cmd); // Can contain blanks... // } // else if (os.indexOf("Linux") > -1) // Assuming htmlview // Runtime.getRuntime().exec("htmlview " + page); // else // { // throw new RuntimeException("OS [" + os + "] not supported yet"); // } } public static void showFileSystem(String where) throws Exception { String os = System.getProperty("os.name"); if (os.indexOf("Windows") > -1) { String cmd = "cmd /k start /D\"" + where + "\" ."; // System.out.println("Executing [" + cmd + "]"); Runtime.getRuntime().exec(cmd); // Can contain blanks, need quotes around it... } else if (os.indexOf("Linux") > -1) Runtime.getRuntime().exec("nautilus " + where); else if (os.indexOf("Mac") > -1) { String[] applScriptCmd = { "osascript", "-e", "tell application \"Finder\"", "-e", "activate", "-e", "<open cmd>", // open cmd: index 6 "-e", "end tell" }; String pattern = File.separator; if (pattern.equals("\\")) pattern = "\\\\"; String[] pathElem = where.split(pattern); String cmd = "open "; for (int i=pathElem.length - 1; i>0; i--) cmd += ("folder \"" + pathElem[i] + "\" of "); cmd += "startup disk"; applScriptCmd[6] = cmd; Runtime.getRuntime().exec(applScriptCmd); } else { throw new RuntimeException("showFileSystem method on OS [" + os + "] not implemented yet.\nFor now, you should open [" + where +"] by yourself."); } } public static void main(String[] args) throws Exception { // System.setProperty("os.name", "Mac OS X"); // showFileSystem(System.getProperty("user.dir")); long elapsed = 123456L; // 231234567890L; System.out.println("Readable time (" + elapsed + ") : " + readableTime(elapsed)); } public static int sign(double d) { int s = 0; if (d > 0.0D) s = 1; if (d < 0.0D) s = -1; return s; } public static void makeSureTempExists() throws IOException { File dir = new File("temp"); if (!dir.exists()) dir.mkdirs(); } /** * remove leading and trailing blanks, CR, NL * @param str * @return */ public static String superTrim(String str) { String str2 = ""; char[] strChar = str.toCharArray(); // Leading int i = 0; while (strChar[i] == ' ' || strChar[i] == '\n' || strChar[i] == '\r') { i++; } str2 = str.substring(i); while(str2.endsWith("\n") || str2.endsWith("\r")) str2 = str2.substring(0, str2.length() - 2); return str2.trim(); } public static String replaceString(String orig, String oldStr, String newStr) { String ret = orig; int indx = 0; for (boolean go = true; go;) { indx = ret.indexOf(oldStr, indx); if (indx < 0) { go = false; } else { ret = ret.substring(0, indx) + newStr + ret.substring(indx + oldStr.length()); indx += 1 + oldStr.length(); } } return ret; } public static byte[] appendByte(byte c[], byte b) { int newLength = c != null ? c.length + 1 : 1; byte newContent[] = new byte[newLength]; for(int i = 0; i < newLength - 1; i++) newContent[i] = c[i]; newContent[newLength - 1] = b; return newContent; } public static byte[] appendByteArrays(byte c[], byte b[], int n) { int newLength = c != null ? c.length + n : n; byte newContent[] = new byte[newLength]; if (c != null) { for (int i=0; i<c.length; i++) newContent[i] = c[i]; } int offset = (c!=null?c.length:0); for (int i=0; i<n; i++) newContent[offset + i] = b[i]; return newContent; } public static String chooseFile(int mode, String flt, String desc, String title, String buttonLabel) { String fileName = ""; JFileChooser chooser = new JFileChooser(); if (title != null) chooser.setDialogTitle(title); if (buttonLabel != null) chooser.setApproveButtonText(buttonLabel); if (flt != null) { ToolFileFilter filter = new ToolFileFilter(flt, desc); chooser.addChoosableFileFilter(filter); chooser.setFileFilter(filter); } chooser.setFileSelectionMode(mode); // Set current directory File f = new File("."); String currPath = f.getAbsolutePath(); f = new File(currPath.substring(0, currPath.lastIndexOf(File.separator))); chooser.setCurrentDirectory(f); int retval = chooser.showOpenDialog(null); switch (retval) { case JFileChooser.APPROVE_OPTION: fileName = chooser.getSelectedFile().toString(); break; case JFileChooser.CANCEL_OPTION: break; case JFileChooser.ERROR_OPTION: break; } return fileName; } public static int drawPanelTable(String[][] data, Graphics gr, Point topLeft, int betweenCols, int betweenRows) { return drawPanelTable(data, gr, topLeft, betweenCols, betweenRows, null); } public final static int LEFT_ALIGNED = 0; public final static int RIGHT_ALIGNED = 1; public final static int CENTER_ALIGNED = 2; public static int drawPanelTable(String[][] data, Graphics gr, Point topLeft, int betweenCols, int betweenRows, int[] colAlignment) { return drawPanelTable(data, gr, topLeft, betweenCols, betweenRows, colAlignment, false, null, 0f); } public static int drawPanelTable(String[][] data, Graphics gr, Point topLeft, int betweenCols, int betweenRows, int[] colAlignment, boolean paintBackground, Color bgColor, float bgTransparency) { return drawPanelTable(data, gr, topLeft, betweenCols, betweenRows, colAlignment, paintBackground, bgColor, null, bgTransparency, 1f); } public static int drawPanelTable(String[][] data, Graphics gr, Point topLeft, int betweenCols, int betweenRows, int[] colAlignment, boolean paintBackground, Color bgLightColor, Color bgDarkColor, float bgTransparency, float textTransparency) { int w = 0, h = 0; Font f = gr.getFont(); int[] maxLength = new int[data[0].length]; // Max length for each column for (int i=0; i<maxLength.length; i++) // init. All to 0 maxLength[i] = 0; // Identify the max length for each column for (int row=0; row<data.length; row++) { for (int col=0; col<data[row].length; col++) { int strWidth = gr.getFontMetrics(f).stringWidth(data[row][col]); maxLength[col] = Math.max(maxLength[col], strWidth); } } int x = topLeft.x; int y = topLeft.y; w = betweenCols; for (int i=0; i<maxLength.length; i++) w += (maxLength[i] + betweenCols); h = betweenRows + (data.length * (f.getSize() + betweenRows)) + betweenRows; if (paintBackground) // Glossy { boolean glossy = (bgLightColor != null && bgDarkColor != null); Color c = gr.getColor(); if (glossy) { drawGlossyRectangularDisplay((Graphics2D)gr, new Point(x - betweenCols, y - f.getSize() - betweenRows), new Point(x - betweenCols + w, y - f.getSize() - betweenRows + h), bgLightColor, bgDarkColor, bgTransparency); } else { gr.setColor(bgLightColor); gr.fillRoundRect(x - betweenCols, y - f.getSize() - betweenRows, w, h, 10, 10); } gr.setColor(c); } ((Graphics2D)gr).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, textTransparency)); // Now display for (int row=0; row<data.length; row++) { for (int col=0; col<data[row].length; col++) { int _x = x; for (int c=1; c<=col; c++) _x += (betweenCols + maxLength[c - 1]); if (colAlignment != null && colAlignment[col] != LEFT_ALIGNED) { int strWidth = gr.getFontMetrics(f).stringWidth(data[row][col]); switch (colAlignment[col]) { case RIGHT_ALIGNED: _x += (maxLength[col] - strWidth); break; case CENTER_ALIGNED: _x += ((maxLength[col] - strWidth) / 2); break; default: break; } } gr.drawString(data[row][col], _x, y); } y += (f.getSize() + betweenRows); } return y; } private static void drawGlossyRectangularDisplay(Graphics2D g2d, Point topLeft, Point bottomRight, Color lightColor, Color darkColor, float transparency) { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency)); g2d.setPaint(null); g2d.setColor(darkColor); int width = bottomRight.x - topLeft.x; int height = bottomRight.y - topLeft.y; g2d.fillRoundRect(topLeft.x , topLeft.y, width, height, 10, 10); Point gradientOrigin = new Point(topLeft.x + (width) / 2, topLeft.y); GradientPaint gradient = new GradientPaint(gradientOrigin.x, gradientOrigin.y, lightColor, gradientOrigin.x, gradientOrigin.y + (height / 3), darkColor); // vertical, light on top g2d.setPaint(gradient); int offset = 3; int arcRadius = 5; g2d.fillRoundRect(topLeft.x + offset, topLeft.y + offset, (width - (2 * offset)), (height - (2 * offset)), 2 * arcRadius, 2 * arcRadius); } public static boolean thisClassVerbose(Class c) { return (System.getProperty(c.getName() + ".verbose", "false").equals("true") || System.getProperty("all.verbose", "false").equals("true")); } public static String readableTime(long elapsed) { return readableTime(elapsed, false); } public static String readableTime(long elapsed, boolean small) { long amount = elapsed; String str = ""; final long SECOND = 1000L; final long MINUTE = 60 * SECOND; final long HOUR = 60 * MINUTE; final long DAY = 24 * HOUR; final long WEEK = 7 * DAY; if (amount >= WEEK) { int week = (int)(amount / WEEK); str += (week + (small?" w ":" week(s) ")); amount -= (week * WEEK); } if (amount >= DAY || str.length() > 0) { int day = (int)(amount / DAY); str += (day + (small?" d ":" day(s) ")); amount -= (day * DAY); } if (amount >= HOUR || str.length() > 0) { int hour = (int)(amount / HOUR); str += (hour + (small?" h ":" hour(s) ")); amount -= (hour * HOUR); } if (amount >= MINUTE || str.length() > 0) { int minute = (int)(amount / MINUTE); str += (minute + (small?" m ":" minute(s) ")); amount -= (minute * MINUTE); } // if (amount > SECOND || str.length() > 0) { int second = (int)(amount / SECOND); str += (second + ((amount % 1000) != 0 ? "." + (amount % 1000) : "") + (small?" s ":" second(s) ")); amount -= (second * SECOND); } return str; } static class ToolFileFilter extends FileFilter { private Hashtable<String, FileFilter> filters = null; private String description = null; private String fullDescription = null; private boolean useExtensionsInDescription = true; public ToolFileFilter() { this((String) null, (String) null); } public ToolFileFilter(String extension) { this(extension, null); } public ToolFileFilter(String extension, String description) { this(new String[] {extension}, description); } public ToolFileFilter(String[] filters) { this(filters, null); } public ToolFileFilter(String[] filters, String description) { this.filters = new Hashtable<String, FileFilter>(filters.length); for (int i = 0; i < filters.length; i++) { // add filters one by one addExtension(filters[i]); } setDescription(description); } public boolean accept(File f) { if (f != null) { if(f.isDirectory()) { return true; } String extension = getExtension(f); if (extension != null && filters.get(getExtension(f)) != null) { return true; } } return false; } public String getExtension(File f) { if(f != null) { String filename = f.getName(); int i = filename.lastIndexOf('.'); if (i>0 && i<filename.length()-1) { return filename.substring(i+1).toLowerCase(); } } return null; } public void addExtension(String extension) { if (filters == null) { filters = new Hashtable<String, FileFilter>(5); } filters.put(extension.toLowerCase(), this); fullDescription = null; } public String getDescription() { if(fullDescription == null) { if(description == null || isExtensionListInDescription()) { if(description != null) { fullDescription = description; } fullDescription += " ("; // build the description from the extension list Enumeration extensions = filters.keys(); if (extensions != null) { fullDescription += "." + (String) extensions.nextElement(); while (extensions.hasMoreElements()) { fullDescription += ", " + (String) extensions.nextElement(); } } fullDescription += ")"; } else { fullDescription = description; } } return fullDescription; } public void setDescription(String description) { this.description = description; fullDescription = null; } public void setExtensionListInDescription(boolean b) { useExtensionsInDescription = b; fullDescription = null; } public boolean isExtensionListInDescription() { return useExtensionsInDescription; } } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/util/Utilities.java
Java
mit
20,395
package raspisamples; 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; import raspisamples.pwm.PWMPin; public class Real4PWMLed { public static void main(String[] args) throws InterruptedException { final GpioController gpio = GpioFactory.getInstance(); final PWMPin pin00 = new PWMPin(RaspiPin.GPIO_00, "LED-One", PinState.HIGH); final PWMPin pin01 = new PWMPin(RaspiPin.GPIO_01, "LED-Two", PinState.HIGH); final PWMPin pin02 = new PWMPin(RaspiPin.GPIO_02, "LED-Three", PinState.HIGH); final PWMPin pin03 = new PWMPin(RaspiPin.GPIO_03, "LED-Four", PinState.HIGH); System.out.println("Ready..."); Thread.sleep(1000); pin00.emitPWM(0); pin01.emitPWM(0); pin02.emitPWM(0); pin03.emitPWM(0); final Thread mainThread = Thread.currentThread(); final Thread monitor = new Thread() { public void run() { int nbNotification = 0; boolean keepWaiting = true; while (keepWaiting) { synchronized (this) { try { System.out.println("Monitor waiting."); wait(); nbNotification++; System.out.println("Received " + nbNotification + " notification(s)..."); if (nbNotification == 4) { synchronized (mainThread) { mainThread.notify(); } keepWaiting = false; } } catch (InterruptedException ie) { ie.printStackTrace(); } } } System.out.println("Monitor exiting."); } }; monitor.start(); Thread one = new Thread() { public void run() { for (int vol=0; vol<100; vol++) { pin00.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin00.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } synchronized(monitor) { System.out.println("Thread One finishing"); monitor.notify(); } } }; Thread two = new Thread() { public void run() { for (int vol=100; vol>0; vol--) { pin01.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } for (int vol=0; vol<=100; vol++) { pin01.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } try { Thread.sleep(100); } catch (Exception ex) {} synchronized(monitor) { System.out.println("Thread Two finishing"); monitor.notify(); } } }; Thread three = new Thread() { public void run() { for (int vol=0; vol<100; vol++) { pin02.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin02.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=0; vol<100; vol++) { pin02.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin02.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } try { Thread.sleep(200); } catch (Exception ex) {} synchronized(monitor) { System.out.println("Thread Three finishing"); monitor.notify(); } } }; Thread four = new Thread() { public void run() { for (int vol=100; vol>0; vol--) { pin03.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=0; vol<=100; vol++) { pin03.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=100; vol>0; vol--) { pin03.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=0; vol<=100; vol++) { pin03.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } try { Thread.sleep(300); } catch (Exception ex) {} synchronized(monitor) { System.out.println("Thread Four finishing"); monitor.notify(); } } }; one.start(); two.start(); three.start(); four.start(); synchronized (mainThread) { mainThread.wait(); } System.out.println("Everyone's done, finishing."); // try { Thread.sleep(5000L); } catch (Exception ex) {} pin00.stopPWM(); pin01.stopPWM(); pin02.stopPWM(); pin03.stopPWM(); Thread.sleep(1000); // Last blink System.out.println("Bye-bye"); pin00.low(); Thread.sleep(500); pin00.high(); Thread.sleep(500); pin00.low(); gpio.shutdown(); } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/Real4PWMLed.java
Java
mit
5,681
package raspisamples.wp; 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 com.pi4j.wiringpi.SoftPwm; import com.pi4j.wiringpi.Gpio; /* * PWM with WiringPi */ public class WiringPiSoftPWM3ColorLed { public static void main(String[] args) throws InterruptedException { // initialize wiringPi library Gpio.wiringPiSetup(); int pinAddress_00 = RaspiPin.GPIO_00.getAddress(); int pinAddress_01 = RaspiPin.GPIO_01.getAddress(); int pinAddress_02 = RaspiPin.GPIO_02.getAddress(); // create soft-pwm pins (min=0 ; max=100) SoftPwm.softPwmCreate(pinAddress_00, 0, 100); SoftPwm.softPwmCreate(pinAddress_01, 0, 100); SoftPwm.softPwmCreate(pinAddress_02, 0, 100); // continuous loop // while (true) { System.out.println("One"); // fade LED to fully ON for (int i = 0; i <= 100; i++) { SoftPwm.softPwmWrite(pinAddress_00, i); Thread.sleep(5); } System.out.println("Two"); // fade LED to fully OFF for (int i = 100; i >= 0; i--) { SoftPwm.softPwmWrite(pinAddress_00, i); Thread.sleep(5); } System.out.println("Three"); // fade LED to fully ON for (int i = 0; i <= 100; i++) { SoftPwm.softPwmWrite(pinAddress_01, i); Thread.sleep(5); } System.out.println("Four"); // fade LED to fully OFF for (int i = 100; i >= 0; i--) { SoftPwm.softPwmWrite(pinAddress_01, i); Thread.sleep(5); } System.out.println("Five"); // fade LED to fully ON for (int i = 0; i <= 100; i++) { SoftPwm.softPwmWrite(pinAddress_02, i); Thread.sleep(5); } System.out.println("Six"); // fade LED to fully OFF for (int i = 100; i >= 0; i--) { SoftPwm.softPwmWrite(pinAddress_02, i); Thread.sleep(5); } } System.out.println("Seven"); // All spectrum for (int a = 0; a <= 100; a++) { SoftPwm.softPwmWrite(pinAddress_00, a); // Thread.sleep(5); for (int b = 0; b <= 100; b++) { SoftPwm.softPwmWrite(pinAddress_01, b); // Thread.sleep(5); for (int c = 0; c <= 100; c++) { SoftPwm.softPwmWrite(pinAddress_02, c); Thread.sleep(1); } for (int c = 100; c >= 0; c--) { SoftPwm.softPwmWrite(pinAddress_02, c); Thread.sleep(1); } } for (int b = 100; b >= 0; b--) { SoftPwm.softPwmWrite(pinAddress_01, b); // Thread.sleep(5); for (int c = 0; c <= 100; c++) { SoftPwm.softPwmWrite(pinAddress_02, c); Thread.sleep(1); } for (int c = 100; c >= 0; c--) { SoftPwm.softPwmWrite(pinAddress_02, c); Thread.sleep(1); } } } System.out.println("Eight"); for (int a = 100; a >= 0; a--) { SoftPwm.softPwmWrite(pinAddress_00, a); // Thread.sleep(5); for (int b = 0; b <= 100; b++) { SoftPwm.softPwmWrite(pinAddress_01, b); // Thread.sleep(5); for (int c = 0; c <= 100; c++) { SoftPwm.softPwmWrite(pinAddress_02, c); Thread.sleep(1); } for (int c = 100; c >= 0; c--) { SoftPwm.softPwmWrite(pinAddress_02, c); Thread.sleep(1); } } for (int b = 100; b >= 0; b--) { SoftPwm.softPwmWrite(pinAddress_01, b); // Thread.sleep(5); for (int c = 0; c <= 100; c++) { SoftPwm.softPwmWrite(pinAddress_02, c); Thread.sleep(1); } for (int c = 100; c >= 0; c--) { SoftPwm.softPwmWrite(pinAddress_02, c); Thread.sleep(1); } } } System.out.println("Done"); } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/wp/WiringPiSoftPWM3ColorLed.java
Java
mit
4,006
package raspisamples.wp; 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 com.pi4j.wiringpi.SoftPwm; /* * PWM with WiringPi */ public class WiringPiSoftPWMExample { public static void main(String[] args) throws InterruptedException { // initialize wiringPi library com.pi4j.wiringpi.Gpio.wiringPiSetup(); int pinAddress = RaspiPin.GPIO_01.getAddress(); // create soft-pwm pins (min=0 ; max=100) // SoftPwm.softPwmCreate(1, 0, 100); SoftPwm.softPwmCreate(pinAddress, 0, 100); // continuous loop boolean go = true; for (int idx=0; idx<5; idx++) { // fade LED to fully ON for (int i = 0; i <= 100; i++) { SoftPwm.softPwmWrite(1, i); Thread.sleep(10); } // fade LED to fully OFF for (int i = 100; i >= 0; i--) { SoftPwm.softPwmWrite(1, i); Thread.sleep(10); } } } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/wp/WiringPiSoftPWMExample.java
Java
mit
1,051
package raspisamples.servo; import adafruiti2c.servo.AdafruitPCA9685; /* * Standard, using I2C and the PCA9685 servo board */ public class StandardServo { public static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } private int servo = -1; private final static int DEFAULT_SERVO_MIN = 122; // Value for Min position (-90, unit is [0..1023]) private final static int DEFAULT_SERVO_MAX = 615; // Value for Max position (+90, unit is [0..1023]) private int servoMin = DEFAULT_SERVO_MIN; private int servoMax = DEFAULT_SERVO_MAX; private int diff = servoMax - servoMin; private AdafruitPCA9685 servoBoard = new AdafruitPCA9685(); public StandardServo(int channel) { this(channel, DEFAULT_SERVO_MIN, DEFAULT_SERVO_MAX); } public StandardServo(int channel, int servoMin, int servoMax) { this.servoMin = servoMin; this.servoMax = servoMax; this.diff = servoMax - servoMin; int freq = 60; servoBoard.setPWMFreq(freq); // Set frequency in Hz this.servo = channel; System.out.println("Channel " + channel + " all set. Min:" + servoMin + ", Max:" + servoMax + ", diff:" + diff); } public void setAngle(float f) { int pwm = degreeToPWM(servoMin, servoMax, f); // System.out.println(f + " degrees (" + pwm + ")"); servoBoard.setPWM(servo, 0, pwm); } public void setPWM(int pwm) { servoBoard.setPWM(servo, 0, pwm); } public void stop() // Set to 0 { servoBoard.setPWM(servo, 0, 0); } /* * deg in [-90..90] */ private static int degreeToPWM(int min, int max, float deg) { int diff = max - min; float oneDeg = diff / 180f; return Math.round(min + ((deg + 90) * oneDeg)); } /** * To test the servo - namely, the min & max values. * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int channel = 14; if (args.length > 0) { try { channel = Integer.parseInt(args[0]); } catch (Exception e) { throw e; } } System.out.println("Servo Channel " + channel); StandardServo ss = new StandardServo(channel); try { ss.stop(); waitfor(2000); System.out.println("Let's go, 1 by 1 (" + ss.servoMin + " to " + ss.servoMax + ")"); for (int i=ss.servoMin; i<=ss.servoMax; i++) { System.out.println("i=" + i + ", " + (-90f + (((float)(i - ss.servoMin) / (float)ss.diff) * 180f))); ss.setPWM(i); waitfor(10); } for (int i=ss.servoMax; i>=ss.servoMin; i--) { System.out.println("i=" + i + ", " + (-90f + (((float)(i - ss.servoMin) / (float)ss.diff) * 180f))); ss.setPWM(i); waitfor(10); } ss.stop(); waitfor(2000); System.out.println("Let's go, 1 deg by 1 deg"); for (int i=ss.servoMin; i<=ss.servoMax; i+=(ss.diff / 180)) { System.out.println("i=" + i + ", " + Math.round(-90f + (((float)(i - ss.servoMin) / (float)ss.diff) * 180f))); ss.setPWM(i); waitfor(10); } for (int i=ss.servoMax; i>=ss.servoMin; i-=(ss.diff / 180)) { System.out.println("i=" + i + ", " + Math.round(-90f + (((float)(i - ss.servoMin) / (float)ss.diff) * 180f))); ss.setPWM(i); waitfor(10); } ss.stop(); waitfor(2000); float[] degValues = { -10, 0, -90, 45, -30, 90, 10, 20, 30, 40, 50, 60, 70, 80, 90, 0 }; for (float f : degValues) { System.out.println("In degrees:" + f); ss.setAngle(f); waitfor(1500); } } finally { ss.stop(); } System.out.println("Done."); } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/servo/StandardServo.java
Java
mit
3,820
package raspisamples.log.net; import adafruiti2c.sensor.AdafruitBMP180; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.json.JSONObject; import raspisamples.util.HTTPClient; public class BMP180Logging { private final static String LOGGER_URL = "http://donpedro.lediouris.net/php/raspi/insert.php"; // ?board=OlivRPi1&sensor=BMP180&type=TEMPERATURE&data=24 private final static String SENSOR_ID = "BMP180"; private final static String TEMPERATURE = "TEMPERATURE"; private final static String PRESSURE = "PRESSURE"; private static String boardID = "OlivRPi1"; private static long waitTime = 10000L; private static String sessionID = "XX"; static { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sessionID = sdf.format(new Date()); } private final static String BOARD_PRM = "-board"; private final static String WAIT_PRM = "-wait"; private final static String SESS_PRM = "-sess"; private final static String HELP_PRM = "-help"; protected static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } private static void processPrm(String[] args) { for (int i=0; i<args.length; i++) { if (BOARD_PRM.equals(args[i])) boardID = args[i + 1]; else if (WAIT_PRM.equals(args[i])) { try { waitTime = 1000L * Integer.parseInt(args[i + 1]); } catch (Exception ex) { ex.printStackTrace(); } } else if (SESS_PRM.equals(args[i])) sessionID = args[i + 1]; else if (HELP_PRM.equals(args[i])) { System.out.println("Usage is:"); System.out.println(" java raspisamples.log.net.BMP180Logging -board <BoardID> -sess <Session ID> -wait <time-in-sec> -help "); System.out.println(" <BoardID> is your board ID (default is OlivRPi1)"); System.out.println(" <Session ID> identifies your logging session (default current date YYYY-MM-DD)"); System.out.println(" <time-in-sec> is the amount of seconds between logs (default is 10)"); System.out.println(); System.out.println("Logging data for board [" + boardID + "]"); System.out.println("Logging data every " + Long.toString(waitTime / 1000) + " s. Session ID:" + sessionID); System.exit(0); } } } public static void main(String[] args) { processPrm(args); System.out.println("Logging data for [" + boardID + "], every " + Long.toString(waitTime / 1000) + " s."); final NumberFormat NF = new DecimalFormat("##00.00"); AdafruitBMP180 sensor = new AdafruitBMP180(); float press = 0; float temp = 0; double alt = 0; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("\nBye now."); } }); while (true) { try { press = sensor.readPressure(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } sensor.setStandardSeaLevelPressure((int)press); // As we ARE at the sea level (in San Francisco). try { alt = sensor.readAltitude(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { temp = sensor.readTemperature(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } System.out.println("At " + new Date().toString()); System.out.println("Temperature: " + NF.format(temp) + " C"); System.out.println("Pressure : " + NF.format(press / 100) + " hPa"); System.out.println("Altitude : " + NF.format(alt) + " m"); // Log here try { String url = LOGGER_URL + "?board=" + boardID + "&session=" + sessionID + "&sensor=" + SENSOR_ID + "&type=" + TEMPERATURE + "&data=" + NF.format(temp); String response = HTTPClient.getContent(url); JSONObject json = new JSONObject(response); System.out.println("Returned\n" + json.toString(2)); try { Thread.sleep(1000); } catch (Exception ex) { ex.printStackTrace(); } // To avoid duplicate PK url = LOGGER_URL + "?board=" + boardID + "&session=" + sessionID + "&sensor=" + SENSOR_ID + "&type=" + PRESSURE + "&data=" + NF.format(press / 100); response = HTTPClient.getContent(url); json = new JSONObject(response); System.out.println("Returned\n" + json.toString(2)); } catch (Exception ex) { ex.printStackTrace(); } waitfor(waitTime); } } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/log/net/BMP180Logging.java
Java
mit
5,010
package raspisamples.log.net; import adafruiti2c.sensor.AdafruitBMP180; import adafruiti2c.sensor.AdafruitHTU21DF; import java.io.BufferedWriter; import java.io.FileWriter; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.json.JSONObject; import raspisamples.util.HTTPClient; /** * Log weather data in a file */ public class WeatherDataFileLogging { private static long waitTime = 10000L; private final static String WAIT_PRM = "-wait"; private final static String FILE_PRM = "-file"; private final static String HELP_PRM = "-help"; private final static String NO_BMP180 = "-nobmp180"; private final static String NO_HTU21DF = "-nohtu21df"; private static String logFileName = "weather.data.log"; private static boolean withBMP180 = true; private static boolean withHTU21DF = true; protected static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } private static void processPrm(String[] args) { for (int i=0; i<args.length; i++) { if (FILE_PRM.equals(args[i])) logFileName = args[i + 1]; else if (WAIT_PRM.equals(args[i])) { try { waitTime = 1000L * Integer.parseInt(args[i + 1]); } catch (Exception ex) { ex.printStackTrace(); } } else if (NO_BMP180.equals(args[i])) withBMP180 = false; else if (NO_HTU21DF.equals(args[i])) withHTU21DF = false; else if (HELP_PRM.equals(args[i])) { System.out.println("Usage is:"); System.out.println(" java raspisamples.log.net.WeatherDataFileLogging -file <LogFileName> -wait <time-in-sec> [ -nobmp180 ][ -nohtu21df ] -help "); System.out.println(" <LogFileName> is your log file name (default is weather.data.log)"); System.out.println(" <time-in-sec> is the amount of seconds between logs (default is 10)"); System.out.println(); System.out.println("Logging data in [" + logFileName + "]"); System.out.println("Logging data every " + Long.toString(waitTime / 1000) + " s"); System.exit(0); } } } public static void main(String[] args) throws Exception { processPrm(args); System.out.println("Logging data in [" + logFileName + "], every " + Long.toString(waitTime / 1000) + " s."); final BufferedWriter log = new BufferedWriter(new FileWriter(logFileName)); final NumberFormat NF = new DecimalFormat("##00.00"); AdafruitBMP180 bmpSensor = null; if (withBMP180) { try { bmpSensor = new AdafruitBMP180(); } catch (Exception ex ) { ex.printStackTrace(); } } float press = 0; float temp = 0; AdafruitHTU21DF humSensor = null; if (withHTU21DF) { try { humSensor = new AdafruitHTU21DF(); } catch (Exception ex ) { ex.printStackTrace(); } } float hum = 0; if (humSensor != null) { try { if (!humSensor.begin()) { System.out.println("Sensor not found!"); System.exit(1); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("\nBye now."); // Close log file if (log != null) { try { log.flush(); log.close(); } catch (Exception ex) { ex.printStackTrace(); } } } }); while (true) { if (bmpSensor != null) { try { press = bmpSensor.readPressure(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { temp = bmpSensor.readTemperature(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } } if (humSensor != null) { try { hum = humSensor.readHumidity(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } } long now = System.currentTimeMillis(); // System.out.println("At " + new Date().toString()); System.out.println("Temperature: " + NF.format(temp) + " C"); System.out.println("Pressure : " + NF.format(press / 100) + " hPa"); System.out.println("Humidity : " + NF.format(hum) + " %"); // Log here try { JSONObject dataObject = new JSONObject(); // + NF.format(temp); dataObject.put("epoch", now); dataObject.put("pressure", press/100); dataObject.put("temperature", temp); dataObject.put("humidity", hum); String logStr = dataObject.toString(); log.write(logStr + "\n"); log.flush(); } catch (Exception ex) { ex.printStackTrace(); } waitfor(waitTime); } } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/log/net/WeatherDataFileLogging.java
Java
mit
5,737
package raspisamples.log.net; import adafruiti2c.sensor.AdafruitBMP180; import adafruiti2c.sensor.AdafruitHTU21DF; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.json.JSONObject; import raspisamples.util.HTTPClient; /** * Log weather data with php/MySQL over the net */ public class WeatherDataLogging { private final static String LOGGER_URL = "http://donpedro.lediouris.net/php/raspi/insert.php"; // ?board=OlivRPi1&sensor=BMP180&type=TEMPERATURE&data=24 private final static String BMP_SENSOR_ID = "BMP180"; private final static String HUM_SENSOR_ID = "HTU21D-F"; private final static String TEMPERATURE = "TEMPERATURE"; private final static String PRESSURE = "PRESSURE"; private final static String HUMIDITY = "HUMIDITY"; private static String boardID = "OlivRPi1"; private static long waitTime = 10000L; private static String sessionID = "XX"; static { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sessionID = sdf.format(new Date()); } private final static String BOARD_PRM = "-board"; private final static String WAIT_PRM = "-wait"; private final static String SESS_PRM = "-sess"; private final static String HELP_PRM = "-help"; protected static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } private static void processPrm(String[] args) { for (int i=0; i<args.length; i++) { if (BOARD_PRM.equals(args[i])) boardID = args[i + 1]; else if (WAIT_PRM.equals(args[i])) { try { waitTime = 1000L * Integer.parseInt(args[i + 1]); } catch (Exception ex) { ex.printStackTrace(); } } else if (SESS_PRM.equals(args[i])) sessionID = args[i + 1]; else if (HELP_PRM.equals(args[i])) { System.out.println("Usage is:"); System.out.println(" java raspisamples.log.net.WeatherDataLogging -board <BoardID> -sess <Session ID> -wait <time-in-sec> -help "); System.out.println(" <BoardID> is your board ID (default is OlivRPi1)"); System.out.println(" <Session ID> identifies your logging session (default current date YYYY-MM-DD)"); System.out.println(" <time-in-sec> is the amount of seconds between logs (default is 10)"); System.out.println(); System.out.println("Logging data for board [" + boardID + "]"); System.out.println("Logging data every " + Long.toString(waitTime / 1000) + " s. Session ID:" + sessionID); System.exit(0); } } } public static void main(String[] args) { processPrm(args); System.out.println("Logging data for [" + boardID + "], every " + Long.toString(waitTime / 1000) + " s."); final NumberFormat NF = new DecimalFormat("##00.00"); AdafruitBMP180 bmpSensor = new AdafruitBMP180(); float press = 0; float temp = 0; double alt = 0; AdafruitHTU21DF humSensor = new AdafruitHTU21DF(); float hum = 0; try { if (!humSensor.begin()) { System.out.println("Sensor not found!"); System.exit(1); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("\nBye now."); } }); while (true) { try { press = bmpSensor.readPressure(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } bmpSensor.setStandardSeaLevelPressure((int)press); // As we ARE at the sea level (in San Francisco). try { alt = bmpSensor.readAltitude(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { temp = bmpSensor.readTemperature(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { hum = humSensor.readHumidity(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } System.out.println("At " + new Date().toString()); System.out.println("Temperature: " + NF.format(temp) + " C"); System.out.println("Pressure : " + NF.format(press / 100) + " hPa"); System.out.println("Altitude : " + NF.format(alt) + " m"); System.out.println("Humidity : " + NF.format(hum) + " %"); // Log here try { String url = LOGGER_URL + "?board=" + boardID + "&session=" + sessionID + "&sensor=" + BMP_SENSOR_ID + "&type=" + TEMPERATURE + "&data=" + NF.format(temp); String response = HTTPClient.getContent(url); JSONObject json = new JSONObject(response); System.out.println("Returned\n" + json.toString(2)); try { Thread.sleep(1000); } catch (Exception ex) { ex.printStackTrace(); } // To avoid duplicate PK url = LOGGER_URL + "?board=" + boardID + "&session=" + sessionID + "&sensor=" + BMP_SENSOR_ID + "&type=" + PRESSURE + "&data=" + NF.format(press / 100); response = HTTPClient.getContent(url); json = new JSONObject(response); System.out.println("Returned\n" + json.toString(2)); try { Thread.sleep(1000); } catch (Exception ex) { ex.printStackTrace(); } // To avoid duplicate PK url = LOGGER_URL + "?board=" + boardID + "&session=" + sessionID + "&sensor=" + HUM_SENSOR_ID + "&type=" + HUMIDITY + "&data=" + NF.format(hum); response = HTTPClient.getContent(url); json = new JSONObject(response); System.out.println("Returned\n" + json.toString(2)); } catch (Exception ex) { ex.printStackTrace(); } waitfor(waitTime); } } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/log/net/WeatherDataLogging.java
Java
mit
6,219
package raspisamples; 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; import raspisamples.pwm.PWMPin; public class RealPWMLed { 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 { final GpioController gpio = GpioFactory.getInstance(); PWMPin pin = new PWMPin(RaspiPin.GPIO_01, "OneLED", PinState.LOW); pin.low(); // Useless System.out.println("PWM, glowing up and down"); // PWM pin.emitPWM(0); Thread.sleep(1000); for (int vol=0; vol<100; vol++) { pin.adjustPWMVolume(vol); Thread.sleep(10); } for (int vol=100; vol>=0; vol--) { pin.adjustPWMVolume(vol); Thread.sleep(10); } System.out.println("Enter \"S\" or \"quit\" to stop, or a volume [0..100]"); boolean go = true; while (go) { String userInput = userInput("Volume > "); if ("S".equalsIgnoreCase(userInput) || "quit".equalsIgnoreCase(userInput)) go = false; else { try { int vol = Integer.parseInt(userInput); pin.adjustPWMVolume(vol); } catch (NumberFormatException nfe) { System.out.println(nfe.toString()); } } } pin.stopPWM(); Thread.sleep(1000); // Last blink System.out.println("Bye-bye"); pin.low(); Thread.sleep(500); pin.high(); Thread.sleep(500); pin.low(); gpio.shutdown(); } private static void waitFor(long ms) { try { Thread.sleep(ms); } catch (InterruptedException ie) { ie.printStackTrace(); } } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/RealPWMLed.java
Java
mit
2,351
package raspisamples; import raspisamples.adc.JoyStick; import raspisamples.adc.JoyStickClient; import raspisamples.servo.StandardServo; /* * Joystick read with ADC (MCP3008) * 2 Servos (UP/LR) */ public class JoyStickAndServos { private static StandardServo ss1 = null, ss2 = null; private static JoyStick joyStick = null; public static void main(String[] args) { ss1 = new StandardServo(13); // 13 : Address on the board (1..15) ss2 = new StandardServo(15); // 15 : Address on the board (1..15) ss1.stop(); ss2.stop(); JoyStickClient jsc = new JoyStickClient() { @Override public void setUD(int v) // 0..100 { float angle = (float)(v - 50) * (9f / 5f); ss1.setAngle(angle); // -90..+90 } @Override public void setLR(int v) // 0..100 { float angle = (float)(v - 50) * (9f / 5f); ss2.setAngle(angle); // -90..+90 } }; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { ss1.stop(); ss2.stop(); System.out.println("\nBye (Ctrl+C)"); } }); try { joyStick = new JoyStick(jsc); } catch (Exception e) { e.printStackTrace(); } finally { ss1.stop(); ss2.stop(); System.out.println("Bye"); } } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/JoyStickAndServos.java
Java
mit
1,408
package raspisamples; import java.io.InputStream; import java.net.URI; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import org.json.JSONObject; import raspisamples.servo.StandardServo; /* * Driven by WerbSocket server * See in node/server.js * * 2 Servos (UP/LR) */ public class PanTiltWebSocket { private static StandardServo ssUD = null, ssLR = null; private static WebSocketClient webSocketClient = null; public static void main(String[] args) throws Exception { ssUD = new StandardServo(14); // 14 : Address on the board (1..15) ssLR = new StandardServo(15); // 15 : Address on the board (1..15) // Init/Reset ssUD.stop(); ssLR.stop(); ssUD.setAngle(0f); ssLR.setAngle(0f); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { close(); } }); StandardServo.waitfor(2000); String wsUri = System.getProperty("ws.uri", "ws://localhost:9876/"); initWebSocketConnection(wsUri); } private static 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:" + string); JSONObject message = new JSONObject(string); JSONObject leapmotion = new JSONObject(message.getJSONObject("data").getString("text")); int roll = leapmotion.getInt("roll"); int pitch = leapmotion.getInt("pitch"); int yaw = leapmotion.getInt("yaw"); System.out.println("Roll:" + roll + ", pitch:" + pitch + ", yaw:" + yaw); ssLR.setAngle(yaw); ssUD.setAngle(-roll); // Actually pitch... } @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 close() { System.out.println("\nExiting..."); webSocketClient.close(); // Reset to 0,0 before shutting down. ssUD.setAngle(0f); ssLR.setAngle(0f); StandardServo.waitfor(2000); ssUD.stop(); ssLR.stop(); System.out.println("Bye"); } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/PanTiltWebSocket.java
Java
mit
2,766
package raspisamples; 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; import raspisamples.pwm.PWMPin; public class Real4PWMLedV2 { 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 { final GpioController gpio = GpioFactory.getInstance(); final PWMPin pin00 = new PWMPin(RaspiPin.GPIO_00, "LED-One", PinState.HIGH); final PWMPin pin01 = new PWMPin(RaspiPin.GPIO_01, "LED-Two", PinState.HIGH); final PWMPin pin02 = new PWMPin(RaspiPin.GPIO_02, "LED-Three", PinState.HIGH); final PWMPin pin03 = new PWMPin(RaspiPin.GPIO_03, "LED-Four", PinState.HIGH); System.out.println("Ready..."); Thread.sleep(1000); pin00.emitPWM(0); pin01.emitPWM(0); pin02.emitPWM(0); pin03.emitPWM(0); boolean go = true; while (go) { Thread one = new Thread() { public void run() { for (int vol=0; vol<100; vol++) { pin00.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin00.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } System.out.println("Thread One finishing"); } }; Thread two = new Thread() { public void run() { for (int vol=100; vol>0; vol--) { pin01.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } for (int vol=0; vol<=100; vol++) { pin01.adjustPWMVolume(vol); try { Thread.sleep(10); } catch (Exception ex) {} } System.out.println("Thread Two finishing"); } }; Thread three = new Thread() { public void run() { for (int vol=0; vol<100; vol++) { pin02.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin02.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=0; vol<100; vol++) { pin02.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=100; vol>=0; vol--) { pin02.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } System.out.println("Thread Three finishing"); } }; Thread four = new Thread() { public void run() { for (int vol=100; vol>0; vol--) { pin03.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=0; vol<=100; vol++) { pin03.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=100; vol>0; vol--) { pin03.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } for (int vol=0; vol<=100; vol++) { pin03.adjustPWMVolume(vol); try { Thread.sleep(5); } catch (Exception ex) {} } System.out.println("Thread Four finishing"); } }; one.start(); two.start(); three.start(); four.start(); String usr = userInput("Again y|n ? > "); if (!"Y".equalsIgnoreCase(usr)) go = false; } pin00.stopPWM(); pin01.stopPWM(); pin02.stopPWM(); pin03.stopPWM(); Thread.sleep(1000); // Last blink System.out.println("Bye-bye"); pin00.low(); Thread.sleep(500); pin00.high(); Thread.sleep(500); pin00.low(); gpio.shutdown(); } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/Real4PWMLedV2.java
Java
mit
4,816
package raspisamples.pwm; 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 PWMLedTestOne { 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, "OneLED", PinState.HIGH); System.out.println("--> GPIO state should be: ON"); Thread.sleep(1000); // turn off gpio pin #01 pin.low(); System.out.println("--> GPIO state should be: OFF"); if (false) { Thread.sleep(1000); // toggle the current state of gpio pin #01 (should turn on) pin.toggle(); System.out.println("--> GPIO state should be: ON"); Thread.sleep(1000); // toggle the current state of gpio pin #01 (should turn off) pin.toggle(); System.out.println("--> GPIO state should be: OFF"); Thread.sleep(2000); // 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 pin.low(); long before = System.currentTimeMillis(); for (int i=0; i<10000; i++) { pin.high(); pin.low(); } long after = System.currentTimeMillis(); System.out.println("10000 switches took " + Long.toString(after - before) + " ms."); } System.out.println("PWM!!!"); // PWM int threshold = 25; int nbLoop = 5; for (int pwmValueOn=1; pwmValueOn<threshold; pwmValueOn++) { System.out.println("PWM " + pwmValueOn); for (int i=0; i<nbLoop; i++) { pin.pulse(pwmValueOn, true); // set second argument to 'true' use a blocking call // waitFor(pwmValueOn); pin.low(); waitFor(threshold - pwmValueOn); } // Thread.sleep(500); } for (int pwmValueOn=threshold; pwmValueOn>0; pwmValueOn--) { System.out.println("PWM " + pwmValueOn); for (int i=0; i<nbLoop; i++) { pin.pulse(pwmValueOn, true); // set second argument to 'true' use a blocking call // waitFor(pwmValueOn); pin.low(); waitFor(threshold - pwmValueOn); } // Thread.sleep(500); } // 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(); } private static void waitFor(long ms) { try { Thread.sleep(ms); } catch (InterruptedException ie) { ie.printStackTrace(); } } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/pwm/PWMLedTestOne.java
Java
mit
2,997
package raspisamples.pwm; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; public class PWMPin extends GPIOPinAdapter { // 30 seems to be the maximum value. You can really see the led blinking beyond that. private final static int CYCLE_WIDTH = 30; private final Thread mainThread; private final boolean debug = "true".equals(System.getProperty("debug", "false")); public PWMPin(Pin p, String name, PinState originalState) { super(p, name, originalState); mainThread = Thread.currentThread(); } private boolean emittingPWM = false; private int pwmVolume = 0; // [0..CYCLE_WIDTH], percent / (100 / CYCLE_WIDTH); public void emitPWM(final int percent) { if (percent < 0 || percent > 100) throw new IllegalArgumentException("Percent MUST be in [0, 100], not [" + percent + "]"); if (debug) System.out.println("Volume:" + percentToVolume(percent) + "/" + CYCLE_WIDTH); Thread pwmThread = new Thread() { public void run() { emittingPWM = true; pwmVolume = percentToVolume(percent); while (emittingPWM) { if (pwmVolume > 0) pin.pulse(pwmVolume, true); // set second argument to 'true' makes a blocking call pin.low(); waitFor(CYCLE_WIDTH - pwmVolume); // Wait for the rest of the cycle } System.out.println("Stopping PWM"); // Notify the ones waiting for this thread to end synchronized (mainThread) { mainThread.notify(); } } }; pwmThread.start(); } /** * return a number in [0..CYCLE_WIDTH] * @param percent in [0..100] * @return */ private int percentToVolume(int percent) { if (percent < 0 || percent > 100) throw new IllegalArgumentException("Percent MUST be in [0, 100], not [" + percent + "]"); return percent / (100 / CYCLE_WIDTH); } public void adjustPWMVolume(int percent) { if (percent < 0 || percent > 100) throw new IllegalArgumentException("Percent MUST be in [0, 100], not [" + percent + "]"); pwmVolume = percentToVolume(percent); } public boolean isPWMing() { return emittingPWM; } public void stopPWM() { emittingPWM = false; synchronized (mainThread) { try { mainThread.wait(); } catch (InterruptedException ie) { System.out.println(ie.toString()); } } pin.low(); } private void waitFor(long ms) { if (ms <= 0) return; try { Thread.sleep(ms); } catch (InterruptedException ie) { ie.printStackTrace(); } } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/pwm/PWMPin.java
Java
mit
2,658
package raspisamples.pwm; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.GpioPinShutdown; import com.pi4j.io.gpio.GpioProvider; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinMode; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.PinState; import java.util.Map; import java.util.concurrent.Future; public class GPIOPinAdapter implements GpioPinDigitalOutput { protected final GpioController gpio = GpioFactory.getInstance(); protected final GpioPinDigitalOutput pin; public GPIOPinAdapter(Pin p, String name, PinState originalState) { super(); pin = gpio.provisionDigitalOutputPin(p, name, originalState); } @Override public void high() { pin.high(); } @Override public void low() { pin.low(); } @Override public void toggle() { pin.toggle(); } @Override public Future<?> blink(long delay) { return pin.blink(delay); } @Override public Future<?> blink(long delay, PinState blinkState) { return pin.blink(delay, blinkState); } @Override public Future<?> blink(long delay, long duration) { return pin.blink(delay, duration); } @Override public Future<?> blink(long delay, long duration, PinState blinkState) { return pin.blink(delay, duration, blinkState); } @Override public Future<?> pulse(long duration) { return pin.pulse(duration); } @Override public Future<?> pulse(long duration, boolean blocking) { return pin.pulse(duration, blocking); } @Override public Future<?> pulse(long duration, PinState pulseState) { return pin.pulse(duration, pulseState); } @Override public Future<?> pulse(long duration, PinState pulseState, boolean blocking) { return pin.pulse(duration, pulseState, blocking); } @Override public void setState(PinState state) { pin.setState(state); } @Override public void setState(boolean state) { pin.setState(state); } @Override public boolean isHigh() { return pin.isHigh(); } @Override public boolean isLow() { return pin.isLow(); } @Override public PinState getState() { return pin.getState(); } @Override public boolean isState(PinState state) { return pin.isState(state); } @Override public GpioProvider getProvider() { return pin.getProvider(); } @Override public Pin getPin() { return pin.getPin(); } @Override public void setName(String name) { pin.setName(name); } @Override public String getName() { return pin.getName(); } @Override public void setTag(Object tag) { pin.setTag(tag); } @Override public Object getTag() { return pin.getTag(); } @Override public void setProperty(String key, String value) { pin.setProperty(key, value); } @Override public boolean hasProperty(String key) { return pin.hasProperty(key); } @Override public String getProperty(String key) { return pin.getProperty(key); } @Override public String getProperty(String key, String defaultValue) { return pin.getProperty(key, defaultValue); } @Override public Map<String, String> getProperties() { // return Collections.emptyMap(); return pin.getProperties(); } @Override public void removeProperty(String key) { pin.removeProperty(key); } @Override public void clearProperties() { pin.clearProperties(); } @Override public void export(PinMode mode) { pin.export(mode); } @Override public void unexport() { pin.unexport(); } @Override public boolean isExported() { return pin.isExported(); } @Override public void setMode(PinMode mode) { pin.setMode(mode); } @Override public PinMode getMode() { return pin.getMode(); } @Override public boolean isMode(PinMode mode) { return pin.isMode(mode); } @Override public void setPullResistance(PinPullResistance resistance) { pin.setPullResistance(resistance); } @Override public PinPullResistance getPullResistance() { return pin.getPullResistance(); } @Override public boolean isPullResistance(PinPullResistance resistance) { return pin.isPullResistance(resistance); } @Override public GpioPinShutdown getShutdownOptions() { return pin.getShutdownOptions(); } @Override public void setShutdownOptions(GpioPinShutdown options) { pin.setShutdownOptions(options); } @Override public void setShutdownOptions(Boolean unexport) { pin.setShutdownOptions(unexport); } @Override public void setShutdownOptions(Boolean unexport, PinState state) { pin.setShutdownOptions(unexport, state); } @Override public void setShutdownOptions(Boolean unexport, PinState state, PinPullResistance resistance) { pin.setShutdownOptions(unexport, state, resistance); } @Override public void setShutdownOptions(Boolean unexport, PinState state, PinPullResistance resistance, PinMode mode) { pin.setShutdownOptions(unexport, state, resistance, mode); } }
12nosanshiro-pi4j-sample
RasPISamples/src/raspisamples/pwm/GPIOPinAdapter.java
Java
mit
5,216
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # sudo java -cp $CP raspisamples.wp.WiringPiSoftPWMExample
12nosanshiro-pi4j-sample
RasPISamples/wiring
Shell
mit
217
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # sudo $JAVA_HOME/bin/java -cp $CP raspisamples.Real4PWMLedV2
12nosanshiro-pi4j-sample
RasPISamples/pwmled.04
Shell
mit
220
#!/bin/bash PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/json.jar CP=$CP:./lib/java_websocket.jar # sudo java -cp $CP raspisamples.PanTiltWebSocket
12nosanshiro-pi4j-sample
RasPISamples/pantilt.ws
Shell
mit
260
# Joystick # #!/bin/bash PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:../ADC/classes #CP=$CP:../SevenSegDisplay/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # sudo java -cp $CP -Dverbose=true raspisamples.PanTiltJoyStick
12nosanshiro-pi4j-sample
RasPISamples/pantilt.js
JavaScript
mit
290
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes # CP=$CP:../SevenSegDisplay/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # CP=$CP:./lib/json.jar # sudo java -cp $CP raspisamples.log.net.WeatherDataLogging $*
12nosanshiro-pi4j-sample
RasPISamples/weather.logger
Shell
mit
281
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # sudo java -cp $CP raspisamples.wp.WiringPiSoftPWM3ColorLed
12nosanshiro-pi4j-sample
RasPISamples/wiring3color
Shell
mit
219