iphone is the best phone to sell? Use Python to get him to play with applause!

Source: Internet
Author: User

There are a lot of technical explanations for IOS, but there are few introductory articles for device visualization synchronization. Learn about this cool IOS black technology together with this article.

Our task is simple-get the current direction of the device in real time, as shown in.

UIDevice.current.orientation

First, you need to call

But that's just not enough. Because if the rotation on the device is locked, the above notification is not generated. My camera application needs to know the direction from start to finish-so I realize I need to calculate the direction directly based on the acceleration of the device.

Well, now that we have these values, what should we do? This is a more difficult part. If everything is output to the console, then we will soon be overwhelmed by a lot of data. I think it's better to show these values on the screen.

But, wait, what happens if the values are displayed on the chart? Don't think about the chart, we can try it with open source Blender, which can visualize these values and easily expand.

However, Blender is not a very good code editor, so let's use a favorite external editor. In order to invoke the external file, we can replace print ("HI") with the following code:

import bpyimport osfilename = os.path.join(os.path.dirname(bpy.data.filepath), "server.py")exec(compile(open(filename).read(), filename, ‘exec‘))

Next, we need to create a new server.py file in the same folder as the. blend file, and our real code will be saved here. Now that we can open it with any editor, you can choose Atom, Sublime, or even Word 2007.

Locate the Cube object, right-click and choose Rename, rename to IPhone. Now let's take a look at server.py.

Import socketimport selectimport jsonimport threadingimport tracebackclass serverthread (threading. Thread): def __init__ (self): threading. Thread.__init__ (self) self.running = True def stopserver (self): self.running = False self.server.running = False Def run (s ELF): Try:self.server = Server () while self.running:self.server.receive () Except:passclass server:def __init__ (self): Self.socket = Socket.socket (socket.af_inet, socket. SOCK_STREAM) self.socket.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) self.socket.setblocking (False) self.socket.bind ((str) (socket. Inaddr_any), 9845)) Self.socket.listen (2) self.running = True def __exit__ (self, exc_type, Exc_value, traceback): self.so Cket.close () def receive (self): pairs = [] Timeout = 1 while self.running:sockets = list (map (lambda x:x[0], pairs)) if L En (Pairs) > 0:read_sockets, write_sockets, error_sockets = Select.select (sockets, [], [], timeout) for sock in Read_so Ckets:data = SOCK.RECV (4096) if not data:print (' Client Disconnected ') pairs = [] Else:self.connectionReceivedData (Connection, Data.decode ()) try:try:connection,address = Self.sock Et.accept () print ("New connection:", Connection) Pairs.append ((connection, address)) Except:pass Except:pass for pair I N Pairs: (connection, address) = Pair Connection.close () def connectionreceiveddata (self, Connection, data): Try:motionda TA = json.loads (data) except Json.decoder.JSONDecodeError:print ("Invalid JSON:", data) return None Receivedmotiondata (m Otiondata) # This was a global so when we run the script again, we can keep the server alive# and how it worksimport Bpydef Receivedmotiondata (motiondata): Phone = bpy.context.scene.objects["IPhone"] phone.rotation_quaternion.x = Float (motiondata[' x ']) PHONE.ROTATION_QUATERNION.Y = 0-float (motiondata[' z ']) phone.rotation_quaternion.z = float ( motiondata[' y ']) PHONE.ROTATION_QUATERNION.W = float (motiondata[' W ')) passtry:if serverthread.running = = False: Serverthread = Serverthread () Serverthread.start (Print ("Starting server") Else:print ("Server already running, using new motion handler.") Except:serverthread = Serverthread () Serverthread.start () print ("Starting server")

Check Blender and you should see that the iPhone hasn't changed at all. This is because the script above uses a four-tuple to set the IPhone's rotation angle, and it uses Euler angles to rotate. Some changes need to be made. Switch the Python control table to Properties, and then click the Orange Cube icon at the top of the panel. Below the central Transform, click XYZ Euler and select Quaternion. Now try running client.py again.

You should see the iPhone flipping over immediately. Don't panic, that's what we want. Now, we need to make this model rotate with the actual iPhone.

We need to send motion data from the IPhone to the computer running Blender. Thank God we don't need to go deep into the original C socket level in Swift, because the Foundation has an abstraction.

We can put the following code in the new IOS project to replace the default Viewcontroller. Be sure to replace the host variable with the local IP address of the computer.

Import Uikitimport Coremotionclass Coremotionviewcontroller:uiviewcontroller, streamdelegate {Let MotionManager = Cmmotionmanager () Let queue = Operationqueue () Let host = "192.168.1.2" override func Viewdidload () {super.viewdidload () Setupstreams (host:host) motionmanager.startdevicemotionupdates (to:queue) {(data:cmdevicemotion?, Error:error?) in Guard Let data = Data else {print ("Error: \ (error!)") return} let Attitude:cmattitude = data.attitude let quaternion = attitude.quaternion var motiondata = motiondata () motiondata.x = quaternion.x Motiondata.y = quaternion.y motionData.z = q Uaternion.z MOTIONDATA.W = QUATERNION.W Let encoder = Jsonencoder () does {let JSON = Try Encoder.encode (motiondata) self.se nd (Data:json)} catch let error {print ("couldn ' t send data, error: \ (Error)")}}}//MARK:-Streams var InputStream: InputStream? var outputstream:outputstream? Func Setupstreams (host:string) {var readstream:unmanaged<cfreadstream>? var writestream:unmanaged< Cfwritestream>? Cfstreamcreatepairwithsockettohost (Kcfallocatordefault, host as Cfstring, 9845, &readstream, &writeStream) InputStream = readstream!. Takeretainedvalue () OutputStream = writestream!. Takeretainedvalue () guard Let InputStream = InputStream, let OutputStream = OutputStream else {print ("Failed to create St Reams ") return} inputstream.delegate = self outputstream.delegate = self inputstream.schedule (in:. Current, Formode:. com Monmodes) Outputstream.schedule (in:. Current, Formode:. Commonmodes) Inputstream.open () Outputstream.open ()} func send (Data:data) {Guard Let OutputStream = OutputStream else {return} _ = data.withunsafebytes {Outputstream.write ($, maxlength:data.  Count)}} the Func stream (_ Astream:stream, handle eventCode:Stream.Event) {if EventCode = =. erroroccurred {InputStream = Nil OutputStream = nil print ("Error:stream Error")} else if EventCode = =. endencountered {InputStream = nil Outputstre am = Nil print ("error:encountered End of Stream")} Let Maxreadlength = 4096 if EventCode = =. hasbytesavailable {guard Let InputStream = InputStream else {return} Whil E inputstream.hasbytesavailable {Let buffer = unsafemutablepointer<uint8>.allocate (capacity:maxreadlength) Inputstream.read (buffer, maxlength:maxreadlength) Buffer.deallocate ()}}}}//MARK:-Data modelprivate struct MOTIONDAT a:codable {var x:double = 0 var y:double = 0 var z:double = 0 var w:double = 0}

So how did I end up getting direction information from the Mobile Manager?

Welcome to my Blog or public number: Https://home.cnblogs.com/u/Python1234/Python Learning Communication

Welcome to join my thousand People Exchange learning questions: 125240963

iphone is the best phone to sell? Use Python to get him to play with applause!

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.