Build your own Mac robot helper.

Source: Internet
Author: User
Tags python script

Ever since I saw the Iron Man series, I have been very enthusiastic about all kinds of automation, monitoring, and warning ideas. If you use the iphone then you have Siri on your phone and you can perform some of the actions you want it to perform (such as calling a contact person, and so on). But I have always been in the computer time than on the phone longer, so always like the computer can also be more intelligent. In fact, the "smart" I am looking for here refers to a kind of "pseudo automation", which basically contains two features: Automatic processing + prompt reminder.

Mac OS X originates from the open source operating system: Darwin, (it is the Unix-like operating system). Because of the innate hack culture, makes Mac OS X programmability is very good, many to the system's monitoring, the operation has opened the shell command. This makes my mind not far away.

The past few days, wrote a series of automatic-services open source in the GitHub (service is not enough, also not fully constructed). The list that is currently built or is being built is as follows:


You can write a lot of services, such as you can refer to the rest of the body schedule. Let the robot automatically remind you what the current session advises you to do.

Currently, these services have been running well on my MBP (most of which are boot-initiated deamon programs).

Implement
Analysis

First, let's analyze what the possible services are. In fact, the service is divided into its life cycle, can be simply divided into: Real-time running short service (such as the time); In the system boot State, resident system Deamon Service (memory, CPU, battery power monitor/alarm lamp).

Most modes of service are based on the classic request/reply mode, which is no exception. Because there is no Mac OS X programming involved, there are some benefits of system level (such as signaling mechanisms, system events, etc.) that make it difficult for you to implement a set of custom protocols (because you need to take advantage of message mechanisms, event mechanisms). It is very unreliable to write a while true, especially with Deamon running in the background (which takes up CPU, causing the CPU to keep idling), and the temperature of the CPU is soaring.

For the above reasons, the existing standard protocol (HTTP) and its service handlers have been selected. From the simple point of view of building HTTP server, Node.js is undoubtedly the best choice, and its features are well suited to such requirements (single-threaded, event-based). So the final choice is to use Node.js to run an HTTP server on this computer as a container for services.


How to start a service

Because these services are hosted inside a native-initiated HTTP server, it is only possible to initiate a request from locally to start it. For example, if you want to open a goagent, you may first think of opening the browser and then entering:

http://localhost:9876/proxy_on

Then, tap the ENTER key to request a service. Yes, it's one of the ways (it also provides a way to get away from it for many people who hate the command line). But if this is the only way to make a request to HTTP server, the limitations are too great. This affects the way we want to launch the services that run in deamon form at boot time (because the request must be browser-supported and manual). Fortunately, the Shell's own Curl command supports the direct request to any accessible HTTP server from the command-line form. In this way, we can write a script to initiate the request in such a manner as to trigger the Deamon service to run with the boot.

Curl Http://localhost:9876/sayHello sleep
Curl http://localhost:9876/proxy_on sleep
Curl http ://localhost:9876/weather sleep
Curl Http://localhost:9876/memoryMonitor?opt=d          #opt:d Run as Deamon

You can see that you can carry parameters in the back, and the first parameter opt (option) value is D (deamon) to indicate that it runs Deamon. So, if you have the need for a service that can be run on an instant request and run in a deamon way, you can judge within your service:

if [[$#-eq 0]]; Then
    speak "battery checking!"
    Monitor
    exit 0
fi while

getopts ":d" optname does case
    "$optname" "
    D")
        echo " Monitor_deamon "
        Monitor_deamon
    ;;
    *)
        echo "others"
    ;;
    Esac done

And the so-called Deamon mode, in fact, is a while-true program, to run-sleep-run-sleep such a pattern non-stop to carry out the loop only:

function Monitor_deamon () {while
    [true]], do

        monitor

        if [[$CONNECTED!= $CONNECTED _tmp]]; then
            if [[ $CONNECTED = ' No ']]; Then
                speak "AC power disconnected!"
            else
                speak "AC Power connected! Battery is charging now! "
            Fi

            connected_tmp= $CONNECTED
        fi sleep done
}

But no matter what request, within the HTTP server is to open a child process alone to execute, so it does not affect any other services, nor any other request blocking:

var exec         = require ("child_process"). exec;
var shellcmdlist = require ("./shellcmd"). Getshellcmdlist ();
var URL          = require (' URL ');
var querystring  = Require ("querystring");

function battery (request, response) {
    var paramobj=querystring.parse (Url.parse (request.url). query);
    var cmd=shellcmdlist["Battery"];

    if (typeof paramobj!= "undefined" 
        && 
        typeof paramobj.opt!= "undefined" 
        && 
        paramobj.opt== "D") {
        cmd+= "-D";
    };

    EXEC (cmd, function (Error, stdout, stderr) {
        logexecinfo ("Battery", error, stdout, stderr);

    Response.writehead ({"Content-type": "Text/plain"});
    Response.End ();
}

At the same time, because most of the services ' real-time ' does not need to be too strong, so the above run once, will sleep at least 60 seconds, and run itself about 1 seconds. As a result, the CPU occupancy rate is almost zero and negligible (the instant you open dozens of such deamon service, now at least i5 the processor capabilities, you can ignore them).

It says "pseudo automation" here requires at least two features. In which, the automatic processing, to these service, the immediate reminder is clearly dependent on the "voice alert." This is also a big feature of Mac system, it does not need any Third-party program dependencies, itself is can "speak", and support basic all languages, and can automatically select the Voice library. You just need to open the terminal and enter the following command:

Say-v Alex ' Hello, Kobe Bryant '

You can let it speak (where the-V indicates that you can select a specific language library, which is the Alex pronunciation, you may choose Chinese).

So before you use the service, you first need to turn on the function of the system. See, my other article: "Python script to achieve the MAC boot automatic voice broadcast weather." Also, you should also know how to make a script run automatically, as explained in this article.

As long as you can get it and you're willing to do it (first you'll have to shell or any other kind of Mac-supported scripting language), you can try the Automation services you want to implement.

Mobile End Control

If your computer and mobile phone are connected to the same Wi-Fi, then you can also through the phone's browser to complete the httpserver on your computer (although your httpserver listening to your native [localhost/127.0.0.1], but in the local area network, Your computer still has an IP address on the LAN that uniquely identifies your computer, so the effect is the same. Just turn on system settings-network settings, see what IP is displayed on your Wi-Fi bar, and then in your mobile browser, change the above localhost to the IP, but the port is still necessary.

Of course, if you can develop the iphone and be able to write an exclusive client for it, that would be great.

Remote Control conjecture

Here on a machine, run Httpserver and client. Does that make it possible to manipulate the computer from the remote as well as the normal way of accessing the site? I have written an article before, XXX is the mail protocol to achieve remote control of the computer (of course, this also relies on the HTTP protocol, but it only acts as a transport media). Now that we have httpserver, everything is simple, you only have to expose your current host IP can (of course, you must be authorized access to these service). Also, if you feel it is unrealistic to expose your computer to the Internet. Then you can use a proxy, intermediary mode to achieve. This is easy, now a lot of App engine platform, you can apply for one as your proxy server. So you and the computer you want to control the HTTP server only need to directly with this proxy server to interact with it. Proxy server can temporarily cache your service instructions, HTTP server interval for a period of time to poll the proxy server, get the command received.


It's the Mac that makes life better .


In fact, you will find that all repetitive actions should be replaced by the program, and then handed over to the computer for execution. At least the UNIX-system operating system supports this, but because the programmer is only a handful, and Mac OS X has always advertised itself with a high standard of user experience, it does provide some automated tools for a lot of ordinary users who don't program and want to reduce some repetitive work.



Apple Script

A script language that applies only to Mac operating systems, right box above


Automator's Tools

Above the left box, there can be a variety of repetitive processes in tandem, so that the system to act as a "robot" for you to perform those boring and repetitive things (such as renaming a folder in all the file names, go to a site to click on a number of rules to crawl specific pictures ...) )。



Voice dictation provided by Mac

I have tried, but the recognition rate is not very ideal, unless your English is very standard.



about Vino

Vino is Bryant's new nickname, the implication is vintage wine, the longer the more fragrant.

Enjoy & Have fun!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.