Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 50
Текст из файла (страница 50)
The first POST request from the phone passesthe art image in binary form from the variable chunk to the scriptin Example 117, which stores it on the server in the directory namedpictures. Its filename, which becomes part of the image’s URL, iscreated dynamically using the timestamp and a random number. Withecho "".$filename; the filename of the art image is returned to thePyS60 script.Example 117: Server-side PHP script<?php// this file's name is upload_to_url.php// read the incoming image data handed over from PyS60 phone$chunk = file_get_contents('php://input');// create a filename based om time and a random number$timestamp = time();$random_id = rand(0, 10);$filename = 'Pic'.
$timestamp .$random_id .'.jpg';ARDUINOBT MICRO-CONTROLLER BOARD261// write the file to the server into the directory pictures$filepathname = "pictures/$filename";$handle = fopen($filepathname, 'wb');fputs($handle, $chunk, strlen($chunk));fclose($handle);// return the filenameecho " ".$filename;?>11.3.3 Inserting Data into a MySQL DatabaseThe structure of the MySQL database table that is used for the MobileArtBlog contains five fields that are named blog text, blog datetime,blog pic url, blog lon, blog lat.
The second POST requestpasses the encoded contents sent by the PyS60 script to the PHP script inExample 118, which inserts them into the fields in the table.Example 118: PHP script for MySQL database insert<?php// this file's name is insert_artblog.php// Get the incoming params sent by the PyS60 phone$data = $_POST['data'];$eggs = $_POST['eggs'];$bacon = $_POST['bacon'];$noodle = $_POST['noodle'];include "_mysql.php";$sql = "INSERT INTO artblog (blog_text, blog_datetime,blog_pic_url, blog_lon, blog_lat)VALUES ( '$data', NOW(), '$eggs', '$bacon', '$noodle')";db_query($insert, $sql);?>11.4 ArduinoBT Micro-Controller BoardAs mentioned in Chapter 7, it is possible to connect your phone to amicro-controller.
The ‘ArduinoBT board’ (Figure 11.7) is an example ofa micro-controller board with Bluetooth extension chip that offers serialport communication.Arduino is an open-source physical computing platform based on asimple I/O board and a development environment for writing Arduinoapplications (www.arduino.cc). The Arduino programming language isan implementation of Wiring (http://wiring.org.co), based on Processing(www.processing.org). It is easy to learn and quick to program. Thismakes it an ideal complement for PyS60 to do rapid prototyping of262COMBINING ART AND ENGINEERINGFigure 11.7 ArduinoBT board and Nokia N80physical computing applications.
It can serve as a mediating technologybetween sensors, motors and other actuators, providing access to thephysical world.The mobile phone acts as a gateway device to the Internet givingaccess to the digital and virtual world. As the Arduino board is small,light and battery-powered, it is suitable to be taken anywhere, like themobile phone itself.In this section, we describe the steps to connect a phone over Bluetoothto the ArduinoBT board.
The PyS60 code is given, as well as the Arduinocode that runs on the board. The Arduino software tool has a built-ineditor for writing the Arduino code. When you press an upload button,the code is pushed to the board and can be executed.The example application we provide here simply lets the user switchan LED light on and off on the Arduino board. Each time the LED changesits status, the board sends a confirmation (on or off) message back to thephone. This is a simple example but it shows you the basic principlesfor communicating with the board using the phone.
It is up to you to dogreat things with it.All you need for this example, besides the ArduinoBT board, is abattery between 1.2 V and 5 V for powering the board and a 5 mm LEDthat you stick into the board at pin 13 and pin GND.ARDUINOBT MICRO-CONTROLLER BOARD26311.4.1 Setting Up the ArduinoBT EnvironmentTo set up the various components involved in this example, such asinstalling the Arduino software tool and configuring the Bluetooth settingson your computer, you need to take the following steps (this descriptionwas valid in June 2007 and is for a Mac, but similar steps apply forWindows PCs, too).1.
Create a Bluetooth serial port on your computer:1.Go to System preferences. Select ‘Bluetooth icon’.2.Select ‘Devices Tabs’ and press ‘Set Up New Device’.3.Press ‘Continue’.4.For device type, select ‘Any Device’.5.ARDUINOBT should show up in a list, select it and press ‘Continue’.6.Type passkey ‘12345’ (this is the default key set up by the factory).7.Press ‘Continue’ (then you are done with the set up).8.In ‘Devices’, you should now see ARDUINOBT (this is the defaultname set up by the factory, but you can change it if you wish).9.Select the name ARDUINOBT.10.Press ‘Edit Serial Ports’. There you can see the name of your newport, for example, ARDUINOBT-bluetoothseri-1.2. Set up the Arduino software1.Download the Arbuino software from www.arduino.cc and installit on your computer.2.Open it and select Tools.3.Select ‘microcontroller (mcu)’ and set it as ‘atmega168’.4.Select Tools.5.Select ‘Serial port’ and then the Bluetooth port that you createdearlier, for example, /dev/tty.arduinobt-bluetoothseri-1.Now you need to write your code for the board using the Arduinosoftware.
(There are plenty of tutorials available on how to do this, forexample, at www.arduino.cc/.)3. Upload your Arduino code to the board1.Press the Reset button on the Arduino board.264COMBINING ART AND ENGINEERING2.Press the ‘Upload to I/O board’ button on the Arduino software toolUI.3.After a moment, the Arduino software tool should show ‘Uploaddone’.4.Now you can start your Python script on the phone, connect overBluetooth to the Arduino board and test your functionality.11.4.2 Writing Code in the ArduinoBT EnvironmentIn a similar way to Example 59 of Chapter 7, Example 119 first scansfor Bluetooth devices until we find ARDUINOBT, the ‘nickname’ of theArduino board and then selects it. This connects the phone to the Arduinoboard by the serial port using RFCOMM communication.
The board canreceive data from the mobile phone and send data back to the mobilephone.The function bt send data1() sends the ASCII character ‘1’ to theboard to switch the LED on. The function bt send data2() sends theASCII character 0 to the board to switch the LED off. Each time the boardreceives a ‘1’ (49 in decimal format), it sends ‘1’ back to the phone whichdisplays a note dialog ‘LED on’; similarly, it sends back ‘0’ (48 in decimalformat) and the phone displays ‘LED off’.Example 119: LED on/offimport socket, e32, appuifwdef choose_service(services):names = []channels = []for name, channel in services.items():names.append(name)channels.append(channel)index = appuifw.popup_menu(names, u"Choose service")return channels[index]def connect():global sockaddress, services = socket.bt_discover()channel = choose_service(services)sock = socket.socket(socket.AF_BT, socket.SOCK_STREAM)sock.connect((address, channel))def receive():global sockdata = sock.recv(1)if data == "1":appuifw.note(u"LED on ", "info")elif data == "0":appuifw.note(u"LED off ", "info")def bt_send_data1():ARDUINOBT MICRO-CONTROLLER BOARDglobal socksock.send("1")receive()def bt_send_data2():global socksock.send("0")receive()def exit_key_handler():print "socket closed"sock.close()app_lock.signal()app_lock = e32.Ao_lock()appuifw.app.menu = [(u"LED on", bt_send_data1),(u"LED off", bt_send_data2),(u"Connect", connect)]appuifw.app.exit_key_handler = exit_key_handlerapp_lock.wait()Example 120 contains the code that runs on the Arduino board.Example 120: Arduino code LED on/offint LED = 13; // pin for LEDint RESET = 7; //reset pin for bluetoothint val = 0; // initial serial port datavoid ledOFF() {digitalWrite(LED, LOW);}void ledON() {digitalWrite(LED, HIGH);}void reset_bt(){// Reset the bluetooth interfacedigitalWrite(RESET, HIGH);delay(10);digitalWrite(RESET, LOW);delay(2000);}void setup() {reset_bt();pinMode(LED,OUTPUT);pinMode(RESET,OUTPUT);Serial.begin(115200);}void loop () {val = Serial.read();if (val != -1) {265266COMBINING ART AND ENGINEERINGif (val == 49) {ledON();Serial.print(1); // feedback to mobile phone that LED is on} else if (val == 48) {ledOFF();Serial.print(0); // feedback to mobile phone that LED is off}}}11.5Controlling Max/MSP with a PhoneA significant number of people in the art and design community usetools such as Pure Data (www.puredata.org), vvvv (http://vvvv.org) orMax/MSP or Jitter (www.cycling74.com) for interactive audiovisual applications and art installations.
vvvv is especially good for real-time videosynthesis that allows interaction with many users simultaneously.These tools provide a graphical programming environment for music,audio and multimedia. All of them allow rapid programming of powerfulaudiovisual applications running on the computer or a server beingcontrolled through multimodal interfaces. We want to show here how touse your mobile phone as a user interface for such tools. For practicalreasons on our side, we have chosen Max/MSP to get the basic ideasacross, but you can take the same approach when using one of the othersas well.First we describe how to use Bluetooth RFCOMM to set up thecommunication between PyS60 on the phone and Max/MSP on yourcomputer that will allow you to switch a sound on and off and changeits frequency.
On the phone, we use a graphical switch and slider tomanipulate the sound by sending relevant control data to Max/MSP.We then describe a mobile multi-user scenario which allows multiplepeople to interact over WiFi instead, meaning that several users at thesame time can control parameters of a sound generator using the sameMax/MSP application.11.5.1 Connecting a Phone to Max/MSP using Bluetooth RFCOMMThe patch of the Max/MSP graphical programming environment is shownin Figure 11.8.An object with the text ‘serial a 9600’ handles the serial port communication in Max/MSP. When you start Max/MSP, this object opens oneof the free serial ports of your computer. (You might have to check someadditional parameters in your computer’s Bluetooth setting if it doesn’twork straight away.)We cannot explain here the full functionality of the patch in detail,but the basic idea is that when the serial port receives the string ‘51’ overBluetooth from the phone, the frequency of the sound produced by theCONTROLLING MAX/MSP WITH A PHONEFigure 11.8Max/MSP patch using Bluetooth267268COMBINING ART AND ENGINEERINGsound generator increases.