Author: Lisa

Using BC And Command Substitution In OpenHAB’s Exec Binding

My husband has been setting up OpenHAB to control our home automation. Our dimmers are very direct – there’s a z-Wave binding that you set to 100 if you want it at 100%, set it to 18 if you want it at 18%, and so on. We have a handful of Zigbee bulbs, though, which are not so direct. We are controlling these bulbs through a Wink hub by running a curl command with the exec binding.

The OpenHAB exec binding runs a shell with a command string passed in from the -c parameter. Thus far, I have not found anything that runs within a shell not work in the exec binding. This includes command substitution {I personally use the backtick format instead of the $(command) format, but I expect the later to be equally functional}.

What is command substitution (without having to read the Open Group Base Specifications linked above)? If you run

kill `pidof java`

the shell takes the component within the backticks, evaluates it, and then takes the standard output and places that into the command. When “pidof java” returns “938 984 1038”, the command above becomes “kill 938 984 1038”.

We want to set the value to the OpenHab value (0-100) scaled to the Wink value (0-255 for GE Link bulbs) using command substitution with bc (an arbitrary precision calculator language). To evaluate a mathematical expression, echo the expression text and pipe it to bc. To set a bulb to 75% of its maximum brightness, our post data is “nodeId=a&attrId=aprontest -u -m9 -t2 -v`echo 2.55*75/1|bc`”.

Notice the divide by 1 at the end — that’s to turn a decimal value into an integer. If you use just 2.55*75, you post a value of 191.25 which throws an error. In bc’s language, / returns the quotient — this isn’t *rounding* but rather truncating the decimal portion( i.e. bc 9.99999/1 = 9).

We configure the OpenHAB item to take the selected value (the %2$s below), scale the value with bc, and insert the result into the curl command. We use a similar technique to read the data from Wink and present the scaled value through OpenHAB.

The item entry in our sitemap.items file:

Dimmer  DS_Pantry_Bulb_Level                                            “Bulb (Pantry Downstairs) [%d]”                                 <slider>        (gZigbeeBulb,gDS_Pantry,gLight)                                                                                 { exec=”<[/bin/sh@@-c@@echo `/usr/bin/curl \”http://wink.hub.address/set_dev_value.php\” -s -d \”nodeId=a&attrId=aprontest -l -m9;\”|grep Level|grep -oP \”\\d+\\D+\\K\\d+\\D+\\K\\d+\”` /2.55|bc:3600000:] >[*:/bin/sh@@-c@@/usr/bin/curl \”http://wink.hub.address/set_dev_value.php\” -s -d \”nodeId=a&attrId=aprontest -u -m9 -t2 -v`echo 2.55*%2$s/1|bc`;\”]”}

Fish Tacos with Flour Tortillas

More than a decade ago, when my company had an office out in Thousand Oaks, I traveled to LA fairly regularly. We got a “travel day”, so Friday was a free day in LA. Then my whole group would usually stay the weekend and fly out Sunday night. One of the things I loved to do on Friday or Saturday was drive down the coast and get fish tacos. We’ve gotten a few decent fish tacos in Cleveland, but nothing close to what I remember from the West Coast.

A few weeks ago, I decided to try making some at home. They turned out really well. The ocean perch was a really small filet that needed to be skinned first … which was a LOT of  work. The next time, I used a tilapia which came in a larger filet but didn’t require any prep work. The smaller pieces of fish gave us a crunchier taco, but I think I’d get the larger pieces and slice them.

Flour Tortillas:

  • 4 cups all purpose flour
  • 1/2 teaspoon salt
  • 2 teaspoons baking powder
  • 2 tablespoons liquid vegetable oil
  • 1-1/2 cups
  • Zest of one or two limes

Mix all of the dry ingredients (not the lime zest) in a bowl. Measure water in a measuring cup, add in the oil and zest, and mix well to break up the zest. Pour the water into the dry ingredients and mix to combine into a dough. Knead the dough for a few minutes. Cover with clingfilm and let set for at least an hour.

Grab a ball of dough and roll it with a pin — we roll them quite thick (1/8″ to 1/3″) and have something more like a flatbread than a traditional tortilla. I cook them on an electric griddle/grill at 350 degrees F for about three minutes, flip and cook for another two or three minutes (timing is going to depend on how thickly the tortillas are rolled).

Fish:

  • 1 lb of light white fish (we’ve had ocean perch and tilapia)
  • 1/4 cup vegetable oil
  • Juice and zest of one lime
  • 1 teaspoon ancho chili powder

Mix the oil, lime juice, zest, and ancho powder. Place fish in a low baking dish, pour marinade over fish, cover with clingfilm and refrigerate for twenty minutes. For grilled fish tacos, grill or saute the fish at this point.

Fish Breading:

  • Combine zest of one or two limes with bread crumbs in a bowl (add some of the chili powder if you want a spicier completed dish)
  • Combine all purpose flour, salt, and pepper in a second bowl
  • Combine two eggs and a little milk in a third bowl

To bread fish, dip it in the egg mixture, then dredge in flour. Shake off, dip in egg mixture again, then dip in bread crumbs. Pan fry in a good bit of oil, place on paper towels to absorb some of the oil.

 

To serve, take a warm tortilla / flat bread. Place fish onto tortilla and top with broccoli slaw, shredded cabbage, or mixed greens with diced tomatoes and onions. My broccoli and cabbage slaws are usually Mark Bittman’s spicy slaw sauce which has no mayo. Sometimes, though, I’ll do a creamy sauce of Greek yogurt, lime juice, and celery seed.

Parsing JSON In JavaScript

We’ve been trying to get our BloomSky data parsed and reflected in OpenHAB — we can automatically turn the lights on when there is motion *and* the luminescence is lower than some desired value.  Bloomsky has an API which allows us to retrieve JSON formatted data from our weather station. I never worked with JSON before – I’d heard the term, but didn’t actually know what it was … but I needed to parse it in a JavaScript transform. Does JavaScript do JSON? D’oh! Turns out JSON is an abbreviation for JavaScript Object Notation, and JavaScript parses JSON data really well.

Still need to turn my example web code into a transform that runs from OpenHAB, but getting values out of a JSON formatted string is as easy as using the “parse” function:

<html>
	  <head>
	    <script>
	      function parseMyData() {
		var input = '{"DeviceID":"83237E","LAT":41.226644299999997,"LON":-81.7224322,"ALT":292.78720092773438,"UTC":-4,"DST":1,"Searchable":true,"RegisterTime":1464494138,"CityName":"Hinckley","StreetName":"Bellus Road","FullAddress":"Bellus Road, Hinckley, Ohio, US","DeviceName":"Buzzard Cam 01","BoundedPoint":null,"NumOfFollowers":5,"Data":{"Temperature":80.528000000000006,"ImageURL":"http://storage.googleapis.com/bloomsky-img/eaB1rJytnZSmm5y3qJ1krJqwmJmtoJU=.jpg","Humidity":50,"Night":false,"ImageTS":1465938980,"Luminance":3445,"TS":1465938980,"Rain":false,"Pressure":29.087148500000001,"Voltage":2613,"UVIndex":"1"},"Point":{},"VideoList":["http://storage.googleapis.com/bloomsky-video/eaB1rJytnZSmm5y3_-4_2016-06-09.mp4","http://storage.googleapis.com/bloomsky-video/eaB1rJytnZSmm5y3_-4_2016-06-10.mp4","http://storage.googleapis.com/bloomsky-video/eaB1rJytnZSmm5y3_-4_2016-06-11.mp4","http://storage.googleapis.com/bloomsky-video/eaB1rJytnZSmm5y3_-4_2016-06-12.mp4","http://storage.googleapis.com/bloomsky-video/eaB1rJytnZSmm5y3_-4_2016-06-13.mp4"],"NumOfFavorites":0}'

		var jsonOfInput = JSON.parse(input);

		document.write("<P>Device ID is: " + jsonOfInput.DeviceID + "</P>");
		document.write("<P>Temp is: " + jsonOfInput.Data.Temperature + "</P>");
		document.write("<P>Luminance is: " + jsonOfInput.Data.Luminance + "</P>");
	      }
	    </script>
	  </head>
	  <body>
	  <h2>Press the button to start</h2>
	    <input type="button" onclick="parseMyData()" value="Parse"/>
	  </body>
	</html>

Tax and Budget Reform

I wish there was a decent way to file RFE’s (request for enhancements) with the federal government. I can’t do a thing about the complexity of the tax code or the annoyance of having to spend a weekend filling out forms just to get my money back. But there’s existing tax code for charitable deductions (although you can fall afoul of the AMT if you donate too much of your income … so that may need a little rewrite here). Create a new tax deductible donation categorization for government entities — then each department of the government not get themselves registered as a not-for-profit-goverment-entity that qualifies for tax deductible charitable donations. I would feel a LOT better about paying 10k in taxes this year if I knew the money was going toward departments I support (and not going to departments I do not support). I could literally donate every dollar I owe in taxes to specific departments – then get my payroll deduction contributions completely refunded (bonus, US government, you got the interest on my payroll deductions since you held on to them). Don’t want to bother? Then don’t – your payroll deductions will get allocated out for you through the budgeting process.

With a significant adoption rate, if no one wants to fund the Department of Whatever, then the people writing the budget could well take that as a hint. Obviously that’s not a perfect rule – no one wants to fund the IRS, but you’re still going to need someone to handle tax collection & filing (at least until you manage to sort out the tax code & processes). But someone who advocates eliminating the Department of Education may be surprised how many people voluntarily earmark their taxes for Education. Or the military industrial complex may be shocked that donations don’t approach the 60% or 16% (depending on your point of view of “all spending”) of the federal budget that goes into the military and Homeland Security.

Absolutism

I read an article from the NY Times stating: ‘Mr. Trump suggested that all Muslim immigrants posed potential threats to America’s security and called for a ban on migrants from any part of the world with “a proven history of terrorism” against the United States or its allies’. I know there’s a lot of interpretation in journalism, and I was curious what he actually advocated.

One quick Google later, I found the speech text on the candidate’s web site:

    “When I am elected, I will suspend immigration from areas of the world when there is a proven history of terrorism against the United States, Europe or our allies, until we understand how to end these threats.”

If this is what the man actually said, then there’s no third-party misinterpretation to blame. “Areas” of the world is vague, but I get not using legally accurate terms in campaign speeches. Linguistic and legal nuances are not exactly gripping (and sometimes get ridiculed a la what-the-meaning-of-is-is). But where there is a proven history of terrorism against the US, Europe, or our allies??? No delta-time qualification in there, so the Irish are right out? Bonus, though, is he inadvertently sorted a huge portion of South/Central America with this generalization too. For the most part, it’s been decades there too, but “fuera yankis” and all that.

Actually, I’d find the proposal far less incendiary if he said “the immigration system is absolutely a mess. I propose stopping all immigration for six months while we figure out how to do this properly.”. Years ago, Microsoft had a run of significant bugs and took a coding holiday to perform a code review. Similar thing — yeah, it’s disruptive to shut down our business for some period of time while we make sure we’re doing the right thing … but it’s more disruptive to continue doing the wrong thing.

Problem is that what Mr. Trump probably means is more apt to be banning immigration from any country some arbitrary individual / board decides seems like it could be dangerous (or just to be safe – any individual immigrant who looks like ..). Which would be frighteningly institutionalized racism.

Homemade Marshmallow!!!

We made homemade marshmallow using Alton Brown’s recipe (with hazelnut extract instead of vanilla). We built a fire pit out in our woods, and I wanted to make smores.

It got surprisingly thick while whipping it – I was worried that it would get too hard, and I may have stopped whipping it a little too soon.

DSC_9279

The end result, though, was spectacular. For future reference … they melt really quickly over the fire when they’re still fresh. Supposedly if you let them dry for a few days, they toast up better.

DSC_9300

We have a HUGE tray of marshmallows – supposedly they freeze well … so I used maybe 1/10th of them & froze the rest. This might be a lifetime supply … but I’m kind of looking forward to hot cocoa this winter with hazelnut marshmallows!

Serving Custom Error Pages From Apache

At work, we are in the process of retiring an old password management web site. We want to direct users to the new site, and I don’t particularly want to handle each possible entry point an individual may have bookmarked. It seemed a lot quicker and easier to just move everything out of the directory and throw up a custom 404 page.

I am certain that I’ve used just “ErrorDocument ### /file.xtn” in Apache configurations to serve custom error pages, but when I set this up in our staging environment … I got the generic 404. Three days of Googling and reading Apache documentation later, and I have a configuration that actually serves a custom page when error 404 is encountered:

        ErrorDocument 404 /customized-404.html
        <Files "customized-404.html">
        <If "-z %{ENV:REDIRECT_STATUS}">
            RedirectMatch 404 ^/customized-404.html$

Voila, a pretty page that doesn’t in any way indicate 404 / not found / etc but rather says “hey, this web site is being retired. please go over yonder to manage your password.”.

Sometimes, math *is* hard

A recent meeting included a call back to “math is hard barbie” — back in 1992, Mattel produced a ‘talking’ Barbie that (among other phrases) said “math class is tough”. They ended up recalling the doll – a process which I assume cost the company quite a bit of money. And bad press. As a sophomore in high school, I didn’t understand the controversy. I was concurrently taking both Algebra 2 and Geometry (allowing me to complete two years of Calculus at graduation), so I had some experience with math classes.

The thing that struck me — the actual phrase is not untrue. Sometimes math class was hard. As someone with hand-eye coordination issues, art class was hard too. As someone who is tone deaf, music class was really hard. People who take offense at someone declaring something to be ‘hard’ have themselves declared difficult things as somehow negative. Not worth doing. I understand that the offense was people familiar with existing stereotypes extrapolating the statement to mean “girls think math is hard and girls avoid difficult academic subjects” or “females think math is hard because their brains don’t work that way and males have an innate advantage”.

I worry that we’re selling people false hope by refusing to tell them that something is hard. At some point, you’re going to encounter reality. I studied theoretical physics – gravitation, specifically gravitational phenomenon brought about during binary black hole collisions. Had someone told me it was going to be a super easy way to earn money – head into a computer lab for a few hours a day, drink some coffee, do a little typing, and head home … wow, what a shock my first day would have been. Why don’t we work on teaching people that a lot of things are hard. And each person makes their own effort:reward analysis. Raising chickens is a lot harder than picking a carton up at the grocery store; but if you like fresh eggs, or if you like to ensure the welfare of the animals providing your eggs, if you want to avoid using fossil fuels to transport your food, or if you just want to be involved in the process of generating your food … you decide to get some chickens. If you want to understand the mechanisms of the universe, you learn the math and physics. You do the research.

Multi Party System

I’m eternally hopeful that a viable third party will emerge from the chaos that is the American political landscape. Movements with sufficient momentum (e.g. the tea party who think taxation with representation is just as bad as taxation without) get absorbed into one of the two traditional parties. And while I am still certain a viable centrist party would provide a truer picture of American’s actual will, the Republican primaries serve as warning against dividing the electorate among dozens of parties.

In the UK, there are hundreds of parties. A good dozen of them are represented in Parliament. But there’s no national vote for Prime Minister – if no party garners a sufficient majority in Parliament, then parties agree to work together (a coalition government) until a sufficient majority is created. And failure to abide by the agreement can force a PM out of office. Unless a plurality of Britons chose to elect the same party, the most extreme views of any party are tempered by the views of their coalition partners.

In the US, however, there is a nation-wide vote for head of the Executive branch. What would an American election look like with a dozen viable political parties? The Republican primary has shown us – last cycle and again this year. The lesson from last cycle is that a dozen people researching and publicizing the worst about each other diminishes them all. If half a dozen people spent six months digging into every single action or interaction you’ve had in your lifetime and assembling a worst-of list … I doubt anyone would look good. But this year the lesson is more dangerous — splitting your electorate in so many pieces allows an individual who is not the majority’s preference … a charismatic individual, an individual with divisive enough views to appeal to a “their” segment and  a small fraction of other voting segments … to win the election. If 120 million people vote in the presidential election, but split their votes across a dozen parties, someone could win with thirteen million votes. 89% of voters don’t want the person in office, but there they sit.

I still wish for a viable centrist third party, but many party systems are probably best left to Parliamentary systems.