Parsing data from twitter search.twitter.com/search.json?query=

Followers of this blog will know that I have been playing with twitter and an arduino.

I would like to document my method of parsing twitter for data.

PHP code follows, but any language that can parse json data will be fine.

<?php
/*
	This code will parse twitter for a search string from a particular twitter handle
	passed variables:
		username	twitter username
		q		search string
		count		Maximum number of results to return
		since_id	This can initially be empty, it gets populated by the json result

	This script will return the following parseable string:
		"tweet messagehttp://refresh.urlusername"
	After the first pass, you can simply send the information in the  tags which will only return any new results.

*/
	$host = "http://search.twitter.com";
	$filename = "/search.json";
	$username = (isset($_GET['username']) ? stripslashes($_GET['username']) : "gregoryfenton");
	$query = (isset($_GET['query']) ? stripslashes($_GET['query']) : "arduino");

	$opts = array('http' => array(
		'method'=>"GET",
		'header'=>"Accept-language: en\r\n"
	));
	$context = stream_context_create($opts);

	$search = isset($_GET['q']) ? stripslashes($_GET['q']) : "candy4greg";
	$search = str_replace(" ", "%20", $search);
	$count = isset($_GET['count']) ? stripslashes($_GET['count']) : "1";
	$since = isset($_GET['since_id']) ? stripslashes($_GET['since_id']) : "";

	$a = "$host$filename?" . ($search == "" ? "" : "q=$search") . ($count == "" ? "" : "&count=$count") . ($since == "" ? "" : "&since_id=$since");
	echo "$a\n";
	$json = file_get_contents($a, false, $context);

	$obj = json_decode($json, true);
	$tweet = $obj['results'][0]['text'];
	$refresh = $obj['refresh_url'];
	$user = $obj['results'][0]['from_user'];

	echo "searching for $search\ncount: $count\nsince: $since\n";
	echo "";
	echo "$tweet";
	if($refresh != "")
		echo "$refresh";
	if($user != "")
		echo "$user";
	echo ""
?>
Posted in Uncategorized | Leave a comment

g15daemon restart on “(g15daemon) did not claim interface 0 before use”

#!/bin/bash

g15daemon automatic restart on replugged keyboard
Written by Gregory Fenton, http://labby.co.uk

let count=0
match="(g15daemon) did not claim interface "
tail /var/log/syslog -fn 10 | while read line; do
	if [[ $line == *"$match"* ]]; then
		let count=$count+1
		echo $count
		if [ $count == 10 ]; then
			let count=0
			sudo g15daemon -k
			sudo g15daemon
		fi
	fi
done
Posted in Uncategorized | Leave a comment

My personal review of WebRoot SecureAnywhere Mobile

As followers of my blog will know in one of my posts a comment was made from the Vice President of a company. Me being full of cheek I asked him if I could have a copy of his software for my mobile phone (Samsung Galaxy Nexus).

He obliged, and provided me with a download link and serial key.

First and foremost I wish to thank him for the generosity.

The company is WebRoot http://www.webroot.com and the product I was given was SecureAnywhere Complete. I was actually given the full version for installation on up to 5 devices (PCs, Macs and Android devices) rather than simply the one for my mobile phone.

Installation:
I had an issue that occurred because I was given my copy which I will tell you about.
I was emailed a license key by David Bennett (Vice President) and when I came to install the software I not only needed the key, but also the corresponding email address and password which I was not given. Quite a show-stopper.
I emailed David with the issue and within a short period of time my phone rang.
It was WebRoot Tech Support calling my mobile from Ireland to help with the issue.
He was aware of my problem and asked me for my key, which I could not give him as it was in my email but I was on my mobile. I told him I would end the call, get it from my email and asked if he would phone back a few minutes later.
As promised he returned the call and we began in earnest. He set up the account for me and the only thing I had to do when I finished on the phone was open my email and click on a confirmation link and then I could set up the software.
After this blip – which in no way reflects badly on them and I must highly commend them for their swift handling of my issue – installation was a breeze. I actually did it in the pub in a noisy environment. It did a deep scan of my phone which took a little time but once that was done scans only take a short time.

Day-to-day usage:
During normal usage I do not notice the app. It is one of the very few apps that I allow to have an icon in my Action Bar at the top of my screen.
I only see the app whenever I install or update new software – it scans automatically and within a second or so it tells me whether the new software is safe.
Battery usage is negligible which is a major issue on mobile devices.
Memory usage is 38MB on my phone.

Overall:
I like the look of the software. The user interface is clean and well planned and works remarkably well on my device.
I have not been infected with malware yet which is always a good thing.
It is good that this app is not like so many others I could mention – full of bloatware and useless features.

List of features (blatantly copy/pasted from their site):

ANTIVIRUS/ANTISPYWARE
Advanced protection against viruses, spyware, worms, Trojans, rootkits and more.

BLAZING FAST SPEEDS
Scans your computer in less than two minutes*

NO CONFLICTS
Won't conflict with your other programs – even other security software.

ID THEFT PROTECTION
Blocks the keyloggers and screengrabbers that others miss to keep your financial information safe from cybercriminals.

ANTIPHISHING
Warns you if a website is a fraudulent website that could steal your personal information.

POWERFUL FIREWALL
Two–way firewall blocks hackers and intrusions while minimizing interruptions and false alerts.

SECURE BROWSING
Blocks malicious websites and phishing attacks before they can do harm.

MOBILE PROTECTION
Protects your tablets and smartphones, auto-scanning all apps and downloads for threats. Locates your device if it is lost or stolen.

PASSWORD MANAGEMENT
Creates and stores hacker-proof passwords, automatically logging you into your favorite sites without risk.

AUTOMATIC FILE PROTECTION
Automatically backs up your personal file online and synchronizes them across your PCs.

PRIVACY PROTECTION
Wipes away all traces of your online activity and reclaims space by removing unneeded files.

*After initial scan, deep system scans typically take two minutes or less.

I really like this software (and this comes from someone who runs linux on his home PC and server for security reasons) and will definitely be renewing my license when the time comes.

I would definitely recommend this software for someone running an android phone.

This is a completely unbiased review, even though I got the software for free. If you read my other blog posts you will see that I am rather vocal when I have an issue.

I wish to thank David Bennett for the copy of the software and the tech support team that helped with my issue.

Posted in Uncategorized | Leave a comment

http://www.ipo.gov.uk/response-2011-copyright-final.pdf

Government response to consultation on copyright exceptions and clarifying copyright law

There are a lot of very interesting parts, notably the confirmation that home users can legally transcode between their own devices for their own private use without fear of the Copyright Act, forcing rights holders licenses to comply with law (specifically not allowing the rights holder to remove rights engrained in law using contract terms).

There have been a few concessions to the rights holders.

Let’s see how long before the government sacks somebody and claims this was not supposed to be made public as soon as the rights holders see the changes..

This has slipped through the mainstream media again and gets very few hits on google (9 before I made this post)
ipo

Posted in Uncategorized | Leave a comment

bash split string every n characters

Today I needed to split a string in bash every 5 characters.

Here is how I did it:

a="AdmitAfritAmbitAuditAwaitBefitBinitBruitCubitDavitDebitDemitDigitDixitDroitFixitFruitHabitKraitLegitLicitLimitMeritOrbitPetitPewitPipitPlaitPositQubitQuoitRecitRefitRelitRemitResitSpaitSplitSpritTacitTraitUnfitUnlitUnwitUplitVisitVomitZizit"
count=5 # change 5 to however many characters you wish to break on
b="$a"
while [ "$b" != "" ]; do
echo "${b:0:$count}"
b="${b:$count}"
done

I hope this snippet helps somebody. If it does, please feel free to leave a comment – I enjoy interacting with visitors to my corner of the internet :)

Posted in bash scripts | Leave a comment

E-cigarette machines – health hazard in the making? A future TV ad for claiming compensation?

Edit:

Electronic and herbal cigarettes will also have to carry health warnings under the European-wide shake-up designed to make smoking less attractive to young people.

Guess I was right after all.

Am I the only person in the world who believes that in some point in the future e-cigarettes will be banned from sale because of health hazards?

I was wondering about this when a local restaurant started selling them for use inside the restaurant.

You can get hold of them anywhere nowadays with little or no monitoring of the harmful chemicals they contain.

I did a quick google search and it appears that my worries are justified – one of the very first links I found was http://www.dailymail.co.uk/news/article-2184014/Ministers-warn-electronic-cigarettes-unsafe-lead-health-problems.html (“‘Electronic cigarettes could be unsafe and lead to health problems,’ ministers warn”).

A quote from Health minister Simon Burns said: “The available data suggest that there can be great variability in the content of electronic cigarettes, both in the amount of nicotine present and also in relation to other potentially toxic substances.

Some electronic cigarettes have been tested by local authority trading standards departments and have been found to pose a potential danger to consumers.”

I am a non-smoker, and I will be avoiding this restaurant because of their policy from now on. I don’t wish to smell smoke, fake or otherwise, while I am eating – especially when the government has given health warnings about them and the Medicine and Healthcare Products Regulatory Agency will make a decision next Spring on whether to introduce stricter checks.

The World Health Organization stated in September 2008 that no rigorous, peer-reviewed studies have been conducted showing that the electronic cigarette is a safe and effective nicotine replacement therapy. WHO does not discount the possibility that the electronic cigarette could be useful as a smoking cessation aid, but insisted that claims that electronic cigarettes can help smokers quit need to be backed up by clinical studies and toxicity analyses and operate within the proper regulatory framework.

In May 2009 the US Food and Drug Administration (USFDA) Division of Pharmaceutical Analysis tested 19 varieties of electronic cigarette cartridges produced by two vendors NJoy and Smoking Everywhere. Diethylene glycol, a poisonous and hygroscopic liquid, was detected in one of the cartridges manufactured by Smoking Everywhere . Tobacco-specific nitrosamines (TSNAs), known cancer-causing agents, were detected in all of the cartridges from one brand and two of the cartridges from the other brand. Nicotine can also be traced in some claimed nicotine-free cartridge. Further concerns were raised over inconsistent amounts of nicotine delivered when drawing on the device. Some cartridges were found to contain “tobacco-specific impurities suspected of being harmful to humans—anabasine, myosmine, and β-nicotyrine—were detected in a majority of the samples tested.”
In July 2009, the FDA publicly discouraged the use of electronic cigarettes and raised concerns that electronic cigarettes may be marketed to young people and lack appropriate health warnings.
The Electronic Cigarette Association criticized that the FDA testing was too “narrow to reach any valid and reliable conclusions.” Exponent, Inc., commissioned by NJOY to review the FDA’s study in July 2009, objected to the FDA analysis of electronic cigarettes lacking comparisons to other FDA-approved nicotine replacement therapy products where similar levels of TSNA were detected. Exponent concluded that the FDA’s study did not support the claims of potential adverse health effects from the use of electronic cigarettes.
Furthermore, FDA methods “have been lambasted in journals” by some medical and health research experts who noted the potentially harmful chemicals were measured at “about one million times lower concentrations than are conceivably related to human health.”

On 27 March 2009, Health Canada issued an advisory against electronic cigarettes. The advisory stated “Although these electronic smoking products may be marketed as a safer alternative to conventional tobacco products and, in some cases, as an aid to quitting smoking, electronic smoking products may pose risks such as nicotine poisoning and addiction.”

In Latvia, the Ministry of Health has warned that the e-cigarette can cause harm to cardiovascular, hepatic and renal systems, however, e-cigarettes are legal, and are sold in most shopping centers and at Riga’s airport, as well as via the internet to individuals at least 18 years old.

In Hong Kong the sale and possession of nicotine-based electronic cigarette, classified as a Type I Poison, is govered under the Pharmacy and Poisons Ordinance. Sale or possession is not authorized and both considered are punishable with a fine of up to HK$100,000 and/or a prison term of 2 years. However, the law does not cover any non-nicotine inhaler.

In Lebanon, the council of ministers has banned the sale and use of electronic cigarettes starting 21 September 2011.

In Mexico, the Federal Commission for the Protection Against Sanitary Risks, informed that according to Mexican Law, the selling and promotion of non-tobacco objects that include elements generally identified with tobacco products, are forbidden.

In Pakistan, the import and sale of electronic cigarettes is legal, but Pakistan Medical and Dental council categorizes the current health safety assessments about e-cigarettes not to be yet satisfactory.

In Panama, importation, distribution and sale have been prohibited since June 2009. The Ministry of Health cites the FDA findings as their reason for the ban.

In Singapore, the sale and import of electronic cigarettes, even for personal consumption, is illegal. According to Health Minister Khaw Boon Wan, electronic cigarettes were the industry’s attempt to attract new users and were marketed to appeal to younger customers, including women.

In the United Arab Emirates, sale and import of electronic cigarettes, even for personal consumption, is illegal. Items will be confiscated upon arrival.

Posted in Uncategorized | 2 Comments

@Arduino based twitter-enabled candy machine – all working and monitoring twitter

I got my twitter monitoring candy machine working today!

If you wish to give me a candy simply send a tweet with the hashtag #candy4greg and I (or my children!) get a healthy nutritious snack. Chewing gum, skittles and tic tacs are healthy, right?

Here is the code I am using. Note you will need to get the TextFinder library from the arduino site:

#include <SPI.h>
#include <Ethernet.h>
#include <TextFinder.h>

int treatPin = 9; // The pin the transistor is connected to

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xE4 };
byte ip[] =  { 192,168,0,228}; //change this
EthernetClient client;
char TwitterHashtag[] = "#candy4greg"; //change this to your own twitter hashtag, or follow arduino ;-)
char tweet[140] = "", oldTweet[140] = "";
char serverName[] = "search.twitter.com";  // twitter URL


void setup() {
  pinMode(treatPin, OUTPUT);
  // initialize serial:
  Serial.begin(9600);
  if(!Ethernet.begin(mac))
    Ethernet.begin(mac, ip);
  // connect to Twitter:
  delay(3000);
  for(int i = 0; i < 140; i++)
  {
    oldTweet[i] = 0;
    tweet[i] = 0;
  }
}


void loop(){
  int i;
  Serial.println("connecting to server...");
  if (client.connect(serverName, 80)) {
    TextFinder  finder( client,2 );
    Serial.println("making HTTP request...");
    // make HTTP GET request to twitter:
    client.print("GET /search.atom?q=%23");
    client.print(TwitterHashtag);
    client.println("&count=1 HTTP/1.1");
    client.println("HOST: search.twitter.com");
    client.println();
    Serial.println("sended HTTP request...");
    while (client.connected()) {
      if (client.available()) {
        Serial.println("looking for tweet...");
        if((finder.find("<published>")&&(finder.getString("<title>","</title>",tweet,140)!=0)))
        {
          for(i = 0; i < 140; i++)
              if(oldTweet[i] != tweet[i])
                break;
          if(i != 140)
          {
            Serial.println(tweet);
            feedKids();
            for(i = 0; i < 140; i++)
              oldTweet[i] = tweet[i];
            break;
          }
        }
      }
    }
    delay(1);
    client.stop();
  }
  Serial.println("delay...");
  delay (60000); 
  // don't make this less than 30000 (30 secs), because you can't connect to the twitter servers faster (you'll be banned)
  // off course it would be better to use the "Blink without delay", but I leave that to you.
}

void feedKids()
{
  Serial.println("Time to feed the kids!");
	digitalWrite(treatPin, HIGH);
	delay(2000); // time in ms to run the motor
	digitalWrite(treatPin, LOW);
}

The code searches for the hashtag #candy4greg and then compares it with the previous time it checked, if there is a difference I get fed :)

The below images and above code should point you in the right direction.

Wiring to arduino

Wiring to arduino

Arduino motor driver using TIP120

Arduino motor driver using TIP120

An endnote: The actual candy machine is from Maplin, here is a link to the product page: www.maplin.co.uk/search?criteria=n05nb. They have a larger model, I want that now I know the idea works. That is at www.maplin.co.uk/large-treat-ball-the-motion-activated-treat-dispenser-662062. Both are on sale at the moment, grab them before they become popular now us arduino lovers have discovered them!

A note for parents: Candy like chewing gum balls are not an acceptable substitute for square meals. Stick to giving the kids drumstick lollies and mojo's and you'll be fine.
Drumstick lolly Mojo chews

Posted in Uncategorized | 10 Comments

candy

On my way to buy candy for my twitter powered candy machine @Arduino @codebender.cc @maplintweet

Posted in Uncategorized | Leave a comment

@Arduino based twitter-enabled candy machine – almost finished, it works!

I have made a very basic test of my circuit (not much more than soldering 2 wires to the motor where the wires meet the resistors) and it works great :)

I couldn’t find a tip120 so I opted instead for a BD135.

Pity my maoam sweets don’t fit :( Time to get some skittles from the shop :)

One of the resistors broke (manufacturing flaw?) when I touched it but it still works as the internal wire was intact. I will replace it when I make a more permanent circuit.

The circuit goes as follows:

+5v goes to positive side of motor (the side with the diode)
Ground goes to pin 1 (emitter) of BD135
pin 2 (base) of bd135 goes to negative side of motor
Arduino pin 9 goes to pin 3 (collector) of BD135

Sample arduino code:

int feedPin = 9; // pin connected to collector of BD135

void setup()
{
	pinMode(feedPin, OUTPUT);
	digitalWrite(feedPin, HIGH);
	delay(1000); // You may change this to make the motor run for longer or shorter
	digitalWrite(feedPin, LOW);
}

void loop()
{
	
}

To trigger the feeder simply press the arduino reset switch, after a brief pause it will start.

The pause is caused by the arduino resetting. In proper code you would not see a delay.

Tomorrow I will purchase the aforementioned Skittles and as a reward to myself I will eat some when I have the written twitter feed monitor code.

Enjoy what I have so far and don’t forget to spread the word of my triumph far and wide!

If you build one, ensure you get sweets smaller than a malteser or the mechanism may jam. Plus a handful rather than one is always good :)

Wiring to arduino

Wiring to arduino

Posted in Uncategorized | 5 Comments

@Arduino based twitter-enabled candy machine – teardown images and preliminary ideas

This post contains all the images of the candy machine before I started hacking it.

The wiring is as follows:

red: +
black: -
white: to capacitive sensor
red and black are used again from the PCB to the motor
The circuit runs on 3 AAA batteries for a total of 4.5 volts, feeding the circuit 5 volts (running from USB power perchance) should be acceptable and an easy mod as the motor itself is quite small.

My first instinct is to connect the arduino trigger to the circuit where the capacitive sensor goes, but I may leave that alone so I can still use the sensor. That would leave me with the other options of poking about on the circuit board to see if I can trigger the motor or simply interfacing directly with the motor.

The easiest solution would be to interface with the motor directly using a transistor such as the TIP-120 and I think that this is the way I will go.

I will make a complete blog post once I have built the entire contraption, including the code to interface with twitter and post it to http://instructables.com as well if I remember to document all the steps I made :)

Right now I just keep getting bugged by my darling children to see it in action (read that as “eat the sweets”).

My circuit would be along the lines of this:

Arduino motor driver using TIP120

Arduino motor driver using TIP120

Candy machine before the warranty was voided

Candy machine before the warranty was voided

Candy machine before the warranty was voided

Candy machine before the warranty was voided

Candy machine before the warranty was voided

Candy machine before the warranty was voided

Bottom of candy machine showing screw locations

Bottom of candy machine showing screw locations

There goes the warranty, here are the internals

There goes the warranty, here are the internals

Closer look at the battery terminals and wires

Closer look at the battery terminals and wires

The lid simply twists off

The lid simply twists off

The bottom red plate lifts out for cleaning

The bottom red plate lifts out for cleaning

A view of the screw mechanism (the "treat auger")

A view of the screw mechanism (the “treat auger”)

A view of the motor and wires

A view of the motor and wires

The white wire comes from the capacitive sensor

The white wire comes from the capacitive sensor

A close up view of the motor showing the resistors and diode

A close up view of the motor showing the resistors and diode

a bottom view of the PCB showing the wires

a bottom view of the PCB showing the wires

a top view of the PCB

a top view of the PCB

a top view of the PCB

a top view of the PCB

a top view of the PCB

a top view of the PCB

Posted in Uncategorized | Leave a comment