Monday, December 14, 2015

Got a Round TUIT

UPDATED:

As previously posted, I just needed a Round TUIT.

I receive the replacement CDSH270 Diodes for my Antenna Tuner today, with a little work and with a TUIT they were installed. The Tuner now works as before.

While during the surgery on the tuner, I installed some sharp pointed spark gaps at the SO-239 connectors, and between the Balanced Line Terminals. Maybe they will help save the Diodes the next time I forget to disconnect the Antenna during the an Electric Storm.

For the spark gaps, I soldered one end of a heavy copper wire directly to the SO-239 RF center connector, and then bolted the other end directly to ground (at the connector mount point). After the "Short" was installed, I cut it at the center with dull side-cutters, leaving sharp points on each side. The gap was adjusted to about 1/20 of a inch. The same was done between the Balanced Terminals.

With another TUIT, I installed a 6 AWG ground wire to the Tuner, but waiting for a large spade lug to make the final connection. My available lugs are not big enough for 6 AWG.


Today was nice and sunny, so I also raised the Long Wire Antenna to it normal height. Yesterday when I was repairing it, it was too cold and wet to futz with it to bring it to full height at 90 feet AGL.
 
Two years ago I tried to work on the antenna, but could not get the 3/32 support line to slide back down the tree. I suspected it had "grown" into a limb, or was pitched into a warren slot. My friend Jeff - KO7M and I was able to pull together hard enough to finally break it free. To avoid the same problem again, I slipped the line into a 20 foot piece of 1/4 inch polypropylene ice-make tube. which we pulled up into the tree where the support line goes over the branches.  Now two years later the line was easy to pull down and then back up.

So far I have made a few SSB contacts with the current antenna configuration. Now I am anxious to work some WSPR - but another TUIT is in the way.

-- Home Page: https://WA0UWH.blogspot.com


Sunday, December 13, 2015

Some Antenna Work and Repair

UPDATED: Tue Dec 22 21:38:59 PST 2015

I removed the 9:1 BalBal from my Off-Center-Fed Long Wire Antenna, as described below, it did not work as well as expected. More testing and measurement needed.



There has been a lot of chatter on the local Yahoo pQRP email list about building some 9:1 Ununs as a group project. I already have the Toroids and Wire and had planned to make several of my own - I was just waiting for a Round-TUIT (TUIT).

For the last several (6 or so) years, I have been using a 300 foot Off-Center-Fed (OCF) Long Wire antenna. It is strung up near the top of some nice tall trees with the feed point at about 90 feet AGL. It has worked very well on all bands for WSPR, QRSS, CW, and general Ham use. The antenna is fed with 450 ohm ladder line fed from a Tuner with an internal Balun. I rarely have to provide much L or C adjustment for reasonable performance.

With a crippled antenna (see below), last night I worked Sandy - KG7FFP as she is new General License Ham - Good going Sandy! We were on 80m, 3.885MHz.

There are several things that I have wanted to try, to see if I could improve performance.

The first, is a no-brainer; Ground the Tuner and the Rig, something that has always been waiting for another TUIT.

The second, may be more controversial, I have wanted to put a 9:1 BalBal at the feed point of the OCF Long Wire.  With 450 ohms ladder line in, the output should approximate 4050 ohms, which I think would more closely match typical OCF Long Wire feed impedance. In my case the short end of the Long Wire is about 20 feet. The Feed Line drops straight into my Loft's window, across the celling to the Ham Rig, I think more impedance is desirable, in reality, I thing everything in close proximity becomes the antenna, that is; the long wire, feed line, metal roof, and the moss soaked wet-trees, and I don't think they are typically just 450 ohms  :-)

Another "nit" that I wanted to improve (or remove) is the "egg" insulator at the feed point. I have never really liked this centre point set up, but it is what I had when it was first installed. The new set up is a now a 14 inch long, 3/4 inch PVC (conduit) with three holes in each end. The antenna wire goes through a "Z" bend at each end of the conduit, then "V's" down to my new 9:1 BalBal, which is about 18 inch lower. The antenna wire is standard, solid copper 12 AWG conduit wire.

My antenna tuner is still in my eShop waiting replacement diodes (CDSH270), they are on order and should arrive soon.  The antenna and Tuner took a near hit during one of the last electric storms. I was near the radio and heard a snap or spark across the terminals or somewhere inside, the radio did not suffer any ill effects, the tuner TOOK it ALL.

So, now what?

My newly configured OCF Long Wire Antenna is now up and ready for use, but still waiting tuner repair.

I am expecting some VERY GOOD to EXCELLENT performance from this antenna configuration, because it was installed exactly as per the weather-man specification - that is, it was raining all the time I was outside working with; support lines, antenna wire, BalBal, and feed line. I got soaked ! Everyone knows, that the best antennas always go up during inclement weather.

But, time will tell, I will post my impressions, measurement, and results, when available.


-- Home Page: https://WA0UWH.blogspot.com


Saturday, December 12, 2015

More Fun with Cyclops Numbers

UPDATED:
Added Details and Links


I created a fun function to compute Cyclops Numbers, see previous post.



D=9; C=0; L=27; 
echo "obase=${D}+1;(${D}+1)^(2*${L}-1) -1 -(${D}-(${C}%${D}))*(${D}+1)^(${L}-1)" | bc

Where:
  • D = Is the side Digits, 1 to 9
  • C = Is the single Cyclops Eye Digit, must be < D, or C mod D will be used
  • L = The Cyclops Eye Location (width)

D=8; C=3; L=2; => 838
D=8; C=3; L=3; => 88388
D=8; C=3; L=4; => 8883888
D=4; C=8; L=5; => 444484444
D=9; C=0; L=6; => 99999099999

The results for the above function:

99999999999999999999999999099999999999999999999999999


It is all fun and games, until someone pokes the Cyclops Eye   :-)


-- Home Page: https://WA0UWH.blogspot.com


Wednesday, December 9, 2015

More Large Numbers

UPDATED:
Added Details and Links

Update: Jan 7, 2016 - New Largest Prime found: echo "2^74207281-1" | bc, which is 22 Million Digits, the function takes 77.25 minutes to compute on a 3.4GHz Processor. See, youtube at: https://goo.gl/C7ngE7

See previous post.

The largest known prime number is: 17,425,170 digits long, it can be computed with this very short function:

echo "2^57885161 -1" | bc

On my Workstation (2.2GHz) it takes about 82 minutes to compute, but with more than 17M digits, it takes much longer to display or print.

To print, it would require 7.7 Reams of paper; single sided, 80 character per line, 56 lines to a page, and 500 pages pre ream.

Note: The person that finds the "next" larger prime number will be famous.


-- Home Page: https://WA0UWH.blogspot.com


Large Numbers

UPDATED:
Added Details and LInks

As noted in previous posts, I am a fan of Large Numbers, I am especially interested in small functions that compute Large Numbers.

Recently I watched a Numberphile Youtube video, which captivated my interest. The numbers that I found most interesting are large "Cyclops Numbers".

The following Linux function will compute a large Cyclops:

echo "10^(2*253-1) -1 -9*10^(253-1)" | bc

Can you spot the Cyclops Eye?


99999999999999999999999999999999999999999999999999999999999999999999\
99999999999999999999999999999999999999999999999999999999999999999999\
99999999999999999999999999999999999999999999999999999999999999999999\
99999999999999999999999999999999999999999999999909999999999999999999\
99999999999999999999999999999999999999999999999999999999999999999999\
99999999999999999999999999999999999999999999999999999999999999999999\
99999999999999999999999999999999999999999999999999999999999999999999\
99999999999999999999999999999


-- Home Page: https://WA0UWH.blogspot.com


Tuesday, December 8, 2015

Email from Raspberry PI or the Esp8266

UPDATED:
Added Details and Links

If you have been following my recent blog post, I posted about using "curl" to send SMS messages to a Cell Phone Number, I have also created a software function to send a similar SMS messages from Esp8266, and/or using the same strategy this could be used on a Raspberry PI. The SMS messages are transferred to the "textbelt.com" Open SMS Gateway. Access is via a HTML URL post, or via a command line "curl" command which simulates a HTTP post. The textbelt.com server imposes some limits, that is; no more than 3 messages per 3 minutes, and no more than 75 messages per day from a single IPA.

The folks at Textbelt are gracious to allow us "small-time" users to access their gateway for FREE, - SPAMMERS  are not welcome.

But, if you want your Raspberry PI or Esp8266 to send an actual "email", that is another problem. Accessing an "Open" Simple Mail Transport Protocol Gateways (an SMTP) is normally a problem for most users. The reason an "Open" SMTP is desirable for our Internet-of-Things (IoT's) is that authentication is NOT required on Open SMTP's, and therefore there is NO need for a "clear text" password saved in a file, nor is it transferred over the Internet.

There are a few Open SMTP available, where services are purchased by SPAMMERS to do their thing. A few of these SMTP gateways allow low-volume users access to their services for FREE, with some restrictions.  I have tried several Open SMTP gateways, and found most have additional requirements that I did not agree, like; sign up with a credit card.

I am currently using "smtp2go.com" which has a FREE Option and does not require a credit card to sign up. For low volume users like myself, it has a limit of 25 emails per hour, and/or 1000 emails per month, - which is more than enough email for my IoT's to report status, and/or other reports to me via email.

I have implemented a Mail Transfer Agent (MTA) which "talks" to the Open SMTP to send my messages. Messages can be sent to my normal Gmail Account, or to my Cell Phone as an SMS text message, or to any other email address that I desire.

I have written complete MTA function for my use with my ERB-EspWebServer Farm, but provided just some excerpts here for discussion. At some point I will post the complete listing on my GitHub.

Sorry, I did not include the "set up", but I think the upper case "#define" are obvious.



// ###########################################################
//////////////////////////////////////////////////////////////
//
//
boolean
_MTA(WiFiClient client, String aStr, String aPat, unsigned long aTimeout)
{
    
    boolean myStatus = false;
         
    if (aStr.length() ) client.println(aStr);

    yield();

    // Wait For Response
    unsigned long ts = millis();
    while (true) {
        if ( ts + aTimeout < millis() ) {
           myStatus = false;
           break;
        }
        
        yield();
        #if (OPT_MONITOR_DEBUG_OUTPUT) > 0 
            DEBUG_INDENT; Serial.println(sE(" Waiting: ") + aPat + E(" . . . ") );
        #endif
        
        String line = client.readStringUntil('\n');
        
        #if (OPT_MONITOR_DEBUG_OUTPUT) > 0 
            DEBUG_INDENT; Serial.println(sE("  ") + line);
        #endif
        
        if(line.indexOf(aPat) >= 0) {
            myStatus = true;
            break;
        }
    }

    return myStatus;
}

// ###########################################################
//////////////////////////////////////////////////////////////
//
// Provides easy access to page via Email Gateway
//
boolean
eMTA( String aDomain   = MY_DEFAULT_NODE_DOMAIN,
      String aTo       = MY_DEFAULT_EMAIL_TO,
      String aFrom     = MY_DEFAULT_EMAIL_FROM,
      String aMesg     = MY_DEFAULT_EMAIL_MESSAGE,
      String aHost     = MY_DEFAULT_EMAIL_HOST,
         int aPort     = MY_DEFAULT_EMAIL_PORT )
{
    
    digitalWrite ( gBluLED, ON );
    
        #if (OPT_MONITOR_DEBUG_OUTPUT) > 0
            DEBUG_INC_INDENT; Serial.println ( E("Starting Email Client ...") );
        #endif
      
        boolean myStatus = false;
       
        #if (OPT_MONITOR_DEBUG_OUTPUT) > 0
            DEBUG_INDENT; Serial.println( sE(" Connecting to: ") + aHost );
        #endif
      
        // Use WiFiClient class to create TCP connections
        WiFiClient client;
        if (!client.connect(aHost.c_str(), aPort)) {
            #if (OPT_MONITOR_DEBUG_OUTPUT) > 0
                DEBUG_DEC_INDENT; Serial.println( E(" Connection Failed") );
            #endif
            myStatus = false;
        }
        else {
      
          // Wait for Client to Start Sending
            #if (OPT_MONITOR_DEBUG_OUTPUT) > 0 
                DEBUG_INDENT; Serial.println( E(" Waiting for Connection") );
            #endif

            // The MTA Exchange
            while(true) {
    
                if (_MTA(client, "",                          "220 ", 10*SECs ) == false) break;
                if (_MTA(client, "EHLO " + aDomain,           "250 ", 10*SECs ) == false) break;
                if (_MTA(client, "MAIL FROM:" + aFrom + "",   "250 ", 10*SECs ) == false) break;
                if (_MTA(client, "RCPT TO:" + aTo + "",       "250 ", 10*SECs ) == false) break;
                if (_MTA(client, "DATA",                      "354 ", 10*SECs ) == false) break;
                if (_MTA(client, aMesg + "\r\n.\r\n",         "250 ", 10*SECs ) == false) break;
    
                myStatus = true;
                break;

            }
            
            client.flush();
            client.stop();
            
            #if (OPT_MONITOR_DEBUG_OUTPUT) > 0
                if (myStatus == true) { 
                    DEBUG_DEC_INDENT; Serial.println( E(" Connection Closed Successfully") );
                }
                else { 
                    DEBUG_DEC_INDENT; Serial.println( E(" Connection Closed With Error") );
                }
            #endif

        }
         
    digitalWrite ( gBluLED, OFF );
    
    return myStatus;
  
}


As can be seen, the logic of the MTA is really very simple: send a message, and then wait for a response, repeat as necessary, stop on error or finished.

Note: For the Raspberry IP, this can be implemented as a Bash script, in fact the details for the above program were first worked out using a script on a Linux Workstations.  I will post the script later.

If you find this useful - leave a comment.


-- Home Page: https://WA0UWH.blogspot.com

Wednesday, December 2, 2015

Playing with Diffie Hellman

UPDATED:
Added Details and Links

Note: I am not a cryptographer, I just like playing with large numbers.

There are no secret information provided in this blog post, it is all available online, this is just my added two cents, take it for what it is worth.

The Diffie-Hellman Key Exchange method is used to share a "Secret Key" between two users, without sending the shared Secret Key across the network.

See: Google Diffie Hellman.

The idea is simple, and the maths can be simple:

k=<my secret number>
g=<a publicly shared number>
p=<a publicly shared large prime number>

A new Shared or Secret Key: G = (g ^ k) mod p

What can make it difficult and secure is that VERY large numbers can be used, and therefore making it very difficult for an observer (villain) to use brute force to discover the Shared Secret Key.

If you read the available documentation about Diffie Hellman Key Exchange, you will no doubt learn all about; Alice, Bob (the good guys), and Eve (the villain). I suggest it for some bed time reading.

Note: the online documentation suggest that Alice and Bob must first each know some public numbers for "g" and "p".

But, there is nothing preventing a proper and secure Key Exchange when Alice initiates the process by sending Bob three numbers; "g", "p" and "g2B" (g to Bob) values.

Bob would need to use these three values to compute the "Shared Secret Key".  Bob also returns to Alice a computed "g2A" (g to Alice), now Bob is finished, he now knows the Shared Secret Key. Alice will also know the Shared Secret Key when she completes her next calculation.

Alice uses the returned "g2A" value to compute the same "Shared Secret Key".

It looks like magic, but it is simple when you look at the maths with small numbers, and knowing:

g^(ab) mod p  ==  g^(ba) mod p

where: "a" is Alice's secret key ("kA"), and "b" is Bob's secret key ("kB").

See the online documentation.

You will also learn from online documents, that "p" should be a Large Prime Number, and "g" should be greater than "0", but less than "p", and "k" is a Secret Key that should NOT be shared.

Which is all good advice, if you are implementing a banking system, or saving the world via encrypted text messages. But the Diffie Hellman function works regardless of the numbers used, so in the examples below, some small and maybe inappropriate values are used.

What started my interested in Diffie Hellman Key exchange is the UNIX provided, and neat little and powerful, utility called "bc". The "bc" command can deal with VERY large numbers without difficulty.

An Example:

A Diffie Hallman Example, with small numbers.

Assume that Alice, Bob and Eve will know and/or use the following:

gP =16
pP = 101

As stated above, these numbers could be suggested by Alice or Bob, or both. Or, the numbers could be hard coded into a application that they both use. If large enough, the knowledge of these numbers does NOT detract from security.

Note: For this example, I will use the upper case "P" to denote a number is "Public", "pP" is normally prime. I will use "kA" for Alice secret key, and "kB" for Bob's secret key. Also, "g2B" and "g2A" are the computed exchanged values. Then finally, "gS" becomes the value of the "Shared Secret Key".

Note: "g2B" and "g2A" are just like other "g" values that can be used in the same Diffie Hellman formula.

Eve can eavesdrop on all of the network data exchanges between Alice and Bob, but will NOT be able to compute the Shared Secret Key, because Eve is not privy to Alice's or Bob's Secret Keys.

-----------------------

Alice's Secret Key, known only by her, is: kA = 7

Alice wants to Share a Secret Key with Bob.

Alice computes a: g2B = (gP ^ kA) mod pP with her key.

Alice will do this on UNIX system with the values above using the following command:

$ g2B=`echo "(16^7)%101" | bc`
g2B becomes 80

Alice can now send "qP", "pP" and "g2B" to Bob as clear text within an email (or whatever). Note: Eve may or can eavesdrop on the Internet traffic.

-----------------------

Bob's Secret Key, known only by him, is: kB = 11

Because Bob also uses a UNIX system, he computes from the values sent from Alice a value to be returned to Alice: g2A = (gP ^ kB) mod pP

$ g2A=`echo "(16^11)%101" | bc`
g2A becomes 71

Bob can now sends Alice "g2A", so she can complete her side of the key exchange.

Bob also can compute the "Shared Secret Key" as:  gS = (g2B ^ kB) mod pP

$ gS=`echo "(80^11)%101" | bc`
gS becomes  54

Bob is now finished, he knows the Shared Secret Key as "54".

-----------------------

With the value of "g2A" sent by Bob, Alice can complete her side of the exchange, by computing: gS = (g2A ^ kA) mod pP

$ gS=`echo "(71^7)%101" | bc`
gS becomes 54

Alice now finished, she knows the Shared Secret Key as "54".

-----------------------

Both Alice and Bob both know the same value of "gS", the Share Secret Key as "54".  Alice or Bob, could now use the Shared Secret Key to encrypt messages that hopefully only the opposite could decrypt.

Eve is left clueless.

-----------------------

But there is a flaw !

With small numbers, as used in this example, Eve could Brute Force a decryption solution, by trying all numbers starting with "0". In this case it will only take 54 iterations to find the correct Shared Secret Key that would successfully decrypt Alice's message. Eve could easily know (via eavesdropping) the value of "pP" is small, and therefore, can assume the Secret Key is some number between 0 and 101, which implies a brute force attack is warranted.

But Normally

Normally, the values of "gP", "pP", and the resulting "g2B" and "g2A" are VERY much larger numbers, maybe hundreds or thousands of digits.

Imagine what Eve prospects of having enough CPU horse power to attempt a sequential attack if "pP" is extremely large number -  prospects = none.

If "pP" is large enough, a brute force attack could take forever even with multiple very fast computers.

Some Experiments

Remember I said "bc" can deal with large numbers, well, to avoid "typing" a large number I will use exponentiation to generate some numbers for "qP" and "pP", for Alice try this:

$ gP="(3^456)"
$ pP="(2^4253-1)"  # A Large Prime Number
$ kA="12345"

$ time echo "${gP}^${kA} % ${pP}" | bc

On my 3.2GHz Workstation, this took about 6 minutes to compute, if necessary try shorten the lapse time, by changing Alice's key to "123".



$ gP="(3^456)"
$ pP="(2^4253-1)"
$ kA="12345"

$ time echo "${gP}^${kA} % ${pP}" | bc
80926261610442626577264521832490790161484618732554432140432039188058\
63206215275578738866144144831890725477013508191723348004478728927721\
95788786903156432412894232199564275068253627223471477034284902245829\
91421266442623706953457344345029183351048403313211524973218664085545\
87664348342026922029976056154815423683953094807171496683969416932115\
99132155230551185025739817346443301752666222054850477088018492513173\
91624760224393336362809726321106680382250456588357956381388166323729\
38771361918677860624224646340387910263769022858722611291936528412356\
03100668125135517222317410124988021081469568935461035793383680680665\
55390092789716566511778596204161424690071853937453863897083377508927\
67048039381017256779118656382146384480277810498377460548282809326731\
69234441684180112706844382298511472521071812891762065337050899792993\
70060526297317940169650082051030560624756658527561344770507458651702\
43716790444907248809569095106287466645236990947552803718232042574873\
11042448383261839081283910961519762548619655187688322601121778057413\
25524176872795543285574829694591574831681802471828336907766795593351\
38229222971475049624002124059810014875496597620324310354937668694220\
99070653730452586152318927155511512700751348007603716449001964877066\
01906432412801407287885578931224463376104843439581857726

real 5m48.432s
user 5m44.929s
sys 0m0.400s



The results is about 1200 digits for "g2B".


Stay tuned, more interesting "bc" observations to follow.


Me?, I just like very BIG numbers  :-)

-- Home Page: https://WA0UWH.blogspot.com

Monday, November 30, 2015

Esp8266 - Interactive SMS from the Web Page

UPDATE: Mon Nov 30 21:34:56 PST 2015
Added Links and Detail
Added RAW HTML listing

In the previous post I listed a code snippet that provides non-interactive SMS from the Esp8266. But sometime it is desirable to provide a simple interactive SMS interface for the Web User. An interactive SMS interface could be used to "page the SysAdmin" with the web user's supplied message.
Example Interactive Web SMS Interface
The interactive SMS interface is simple and requires only some HTML code to be inserted within a web page. Note: the previous post was a SMS method where user interaction was not needed nor desired.

Note: the Open SMS Gateway domain name that is used in the example is "textbelt.com", read their web page for details for Canadian and International use.

The following are excerpts from my ERB-EspWebServer.

Note: the RAW HTML code could be extracted from the example below and used with any Web Server.

The Setup:


// The Setup

    #define OPT_MONITOR_DEBUG_OUTPUT 1
   
    // ERB - Force format stings and string constants into FLASH Memory
    // I use E() as an Alias for F() so that DEBUG code can be inserted
    #define  E(x) F(x)
    // Used as an F() when being used as the first Element
    // of a Multi-Element Expression
    #define sE(x) String( F(x) )


// Defaults for Pager
    #define DEFAULT_PAGER_GATEWAY "textbelt.com"
    #define DEFAULT_PAGER_NUMBER  "202-555-1212"

    #define SYSTEM_ADMIN_PAGER_NUMBER DEFAULT_PAGER_NUMBER


Web Server Code Arduino Sketch Snippet:


    // Pager - User Interactive Web Interface
    sz += wprintln( E("\r\n<!-- Pager - User Interactive Web Interface -->") );
    sz += wprintln( E("<center>") );
    sz += wprintln( E("<hr width='75%' />") );

    sz += wprintln(sE("<form action="http://")
          + DEFAULT_PAGER_GATEWAY + E("/text method='POST' target='SMS_Report' >") );
       sz += wprintln( E("  <b>Page SysAdmin with </b>") );
       sz += wprintln(sE("  <input name='number' type='hidden' value='")
             + SYSTEM_ADMIN_PAGER_NUMBER + E("' />") );
       sz += wprintln( E("  <b>Message:</b>") );
       sz += wprintln(sE("  <input name='message' type='text' value='")
             + gDeviceName + E(": ' />") );
       sz += wprintln( E("  <input type='submit' value='GO' />") );
    sz += wprintln( E("</form>") );
    
    sz += wprintln( E("Or<br>") );
    
    sz += wprintln(sE("<form action="http://")
          + DEFAULT_PAGER_GATEWAY + E("/text method='POST' target='SMS_Report' >") );
       sz += wprintln( E("  <b>SMS Number:</b>") );
       sz += wprintln( E("  <input name='number' type='tel' />") );
       sz += wprintln( E("  <b>Message:</b>") );
       sz += wprintln(sE("  <input name='message' type='text' value='")
             + gDeviceName + E(": ' />") );
       sz += wprintln( E("  <input type='submit' value='GO' />") );
    sz += wprintln( E("</form>") );

    sz += wprintln( E("</center>") );


Note: I use my own custom "wprintln" function within the above example, modify as necessary.

For reference and to make things simple, I have extracted just the HTML from the above Sketch, as shown below.

HTML:


<!-- Pager - User Interactive Web Interface -->
<center>
<hr width='75%'>

<form method='POST' action='http://textbelt.com/text' target='SMS_Report' >
  <b>Page SysAdmin with </b>
  <input type='hidden' name='number' value='202-555-1212' />
  <b>Message:</b>
  <input type='text' name='message' value='Nod129: ' />
  <input type='submit' value='GO' />
</form>

Or<br>

<form method='POST' action='http://textbelt.com/text' target='SMS_Report' >
  <b>SMS Number:</b>
  <input type='tel' name='number' />
  <b>Message:</b>
  <input type='text' name='message' value='Nod129: ' />
  <input type='submit' value='GO' />
</form>

</center>


If you find this useful, leave a comment.

-- Home Page: https://WA0UWH.blogspot.com
 

Sunday, November 29, 2015

Esp8266 - with SMS

UPDATE: Sun Nov 29 22:14:04 PST 2015
Added details and Links


For my Esp8266 I wanted a easy way to send to my Cell Phone an SMS message.

For example: On a normal computers (Workstations and Raspberry PI) it is a simple mater of using "curl" to access an Open SMS Gateway (see previous post). I used this feature to report simple things like "reboot" and "backup finished" messages.

One such Open SMS Gateway is "textbelt.com", which is the one that I use. But, recently they were "black listed" by some of the Phone Carriers (my carrier) for abuse, apparently there was too much illegal traffic by the Gateway's users.

Textbelt has recently fixed the abuse and their Gateways is up and running again, or at least for my carrier.

For the Exp8266, I have created some functions that implements the "curl" protocol, (the heavy lifting), so now paging to my Cell Phone is a snap.

I am providing the functions here as just application snippets, hopefully you find them useful. I will put this in my ERB-EspWebServer GitHub (eventually).

The Setup:



// The Setup

    #define OPT_MONITOR_DEBUG_OUTPUT 1
   
    // ERB - Force format stings and string constants into FLASH Memory
    // USE WITH CAUTION !
    // I use E() as an Alias for F() so that DEBUG code can be inserted
    #define  E(x) F(x)
    // Used as an F() when being used as the first Element of a Multi-Element Expression
    #define sE(x) String( F(x) )

// Defaults for Pager
    #define DEFAULT_PAGE_GATEWAY "textbelt.com"
    #define DEFAULT_PAGE_PORT     80
    #define DEFAULT_PAGE_NUMBER  "202-555-1212"
    #define DEFAULT_PAGE_MESSAGE "Test"

    boolean gPageStnReady = false;



The Functions:



// Pager

// ###########################################################
//////////////////////////////////////////////////////////////
//
// Provides easy access to page via SMS Gateway
//
boolean
//ICACHE_FLASH_ATTR
page( String aMesgText = DEFAULT_PAGE_MESSAGE,
      String aNumber   = DEFAULT_PAGE_NUMBER,
      String aHost     = DEFAULT_PAGE_GATEWAY,
         int aPort     = DEFAULT_PAGE_PORT )
{
    
    digitalWrite ( gBluLED, ON );
    
        #if (OPT_MONITOR_DEBUG_OUTPUT) > 0
            Serial.println ( );
            Serial.println ( E("Starting Pager Client ...") );
        #endif
        
        String timeUTCBuf = "";
        
        String mesgTextHeader = String(gDeviceName)
            + E(": ")
            + String(gRev)
            + E(", ")
            + timeUTC(timeUTCBuf, gTimeZONE)
            + E(" - ");
    
        String mesg="number=" + aNumber
               + "&message=" + mesgTextHeader + aMesgText ;
    
        #if (OPT_MONITOR_DEBUG_OUTPUT) > 0
            Serial.println( sE("  Connecting to: ") + aHost );
        #endif
      
        // Use WiFiClient class to create TCP connections
        WiFiClient client;
        if (!client.connect(aHost.c_str(), aPort)) {
          #if (OPT_MONITOR_DEBUG_OUTPUT) > 0
              Serial.println("  Connection Failed");
          #endif
          return false;
        }
        
        #if (OPT_MONITOR_DEBUG_OUTPUT) > 0 
            Serial.println( sE("  MESG: ") + mesg );
        #endif
   
        // This will send the request to the server
        client.print( sE("POST /text/ HTTP/1.1\r\n")
                     + E("User-Agent: Esp8266/") + gRev + E("\r\n")
                     + E("Host: ") + aHost + E("\r\n")
                     + E("Accept: */*\r\n")
                     + E("Content-Length: ")
                     + String( mesg.length() ) + E("\r\n")
                     + E("Content-Type: application/x-www-form-urlencoded\r\n")
                     + E("\r\n")  // The Required Blank Line
                     + mesg + E("\r\n") );
    
        delay(10);

        // Wait for Client to Start Sending
        int i = 0;
        while( !client.available() ) {
          delay(10);
          if (i++ > 200) break;
        }
          
        // Read all the lines of the reply from server and print some to Serial
        boolean myStatus = false;
        while(client.available()){
          String line = client.readStringUntil('\n');
          if(line.indexOf("\"success\": true") >= 0) {
              myStatus = true;
          }
          #if (OPT_MONITOR_DEBUG_OUTPUT) > 0 
              if(line.indexOf("\"success\": ") >= 0 ||
                 line.indexOf("\"message\": ") >= 0
              ) Serial.println(line);
          #endif
        }
        
        client.flush();
        client.stop();
        #if (OPT_MONITOR_DEBUG_OUTPUT) > 0 
            Serial.println("  Connection Closed");
        #endif
         
    digitalWrite ( gBluLED, OFF );

    return myStatus;
  
}


// ###########################################################
//////////////////////////////////////////////////////////////
//
// Provides easy access to Pager via SMS Gateway
//
unsigned long gPageHoldOff = millis();
void
//ICACHE_FLASH_ATTR
pageOnStnReady() {
    
      if ( gPageHoldOff < millis() ) {
        
          gPageHoldOff = millis() + 1 * MINs;
        
          if ( gPageStnReady == false ) {
               gPageStnReady = page("Stn Ready");
          }
      }
  
    return;
  
}

// ###########################################################
// End


Let me know if you find this useful, leave a comment.

-- Home Page: https://WA0UWH.blogspot.com

Wednesday, November 25, 2015

Email sent from Raspberry PI

UPDATE:
Added details and Links

Sending Email from a Raspberry PI (or any typical Linux workstation) is NOT normally configured. But with the help of some optional commands it can be done with ease.

Also, see my previous post.


Some History

In the early days of Unix Workstations and Server, "sendmail" was typically configured by default, and therefore sending email was easy. In fact, it was "too easy", which allowed the bad guys to anomalously send SPAM. To combat SPAM most ISP's started requiring mail be "signed" (user name and password) by the originator, so it could be traced back to the point of origin.

Today

Often it is useful to send a simple status report, information, attachments, or a quick SMS messages from; a Linux Workstation, a small Raspberry PI, or a Beagle Bone.

Today "most" email must be signed, and because of that it has become more difficult to use email for sending mail even to oneself.

Note: There are a "few" Open Mail (SMTP) Gateways that can be used. But the gateways can not, and will not guarantee any kind of performance, or can not provide any reasonable expectations. These Open SMTP's  are often used by SPAMMER.

Google'ing "Raspberry PI email" will provide several solutions.

But, most (if not all), require you use/save your EmailAddress and EmailPasswd as clear open-text on the command line or within a configuration file. I do not like that idea. There has got to be a better way?

One of the suggested solutions is "sendEmail", unfortunately it has a (some what) "complex" command line interface, and as above it normally requires the user to type an email password as clear open-text on the command line.

Note the upper case "E" in the sendEmail name.

To simplify, I have created a "Wapper Script", that can be used similar to those used in the early days of UNIX.

Examples:

      $ date | mysendgmail some_user@gmail.com

or,

      $ mysendgmail some_user@gmail.com < textfile

or, SMS

      $ echo "Meet me for Lunch" | mysendgmail phonenumber@vtext.com

or, with an attachement

      $ echo "Here is my report" | mysendgmail some_user@yahoo.com -a myfile

or

      $ mysendgmail some_user@aol.com -s "My Status" -m I am driving, Do you want a ride.

Note: in the above example, @vtext.com is the Verizon SMS gateway, others could be used as necessary.

For the above examples, using my "Wapper Script", the users Gmail Password is prompted for, but does not display, see help text.

Also, see the included Help text for install instructions.

This Script makes my life easy, I hope you also find it useful. It is a little long for a blog post, but I wanted to provide it here before going to the trouble of setting up its own GitHub.

Note: some of the options of "sendEmail" have been used/perverted by this script to make the user interface easy and simple, which I find is a good compromise for functionality and usability.

Note: there is a BUG in the Raspberry PI implementation of "sendEmail",  Again, see the Help text.

If all else fails, "sendEmail" is a useful tool even when used by itself.

This following is mysendgmail script:



#! /bin/bash
# mysendgmail - Command line mail interface for Linux users,
# often on Raspberry Pi and other similar
# This script is a user friendly wrapper for "sendEmail"

# Because this script requires customization for each user,
# it should be save in each users $HONE/bin directory,
# as $HOME/bin/mysendgmail (or what ever name you like).


AUTHOR='Eldon R. Brown  - WA0UWH - 2015/11/22'
REV='1.02.30'

# Notes:
#   I think Google gmail allows 99 SMTP emails to be sent per day.
#   Note: an SMS sent to a Cell Phone has a 160 Character Limit.

progname=`basename $0`

# The Gmail Account, these must be customized per user
 from_user='userName@gmail.com'
 gmail_user='userName'

#This is for Google Gmail, others could be used
 SMTP='smtp.gmail.com:587'


# Setup for Bold, Highlight, and Normal output
 B=`tput bold` G=`tput setf 2` N=`tput sgr0` H=${B}${G}

Usage="

${B}${progname}-${REV}, by: ${AUTHOR}${N}

  ${H}Usage:${N}

        ${progname} [mode] [-t] user@domain.com [[-s|-u] subject] [sendEmail args] -m message . .
  . . | ${progname} [mode] [-t] user@domain.com [[-s|-u] subject] [sendEmail args]

        Where: [mode] =
               -n     = Dry Run
               -v     = Verbose
               -h     = This help message
              --h     = This help message, plus more Info
              --help  = sendEmail help message, also see the
                        man page, as: man sendEmail

"

Info="
  ${H}More Info:${N}

        To Install supporting functions:
        $ sudo aptitude install sendEmail perl
        $ sudo aptitude install libio-socket-ssl-perl libnet-ssleay-perl

        See some sendEmail Examples, at: http://goo.gl/6LqX8Q

        NOTE: There is a BUG in Raspberry PI's implementation
              of: /usr/bin/sendEmail REV=1.56
              Workaround:
                 replace 'SSLv3 TLSv1' with 'SSLv3' within /usr/bin/sendEmail

 NOTE: The Gmail Passwd can be saved (and somewhat hidden)
              in the current environment with:
              $ export GPW; read -s -p 'Gmail Passwd: ' GPW; echo
       And then later, it can be removed with:
              $ unset GPW

" 
 
# Main

 # Check first arg for Help Message, or Version Info
 case "${1}" in
 (-V)    echo -e "${progname}-${REV} by ${AUTHOR}"; exit;;
 (-h|"") echo -e "${Usage}" >&2; exit;;
 (--h)   echo -e "${Usage} ${Info}" >&2; exit;;
 (-help|--help) sendEmail --help >&2; exit;;
 esac
 
 # Check first arg for Dry Run or Verbose
 case "${1}" in
 (-n) DRYRUN='yes'; shift;;
 (-v) VERBOSE='yes'; shift;;
 esac

 # Check next arg for Dry Run or Verbose, again to avoid order conflict
 case "${1}" in
 (-n) DRYRUN='yes'; shift;;
 (-v) VERBOSE='yes'; shift;;
 esac

 # Prompt for Gmail Account Passwd, OR used the Environment Varrible $GPW
 gmail_passwd="${GPW}"
 if [ -z "${GPW}" ]
 then read -s -p "Gmail Password: " gmail_passwd </dev/tty; echo
 fi


# Parse Mail Address and Subject Args
 
 # Check if First arg is "-t", if so ignore, ignore it and
 # assume the next is email address
 case "${1}" in (-t) shift;; esac

 # Assume Next arg is the TO address
 to="${1}"; shift
 
 # Check if Next arg is "-s" or "-u", if so, ignore it and
 # assume the next is the Subject
 case "${1}" in (-u|-s) shift;; esac

 Default_Subject="Sent: `date '+%Y/%m/%d %H:%M:%S'`"
 # Assume Next arg is Subject
 sub="${1:-${Default_Subject}}"; shift

# Setup DEBUG modes

 # Check for DRYRUN mode, if so, Munge passwd for DRYRUN
 if [ "${DRYRUN}" = "yes" ]; then gmail_passwd='"*****"'; fi

 # Check for VERBOSE, For Debug
 if [ "${VERBOSE}" = "yes" ]; then MODE='set -xv'; fi

# Build the Command
 CMD="sendEmail -o tls=yes -s ${SMTP} \
  -xu ${gmail_user} -xp ${gmail_passwd} \
  -f ${from_user} -t ${to} -u ${sub} \
  $@" # Adds user supplied sendEmail options

# Finally,  Run Command
 case "${DRYRUN}" in
 (yes) echo $CMD;;  # For Debug
 (*) ${MODE}; $CMD | grep "`date '+%b %d'`";; # Report just the "basic" status
 esac

# End



-- Home Page: https://WA0UWH.blogspot.com