2017年1月30日月曜日

Dart x WebBluetooth x BLE Peripheral Simulator x Eddystone 's memo (1)

WebBluetoothについて、BLEの学習も兼ねて、アレコレ遊んでみます。
Dartを利用します。

型があるので、保管機能を利用することができます。Crt+Space するだけで、何ができるのかが判断できて便利です。

欠点としては、Dartium のWebBluetoothへの対応が微妙なの事です。dart:jsで変換しないと、動作確認ができません。しかし、Dart DDC対応が完了すれば、この問題もなくなります。なので、今だけの問題といえるでしょう。



# Batteryサービスから、残量を取得してみる

とりあえず、Web Bluetooth x Dart で、HelloWorldをしてみる。

BLE Peripheral Simulator(https://github.com/WebBluetoothCG/ble-test-peripheral-android) は、Web Bluetooth の通信の実験相手をしてくれます。
とっても便利です。
ソースも公開されていますから、中身を見ながら、理解を深める事ができます。

BLE Peripheral Simulator の Batteryサービスから、バッテリー残量を取得して見ましょう。
※ BLE Peripheral Simulator は、GooglePlay からダウンロードできます。
https://play.google.com/store/apps/details?id=io.github.webbluetoothcg.bletestperipheral
※ chrome://flags よりWeb Bluetoothを有効にしてください。

===

Source
https://github.com/firefirestyle/ebook_webbluetooth_with_dart/tree/master/memo/test/hello

import 'package:angular2/core.dart';
import 'dart:html' as html;
import 'bt.dart' as b;
import 'dart:typed_data';


@Component(selector: 'my-app',
    template: """
    <h1>Hello {{name}}</h1>
    <div>
    <div *ngFor='let v of logs'>{{v}}</div>
    </div>
    <button (click)='onClick()'>Click</button>
    """
)
class AppComponent {
  var name = 'Angular';
  List<String> logs = [];

  log(String l) {
    print(l);
    logs.add(l);
  }

  onClick() async {
    b.Bluetooth bluetooth = b.getBluetooth();
    b.BluetoothDevice device = await bluetooth.requestDevice({ "filters": [{ "services": ['battery_service']}]});
    log("name : ${device.name}");
    log("id : ${device.id}");

    b.BluetoothRemoteGATTServer server = await device.gatt.connect();
    log("server.connected : ${server.connected}");

    b.BluetoothRemoteGATTService service = await server.getPrimaryService('battery_service');
    log("service.isPrimary : ${service.isPrimary}");
    log("service.uuid : ${service.uuid}");

    b.BluetoothRemoteGATTCharacteristic chara = await service.getCharacteristic('battery_level');
    log("service.uuid : ${chara.uuid}");

    ByteData buffer = await chara.readValue();
    log("service.value : ${buffer}");
    log("service.value : ${buffer.lengthInBytes}");
    log("service.value : ${buffer.buffer.asUint8List()}");
  }
}

===

参考

Web Bluetooth Draft Community Group Report, 27 January 2017


Implementation Status


LeScanは、これから
https://github.com/WebBluetoothCG/web-bluetooth/pull/239
https://webbluetoothcg.github.io/web-bluetooth/scanning.html



PS

個人的に、ネタを集めて、WebBluetoothについて、まとめる予定
たぶん以下で



2017年1月29日日曜日

AngularDart で Pinterestっぽい、Layout を試して見た。

Angular Dart で Pinterestっぽい、Design を試して見ました。
https://github.com/firefirestyle/ebook_windstyle_markdown/tree/master/angular/tiny-dynamicblock



隙間なく、四角形を詰めていくデモです。

コンストラクターで ElementRef を取得できる事がわかれば
簡単に書けますね!!

コード

main.dart

import 'package:angular2/platform/browser.dart';
import 'package:angular2/core.dart';
import 'dart:async';
import 'dart:html' as html;
import 'dynablock.dart' as dyna;
import 'dart:math';

main() {
  bootstrap(AppComponent);
}

class DynamicItemParam {
  int w;
  int h;

  DynamicItemParam() {
    Random rnd = new Random();
    w = rnd.nextInt(100) + 50;
    h = rnd.nextInt(200) + 100;
  }
}

@Component(
  selector: 'dynamicitem',
  template: """
  xxx
  """,
)
class DynamicItem implements OnInit {
  @Input()
  DynamicComponent parent;

  @Input()
  int width = 100;

  @Input()
  int height = 200;

  final ElementRef element;

  DynamicItem(this.element) {
    (element.nativeElement as html.Element).style.width = "${width}px";
    (element.nativeElement as html.Element).style.height = "${height}px";
    (element.nativeElement as html.Element).style.color = "#FF00";
    (element.nativeElement as html.Element).style.padding = "0px";
    (element.nativeElement as html.Element).style.margin = "0px";
    (element.nativeElement as html.Element).style.backgroundColor = 'yellow';
    (element.nativeElement as html.Element).style.display = 'inline-block';
    (element.nativeElement as html.Element).style.border =
    "medium solid #333333";
  }

  ngOnInit() {
    print("xx1 ${element.nativeElement}");
    (element.nativeElement as html.Element).style.width = "${width}px";
    (element.nativeElement as html.Element).style.height = "${height}px";
    if (parent != null) {
      parent.append(this);
    }
  }
}


@Component(
  selector: 'markdown-component',
  directives: const [DynamicItem],
  template: """
  <div #markdowncontent>
    <dynamicitem  *ngFor='let c of contents' [parent]='own' [width]='c.w' [height]='c.h' ></dynamicitem>
  </div>
  """,
)
class DynamicComponent implements OnInit {
  @Input()
  List<DynamicItemParam> contents;
  List<DynamicItem> items = [];

  html.Element _contentElement;
  dyna.DynaBlockCore dynaCore = new dyna.DynaBlockCore();


  final ElementRef element;
  DynamicComponent own;

  DynamicComponent(this.element) {
    var elm = element.nativeElement;
    elm.style.position = "absolute";
    own = this;
  }

  @ViewChild('markdowncontent')
  set main(ElementRef elementRef) {
    _contentElement = elementRef.nativeElement;
    print("${elementRef} ${elementRef.nativeElement}");
    _contentElement.onChange.listen((e) {
      print("-a");
    });
  }

  append(DynamicItem ap) {
    print("XXS");
    var elm = ap.element.nativeElement;
    int margineW = 10;
    int margineH = 10;
    dyna.FreeSpaceInfo info = dynaCore.addBlock(
        ap.width + margineW, ap.height + margineH);
    elm.style.position = "absolute";
    elm.style.left = "${info.xs}px";
    elm.style.top = "${info.y}px";
  }

  ngOnInit() {
  }
}

@Component(
    selector: 'my-app',
    directives: const [DynamicComponent],
    template: """
    <markdown-component [contents]='contents'></markdown-component>
  """
)
class AppComponent implements OnInit {
  List<DynamicItemParam> contents = [
    new DynamicItemParam(),
    new DynamicItemParam(),
    new DynamicItemParam(),
    new DynamicItemParam(),
  ];

  ngOnInit() async {
    for (int i = 0; i < 10; i++) {
      contents.add(new DynamicItemParam());
      await new Future.delayed(new Duration(milliseconds: 500));
    }
  }
}


四角形を埋め尽くすアルゴ

https://github.com/firefirestyle/ebook_windstyle_markdown/blob/master/angular/tiny-dynamicblock/app/web/dynablock.dart


2017年1月28日土曜日

火の型 Scratchでプログラム入門 固定レイアウト版 おまけ010-012はFIXしたと見なす

三角関数(1) 万有引力をシミュレーションしてみよう
https://firebook.firefirestyle.net/presents010.html



三角関数(2) 角度を指定して移動しよう
https://firebook.firefirestyle.net/presents011.html



三角関数(3) 万有引力をシミュレーションしてみよう
https://firebook.firefirestyle.net/presents012.html



以降はGitbookを参照してください。
https://www.gitbook.com/book/kyorohiro/firestyle/details
100pageくらいあります。

AngularDart で Markdownを利用してみる

AngularDart で Markdownを利用してみた。
"#" と、@ViewChild を利用の仕方を覚えた!!

https://github.com/firefirestyle/ebook_windstyle_markdown/tree/master/angular/tiny-markdown

import 'package:angular2/platform/browser.dart';
import 'package:angular2/core.dart';
import 'dart:async';
import 'dart:html' as html;
import 'package:markdown/markdown.dart' as mark;

main() {
  bootstrap(AppComponent);
}


@Component(
  selector: 'markdown-component',
  template: """
  <div #markdowncontent></div>
  """,
)
class MarkdownComponent implements OnInit {
  @Input()
  String content;

  html.Element _contentElement;

  @ViewChild('markdowncontent')
  set main(ElementRef elementRef) {
    _contentElement = elementRef.nativeElement;
  }

  ngOnInit() {
    _contentElement.children.clear();
    _contentElement.children.add(new html.Element.html(
        """<div>${mark.markdownToHtml(content)}</div>""",
        treeSanitizer: html.NodeTreeSanitizer.trusted)
    );
    print(">> ${content}");
  }
}

@Component(
    selector: 'my-app',
    directives: const [MarkdownComponent],
    template: """
    <markdown-component [content]='content'></markdown-component>
  """
)
class AppComponent {
  String content = """
# H1
aasasdfa;lklasdf
  """;
}



2017年1月27日金曜日

火の型 Scratchでプログラム入門 固定レイアウト版 おまけ00D-00FはFIXしたと見なす

雪を降らせてみる

Scratchの clone機能を利用してみよう

https://firebook.firefirestyle.net/presents00d.html




カーソルに向かって進ませてみる

Scratchの向きと前進で移動させてみよう。

https://firebook.firefirestyle.net/presents00e.html





ランダムに会話


Scratchのリスト機能を利用してみよう
https://firebook.firefirestyle.net/presents00f.html




以降はGitbookを参照してください。
https://www.gitbook.com/book/kyorohiro/firestyle/details
100pageくらいあります。

AngularDart RouteParams.params は UrlEncodeされたまま

OAuthの認証っぽいコードを書いていて、
URLの中にAccessTokenを渡すような書き方をしてみた。

その時に、渡されたパラメータが、UrlEncodeが必要な事に気がついた。


import 'package:angular2/core.dart';
import 'package:angular2/router.dart';
import 'package:cl/config.dart' as config;


@Component(
    selector: "myhome",
    template:  """
    <div class="mybody">
    <h1>Home</h1>
    </div>
  """,
    styles: const[
      """
    .mybody {
      display: block;
      height: 600px;
    }
    """,
    ]
)
class HomeComponent implements OnInit {
  String twitterLoginUrl = "";
  final RouteParams _routeParams;
  HomeComponent(this._routeParams);
  config.AppConfig rootConfig = config.AppConfig.inst;

  ngOnInit() {
    twitterLoginUrl =  config.AppConfig.inst.twitterLoginUrl;
    print(_routeParams.params.toString());
    if(_routeParams.params.containsKey("token")) {
      config.AppConfig.inst.cookie.accessToken = Uri.decodeFull(_routeParams.params["token"]);
      config.AppConfig.inst.cookie.setIsMaster(_routeParams.params["isMaster"]);
      config.AppConfig.inst.cookie.userName = Uri.decodeFull(_routeParams.params["userName"]);
    }
  }
}
===

それは、そうだよなぁ...。
バイナリーデータが渡される事もあるわけだし

と、しかし、
Url.decodeFull()にバイナリデーターが返るような値を渡すと

どんな感じになるのだろうか?



AngularDartを利用して Inputタグで画像を読み込むダイアログ。(2) 関数渡しをしてみる

前回のを、もう少し、賢くしてみました。

関数やパラメータを渡せるようにする
初期化しなくても動作するようにする
エラーメッセージ等を呼び出せるようにする


https://github.com/firefirestyle/ebook_windstyle_markdown/tree/master/angular/image-input-dialog/app


dialog.dart

import 'package:angular2/core.dart';
import 'package:angular2_components/angular2_components.dart';
import 'dart:html' as html;
import 'imageutil.dart' as imgutil;
import 'dart:async';


@Component(
  selector: 'inputimage-dialog',
  styles: const [
    """
    .inputimage-dialog-title {
    }
    .inputimage-dialog-message {
    }
    .inputimage-dialog-errormessage {
    }
    .inputimage-dialog-cancelbutton{
    }
    .inputimage-dialog-okbutton{
    }
    """,
  ],
  template: """
<modal #wrappingModal>
  <material-dialog style='width:80%'>
    <div *ngIf='errorMessage!=""' class='inputimage-dialog-errormessage'>{{errorMessage}}</div>
    <h3 class='inputimage-dialog-title' header>{{param.title}}</h3>
    <p class='inputimage-dialog-message'>{{param.message}}</p>
    <material-spinner *ngIf='isloading'></material-spinner>
    <div #imgc></div><br>
    <input #in *ngIf='isloading==false' type="file" id="upload" (change)='onInput(in,imgc)'>
    <div footer>
      <material-button *ngIf='isloading==false' autoFocus clear-size (click)="onCancel(wrappingModal)" class='inputimage-dialog-cancelbutton'>
        {{param.cancel}}
      </material-button>
      <material-button *ngIf='currentImage!=null||isloading==false' autoFocus clear-size (click)="onFile(wrappingModal)" class='inputimage-dialog-okbutton'>
        {{param.ok}}
      </material-button>
    </div>
  </material-dialog>
</modal>
  """,
  directives: const [materialDirectives],
  providers: const [materialProviders],
)
class InputImageDialog implements OnInit {
  @ViewChild('wrappingModal')
  ModalComponent wrappingModal;

  @Input()
  InputImageDialogParam param;

  bool isloading = false;
  html.ImageElement currentImage = null;
  String errorMessage = "";

  ngOnInit(){
    if(param == null) {
      param = new InputImageDialogParam();
    }
  }

  void open() {
    wrappingModal.open();
  }

  onCancel(ModalComponent comp) {
    wrappingModal.close();
  }

  onFile(ModalComponent comp) async {
    isloading = true;
    try {
      var ret = await param.onFile(this);
      if (ret != "" && ret != null) {
        errorMessage = ret;
      } else {
        errorMessage = "";
        wrappingModal.close();
      }
    } catch (e) {
      errorMessage = "failed to (${e})";
    } finally {
      isloading = false;
    }
  }

  onInput(html.InputElement i,html.DivElement c) async {
    isloading = true;
    try {
      c.children.clear();
      if(i.value.length <= 0) {
        return;
      }
      var img = await imgutil.ImageUtil.loadImage(i.files.first);
      var img1 = await imgutil.ImageUtil.resizeImage(img);
      c.children.add(img1);
      currentImage = img1;
    } catch(e){
      errorMessage = "failed to (${e})";
    } finally{
      isloading = false;
    }
  }
}

typedef Future<String> OnFileFunc(InputImageDialog d);

class InputImageDialogParam {
  String title;
  String message;
  String ok;
  String cancel;
  int get imgWidth => 300;
  int get imgHeight => -1;
  OnFileFunc onFileFunc;

  InputImageDialogParam({this.title:"File",this.message:"select file!!",this.ok:"OK",this.cancel:"Cancel",
  onFileFunc: null}){
  }

  /**
   * if failed to do onFind func, then return error message.
   */
  Future<String> onFile(InputImageDialog d) async {
    if (onFileFunc == null) {
      return "";
    } else {
      return onFileFunc(d);
    }
  }
}

====


main.dart


import 'package:angular2/platform/browser.dart';
import 'package:angular2/core.dart';
import 'dialog.dart';

void main() {
  bootstrap(AppComponent);
}

@Component(
    selector: "my-app",
    directives: const [InputImageDialog],
    template: """
    <div>
    <h1>Dialog Test</h1>
    <div>
    <button (click)='onClick(myDialoga)'>open</button>
    </div>
    <inputimage-dialog #myDialoga [param]='param'>
    </inputimage-dialog>
    </div>
  """
)
class AppComponent implements OnInit {
  final InputImageDialogParam param = new InputImageDialogParam();

  AppComponent();
  ngOnInit() {
  }
  onClick(InputImageDialog _dialog) async {
    _dialog.open();
  }
}

====

InputImageDialogParam を用意して、デフォルト値を持たせるようにして
初期化は必須で無くした。

onFIle()メソッドを追加して、後から機能を拡張できるようにしてみた。


うーむ
徐々に汎用的な部品が作れるようになってきたかな。
まだ、微妙かな



Game Boy の VGM から JavaScript への変換後に、 生成AIの補正が有効だった事について

Game Boy の VGM から JavaScript への変換後に、 生成AIの補正が有効だった事について Tetorica FM2612 Playground には GameBoy や Genesis の VGM ファイル から JavaScript へ変換する機能を持って...