Categories
3D Printing Design Engineering

Magnetic Induction Flashlight

Completed Flashlight

My most recent project has been designing and creating a magnetic induction flashlight. A magnetic induction flashlight is a magnet / human powered circuit. It is also known as a “linear induction”, “shake light”, or a “Faraday flashlight”.

The parts are 3D printed, which include an inner housing, a outer shell, and an end cap. The inner housing is where the coil of wire, magnet, PCB board, electrical components, and LED reside. The shell holds the switch, and the end cap is what holds the inner housing in.

The inner housing was modeled from an induction flashlight in which I disassembled to learn how it worked. I modified the design, changing over 30% of it such as the size, a completely new shell, and minute details, including the length of the coil – which gives it more charge. I also designed a new circuit and circuit board, and included a rechargeable battery.

Parts list:

  • LED Super bright 10mm (Jameco: 2205341)
  • NiMH 3.6v (Jameco: 2137473)
  • Diodes (x4)
  • SPST Mini rocker switch (Jameco: 2208198)
  • Neodymium magnet 9/16″ x 3/4″ (K&J: D9C)
  • 30 AWG Magnet wire (Jameco: 2119363)
  • M2 (x4-6) – Female threaded heat sinks.
  • M2 (x4-6) – Screws

To create one, first print the shell, cap, and inner housing, either yourself (if you have a 3D printer) or from a 3D printing service such as makexyz or through thingiverse. The print material is PLA. Download the 3D artwork here.

3D printed flashlight parts.

With the the zipped PCB artwork included here, order a circuit board through Osh Park or from a prototype circuit board making company. Alternatively, you could get a prototyping board from Jameco or Sparkfun, and design the board yourself.

Wind the coil.

Winding the coil.

I think I drew the schematic correctly, however, make sure to check your polarities before soldering.

Circuit schematic.

When the prototype arrives, solder your electrical components to your board.

The circuit board.
Getting the circuit board ready to solder.

Because screws don’t work so well with PLA, heat sink the female threaded inserts into the holes.

Heat insets.
Heat insets on printed inner flashlight.
Heat insets in the shell.

Next, assemble the flashlight and it should be complete.

Assembling the flashlight.

More info on how this flashlight works: K&J Magnetics or How Shake Flashlights Work

Note: This information, project, the flashlight, and designs are for educational purposes only.

Categories
Art Photography

Sunset / Sunrise

Categories
Nature Photography

Costa

Pacific ocean wave.
Bird: Blue Heron, Garcia Azul
Swimming hole under a bridge.
Categories
Nature Photography

Brazos

Categories
Web Development

Authentication Simplified with AWS Cognito

It took a while for me to find info on how to practically implement web application authentication. Turns out it is really simple to do with AWS Cognito. What Cognito does is authenticates to a pool of (email or SMS confirmed) users and sends back a JWT (Javascript Web Token) once authenticated.

This post will function as an “essential” guide to Cognito. I’ll include the least amount of code as possible for authentication to occur in a web application with just an email address and password. You could find more detailed info at this AWS tutorial (The tutorial is what the following code is vanilla-fied from.).

First off download and include the AWS SDK and NPM SDK in an HTML page.

Then log into AWS Cognito and create a user pool. Use the defaults. Check: “Also allow sign in with verified email address”. Add an app client. Uncheck: “Generate client secret”. Start up your JS and include relevant fields.

_Cognito = {
    cognito: {
        userPoolId: '',// e.g. us-west-2_abcde3fghij
        userPoolClientId: '', // e.g. 12abcde3fgh4ijklmn5
        region: '' // e.g. us-west-2
    }
};

var Cognito = {};

var poolData = {
    UserPoolId: _Cognito.cognito.userPoolId,
    ClientId: _Cognito.cognito.userPoolClientId
};

var userPool; 

userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

Now the SDK is available to use. Let’s register a user.

function register(email, password, onSuccess, onFailure) {
    var dataEmail = {
        Name: 'email',
        Value: email
    };
    var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);

    userPool.signUp(email, password, [attributeEmail], null,
        function signUpCallback(err, result) {
            if (!err) {
                onSuccess(result);
            } else {
                onFailure(err);
            }
        }
    );
}

 if (document.readyState == 'loading'){
   document.addEventListener("DOMContentLoaded", function(){ 
     document.querySelector('#registrationForm').addEventListener('submit', handleRegister); 
   });
}

function handleRegister(event) {
    var email = document.querySelector('#emailInputRegister').value;
    var password = document.querySelector('#passwordInputRegister').value;

    var onSuccess = function registerSuccess(result) {
        var cognitoUser = result.user;
        console.log('user name is ' + cognitoUser.getUsername());
        var confirmation = ('Registration successful. Please check your email inbox or spam folder for your verification code.');
        if (confirmation) {
            //Go to verification page;
        }
    };
    var onFailure = function registerFailure(err) {
        alert(err);
    };
    event.preventDefault(); 
    register(email, password, onSuccess, onFailure); 
}

An email will be sent to the user that includes a verification code. With that you’ll verify the user.

function verify(email, code, onSuccess, onFailure) {
    createCognitoUser(email).confirmRegistration(code, true, function confirmCallback(err, result) {
        if (!err) {
            onSuccess(result);
        } else {
            onFailure(err);
        }
    });
}

if (document.readyState == 'loading'){
   document.addEventListener("DOMContentLoaded", function(){ 
     document.querySelector('#verifyForm').addEventListener('submit', handleVerify);
   });
}

function handleVerify(event) {
    var email = document.querySelector('#emailInputVerify').value;
    var code = document.querySelector('#codeInputVerify').value;
    event.preventDefault();
    verify(email, code,
        function verifySuccess(result) {
            console.log('call result: ' + result);
            console.log('Successfully verified');
            alert('Verification successful.');
        },
        function verifyError(err) {
            alert(err);
        }
    );
}

To sign in:

if (document.readyState == 'loading'){
   document.addEventListener("DOMContentLoaded", function(){
     document.querySelector('#signinForm').addEventListener('submit', handleSignin); 
   });

}

function signin(email, password, onSuccess, onFailure) {
    var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({
        Username: email,
        Password: password
    });

    var cognitoUser = createCognitoUser(email);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: onSuccess,
        onFailure: onFailure
    });
}

function handleSignin(event) {
    var email = document.querySelector('#emailInputSignin').value;
    var password = document.querySelector('#passwordInputSignin').value;
    event.preventDefault();
    signin(email, password,
        function signinSuccess() {
            console.log('Successfully Logged In'); 
        },
        function signinError(err) {
            alert(err);
        }
    );
}

Here we will get the token. You could see what the token consists of at JWT.io.

let user = userPool.getCurrentUser();

if (user){
    user.getSession(function sessionCallback(err, session){
        if (err) {
           //Nada session info.
        } else {
           //JWT
           console.log(session.getIdToken().getJwtToken());
        }
});
}

To sign out:

Cognito.signOut = function signOut() {
    userPool.getCurrentUser().signOut();
};

if (document.readyState == 'loading'){
      document.addEventListener("DOMContentLoaded", function(){ 
        document.querySelector('#signOut').addEventListener('click', function() {
            Cognito.signOut();
            alert("You have been signed out.");
          })
        })
      }

That’s the gist of authentication with Cognito. I’ve included a working example.

Categories
Renewable energy

Net Zero Carbon Emissions

After hearing about the global protest against inaction on climate change, I decided to look into the topic of net zero carbon emissions.

Essentially, the goal of net zero carbon emissions would be met through using only renewable energy production such as solar and wind power.

It just makes sense, clean energy is the future.

In my opinion, a smart start to implementation of net zero carbon emissions might include a push towards a residential solar energy plan throughout the nation and world. This plan might make residential *grid-connected* solar systems extra-affordable through incentives and credits.

Commercial incentives or tax breaks might be an extra reason to switch to renewable energy. Amazon’s pledge to go renewable or Walmart’s sustainability goal could serve as a model for other commercial entities.

Net zero carbon emissions for the individual household or commercial entity is possible, so it is reasonable to take the steps to make a cleaner earth and air. Our future has spoken.

Categories
Daily Living This and That

An Apprenticeship

I’ve tried it before: the electrician’s apprenticeship. I had to travel and it was too much travel for me so I chose not to continue. Now it’s different. I’m going to give it another try. I’m going to ask if it’s possible to stay in town during, at least the beginning of, the apprenticeship. To me it makes sense: decent pay and learning on the job. The work is, sort of awesome, and there is a lot to learn. Let’s see how it goes.

Categories
Geology Photography

Bisti

Bisti
Categories
Web Development

An ES6 Web Application

Overview

Most, it seems, of the code for my most recent web application has been written. There surely is room for improvement with this project, and it is (mostly) functioning how it should be. In this post I’ll be writing about the code techniques I used, provide an overview of the application, and I will also go over areas in which I could improve the application.

It is a simple input and output program with a database on the backend. The program is all written on the frontend, which I found to be very convenient. (All JS.) It’s a simple architecture while using the NoSQL database.

The NoSQL database is called Couch and I used a JS library called Pouch. My only question, while using this architecture is “Why aren’t more people designing their programs with these frameworks!?”

I used ES6 (or newer – and some older) coding techniques. My overall program is structured like this:

//Global and helper functions

class Model{
//Templates go here.
}

class View{
//User interface code goes here.
}

class Auth{
//Authentication goes here.
}

let auth = new Auth();
let model = new Model();
let view = new View();

There is an authentication layer which accesses the database with a login and logout feature. Couchdb is cookie authenticated so the user could stay logged in even during page reloads and navigation.

The view class was composed of mostly methods that managed the logic of the view.

class View {
    constructor(){
    }
    newItem(){
       //Adds a new item.
    }
    editItem(){
       //Edits the item.
    }
    deleteItem(){
       //Deletes item.
    }
}

Techniques

For the HTML templates I used ES6 template strings. They really open up a lot of possibilities with their usage.

class Model(){
    constructor(){}
    template = (data) => {
      return `
          <ul><li>${data}</li></ul>
      `;
    }
}

A feature that became especially useful is Array.map. Before discovering this function, I was using an if…then to “iterate” through the data.

if (data.item[0]){
    doThis(data.item[0]);
} else if (data.item[0] && data.item[1]){
    doThis(data.item[1]);
}// ... etc.

Needless to say that there are more efficient ways of iterating through an array. Array.map to the rescue! It is similar to Array.forEach except returns a duplicate of the modified array instead of modifying the original array. And remember to use the .join to connect each iteration with an empty space instead of including the array’s commas.

class Model{
    constructor(){
    }
    template = (data) => {
      return data.map(function(value, index){
        return `<li>${value.item[index]}</li>`
      }).join('');
    }
}

Areas of Improvement

There could be many areas of improvement to this application though the most notable area is probably having to do with reloading the window location. There are times where location.reload seemed like the perfect solution, yet it wasn’t. It was a question of seemlessness and having to do more with UX (user experience). For example, after editing an item, I would have to manually reload for the items to display. How would one accomplish this without a manual reload? Use location.reload – or code in a “view items” function?

Conclusion

This was a fun project and I learned some new techniques to develop with. While I still have much to learn, this project turned into a functioning program, all with good ‘ole vanilla JS, a code library, and a JS friendly database! If you are creating a project with similar frameworks (or non-frameworks), I’d be happy to share knowledge! Thanks for taking the time to read this.

Categories
Nature Photography

Mountain Stream

Mountain stream.