On coding, tech, privacy, AI and whatever else comes to this mind.

  • Tech Note: Keyboard shortcuts and the iOS responder chain
  • Tech Note: Good practices for RxSwift-based view models
  • Tech Note: Getting push notifications for fastlane errors
  • Hey Siri, pre-heat my car

    When I got my Renault Zoe, I was excited to see that it came with an accompanying app, which let’s you remotely pre-heat (or cool) the car and also check the charge status of the battery. Being able to pre-condition the car is great as the process takes a few minutes and it’s nice when it’s finished by the time you’re getting into the car. And having remote access to the charging status is especially handy on road trips: Firstly, it’s annoying to go back to the car and find that it still needs to charge for another half hour and you could have gotten a coffee or went for a nice walk. Secondly, you might be wasting money by remaining plugged in when the car is already full, if you’re getting charged by the minute. So there’s real utility to such an app.

    The excitement about the app didn’t last too long. It feels neglected, is slow to use, and routinely forgets my login credentials. It doesn’t support current OS features such as the iPhone X-sized screen, Siri or Shortcuts either.

    However, luckily the app is built using an API that other curious minds have since reverse-engineered – Kudos in particular to Terence Eden and aironaut.ch for sharing their insights. This allows you to replicate the features of the app in a different package.

    What I wanted to do was this: Be able to use Siri on my phone or watch to ask “How’s my car” to get the charging status, and “Pre-heat my car” to start pre-heating it.

    Knowing the API is the first half, the second half is picking a tool that let’s me query the API from Siri. This should be possible with Apple’s Shortcuts app, but I prefer to use a textual rather than visual programming language. The right tool for me was the excellent Pythonista which has a beta version available that adds support for running scripts via Siri and the Shortcuts app.

    The result: I can now say “Hey Siri, pre-heat Moritz” and a few seconds later it’ll start pre-heating, or say “How’s Moritz?” and get the current charge, current range, and when it’ll reach 100% charge. I can also trigger both of those without saying a word through the Shortcuts widget on my lock screen. Works like a charm!


    If anyone wants to replicate this, below is the script. Copy it into Pythonista, adjust your username and password, optionally set a custom name for the car. Then use Pythonista’s built-in feature to add Siri Shortcut to use it with Siri. By default this will run the “battery status” part, for the pre-conditioning use a single argument precondition. Once you’ve added the command to Siri, you can also use it in the Shortcuts app.1

    #!python3
    
    import datetime
    import requests
    import shortcuts
    import sys
    
    username = "you@domain.com"
    password = "YourPassw0rd"
    carname = "Zoe"
    
    ### Fetches auth token and VIN
    def login():
      headers = {"Content-Type": "application/json"}
      body = {"username": username, "password": password}
      url = f"https://www.services.renault-ze.com/api/user/login"
      
      result = requests.post(url, json=body, headers=headers).json()
      token = result['token']
      vin = result['user']['vehicle_details']['VIN']
      return {"token": token, "vin": vin}
      
    def get_battery():
      creds = login()
      headers = {"Authorization": f"Bearer {creds['token']}"}
      url = f"https://www.services.renault-ze.com/api/vehicle/{creds['vin']}/battery"
      
      result = requests.get(url, headers=headers).json()
      if result['charging']:
        minutes = result['remaining_time']
        remaining = fuzzy_duration(minutes)
        status = f"done charging in {remaining}"
      else:
        status = "is not charging"
      return f"{carname} can go {result['remaining_range']}km. Battery is {result['charge_level']}% full and {status}."
      
    def fuzzy_duration(minutes):
      if minutes < 90:
        return f"{minutes} minutes"
      if minutes < 3 * 60:
        half_hours = round(minutes / 30) / 2
        return f"{half_hours} hours"
      else:
        hours = round(minutes / 60)
        return f"{hours} hours"
        
    def precondition():
      creds = login()
      headers = {"Authorization": f"Bearer {creds['token']}"}
      url = f"https://www.services.renault-ze.com/api/vehicle/{creds['vin']}/air-conditioning"
      result = requests.post(url, headers=headers)
      if 200 <= result.status_code < 300:
        return f"{carname} is warming up"
      else:
        return f"{carname} is not responding"
      
    def main():
      if len(sys.argv) > 1 and sys.argv[1] == "precondition":
        text = precondition()
      else:
        text = get_battery()
        
      if shortcuts.is_shortcut():
        shortcuts.set_spoken_output(text)
      else:
        # For debugging in the main app (normally, this script would run in a Siri shortcut):
        print(text)
          
    if __name__ == '__main__':
      main()
    

    Changelog:

    1. For detailed steps on how to do this, see a related post on the Pythonista forum. ↩


  • Tech Note: Sharing iCloud Drive documents from your app
  • Switching Mojave's dark and light themes using touch bar

    Mac OS Mojave introduces both a pretty dark mode and a way to trigger Automator scripts right from the Touch Bar. The two go together nicely:

    1. Open Automator and create a “Quick Action”. This should receive “no input” and have a single “Run AppleScript” action with the following content:
    tell application "System Events"
      tell appearance preferences
        set dark mode to not dark mode
      end tell
    end tell
    
    1. Save it, which will then land in your ~/Library/Services folder.
    2. In your System Preferences > Keyboard > “Customise Touch Bar…”, drag the “Quick Actions” to your Touch Bar.

    And – bam! – two taps on the Touch Bar, and you toggle between light and dark.


    I also tried (desperately) to switch the accent colour at the same time, but to no avail. The script below shows that there’s highlight color: orange, but I couldn’t get this to work. I’d appreciate any help from AppleScript pros.

    tell application "System Events"
      tell appearance preferences
        get properties
        set highlight color to orange -- does nothing visually, though it does change that property :(
      end tell
    end tell
    

  • Tech Note: RxSwift in custom views, the clean way
  • Tech Note: Importing app module in unit test fails to compile
  • iPad Pro 12.9 vs. 10.5

    The iPad Pro is a great device and I’ve been happily using the 12.9 inch model for a good 1.5 years. At times it felt too large though – especially when using it on the couch. So when I got the chance to get a new iPad for work, I decided to give the 10.5 inch model a try. What follows are my observations after a few months of using the 10.5 inch model running iOS 11.

    On the screen real estate:

    1. Having two apps in 50/50 split screen mode gives both the iPhone appearance, i.e., you typically just get a single column of content, not two.
    2. However, several apps, such as Safari gets a special mode for when it is in a 50/50 split with another app or you use its own split screen mode: you get a toolbar on the bottom like on an iPad, but you still get the tabs at the top as when using fullsceen.
    3. No more 3-column views when using Apple’s apps full-screen. Say, in Mail you don’t have a view where you can see both the message, the list of messages and the list of folders. I used this a fair bit to quickly drag and drop messages to folders, and this is simply not possible – you never get to see both the list of messages and the list of folders on one screen. The same applies to Notes. However, third-party apps behave differently and, say, Ulysses and Bear still have the three column view.
    4. You only get 13 slots in the Dock, not 15. However, when you cram it full and have the recent apps visible on the right, the tap targets become so small in portrait mode that I had several cases of hitting the wrong app, which is something that never happened on the 12.9. I’m sticking to 11 apps plus the recent ones because of that.

    On the software keyboard:

    1. You don’t get the additional keyboard row with numbers, but you do get the swipe down on keys to get to numbers and special characters.
    2. You also don’t get a tab key (nor a caps lock key). Makes filling in forms slower and a disadvantage if you do coding on the iPad.
    3. 10 finger typing on the software keyboard is also possible. Took me less than a day to adjust and I feel like I am making less mistakes on the 10.5 inch screen than in the 12.9 one.
    4. No more oversized old software keyboard for apps that haven’t yet been updated for the 12.9 size - unfortunately that’s still quite a few apps. You still notice those apps as the lack of being optimised for the 10.5 inch screen means they don’t look as sharp as updated apps.

    On the pencil:

    1. My primary use case on the pencil is hand-written notes and sketches. The 10.5 works just fine for that.

    My summary: I feel less of a need to always use split screen mode as fullscreen apps don’t overwhelm you as easily as on the large iPad. I missed the 3-column views initially, but adopting my workflow for sorting my mails did not take long. I’m very happy with the “tiny” iPad. It’s good for typing, more suitable for the couch and much more portable.


  • Google does not get privacy

    Sundar Pichai, CEO of Google, in an interview with Walt Mossberg at Recode’s Code Conference 2016 1:

    We want you to be able to tell Google: maybe the last four hours, just take it off and go off the record. […] you can switch on in-cognito mode. […] I want to save every conversation that I have with my daughter for eternity […]; but some other converations, […] maybe with my general council at Google, I want to be private.

    Google has a binary view on privacy. Things are either on the record or off the record—with the default being the former.

    For things that are “on the record”, Google’s terms of service they are very explicit about what they can do with it. Namely:

    • You grant them “a worldwide license to use, host, store, reproduce, modify, create derivative works […], communicate, publish, publicly perform, publicly display and distribute such content”,
    • and, of course, to “analyze your content (including emails) to provide you personally relevant product features, such as customized search results, tailored advertising […]”,
    • and lastly, “this license continues even if you stop using our Services”. 2

    But, to many people, privacy isn’t that simple and not binary. Consider the following examples:

    • You might keep a journal, which you want to have accessible even many years later.
    • Private conversations that you have with your child.

    Would you want those things to be “on the record”? While many people trust Google with that data, as Pichai points, it is questionable whether they are fully aware of who is getting what kind of license and access to their content, when they are using their phone or computer.

    For people who do not want these things on the record, while still getting the benefit of them being safely backed up and synchronised between multiple devices, Google provides no help; there is no option in between that lets you get benefits of using cloud services but without granting all these rights to Google.

    If Google wanted to truly get better at privacy, they would do the following:

    1. Revise the terms of use and don’t apply the above mentioned license to all the user’s content, but just to content that the user shares publicly or with a certain set of users.
    2. Make content private by default rather than “on the record” by default.
    3. Enable end-to-end encryption by default where possible when sharing data between users.

    As hinted at in the interview, Google wants to tackle the second point by using machine learning to infer defaults better than using their currently manual heuristics; that’s a good start. They also should do more on email encryption, and they should enable end-to-end encryption by default on their new Allo app—that would bring them on par with iMessage, Whatsapp and, soon, Facebook Messenger. The big one though is the first point; it is possible as Apple demonstrates 3, but it is a shame that Google’s business model gives them limited incentive to follow suit.

    1. Longer transcript of what Sundar Pichai said (slightly paraphrased by me for readability):

      For me: The onus is on us to give enough value that people trust us. Privacy is something that machine learning and AI at Google will help us to do better. Lots of times, it is hard to do privacy because we rely on manual heuristics and how to go to give you manual controls and settings to do these things. But we do these better. Very soon you will be able to give your name to Google and we’ll pop up your My Account settings and control all of that. About a billion people went through these settings in the last year alone. But all the time we want to get even better, we want you to be able to tell Google: maybe the last four hours, just take it off and go off the record. We can do these kind of things. When you use Chrome, you can use it any way you want, you can switch on in-cognito mode, if you want to; we are doing it the same with the messaging product. We give users choice. All the time, we get smarter to give users sophisticated privacy controls. You know, I want to save every conversation that I have with my daughter for eternity, and because I want to be able to go back, look back and et cetera; but some other conversations, I want to, maybe with my general council at Google, I want to be private. I want to be able to do those things and we want to be smart about it all those times.

      ↩

    2. Expanded extract:

      When you upload, submit, store, send or receive content to or through our Services, you give Google (and those we work with) a worldwide license to use, host, store, reproduce, modify, create derivative works […], communicate, publish, publicly perform, publicly display and distribute such content. The rights you grant in this license are for the limited purpose of operating, promoting, and improving our Services, and to develop new ones. This license continues even if you stop using our Services […] Our automated systems analyze your content (including emails) to provide you personally relevant product features, such as customized search results, tailored advertising, and spam and malware detection.

      ↩

    3. Licensing terms for Content in Apple’s iCloud terms (highlight mine):

      […] by submitting or posting such Content on areas of the Service that are accessible by the public or other users with whom you consent to share such Content, you grant Apple a worldwide, royalty-free, non-exclusive license to use, distribute, reproduce, modify, adapt, publish, translate, publicly perform and publicly display such Content on the Service solely for the purpose for which such Content was submitted or made available, without any compensation or obligation to you.

      ↩


subscribe via RSS or via JSON