angular2-webpack-starterにsocketioを追加してみる

angular2-webpack-starterにsocketioを追加してみる


angular2-webpack-starter

ここに説明がある angular2 starter  /  リポジトリ repository

ファイルの追加

赤字を追加、青字を編集。

  • angular2-webkit-starter
  • server
    • server.js
  • src
    • app
      • +barrel
      • +detail
      • about
      • sockets
        • index.ts
        • sockets.service.ts
      • home
      • no-content
      • app.component.css
      • app.component.spen.css
      • app.component.ts
      • app.e2d.ts
      • app.module.ts
      • app.resolver.ts
      • app.routes.ts
      • environmemt.ts
      • index.ts

npm moduleの追加

  • webpack-hot-middleware
  • socket.io-client
  • @type/socket.io-client
npm install webpack-hot-middleware --savedev
npm install socket.io-client --save
npm install @type/socket.io-client --savedev

server.jsの追加

server/server.js


const http = require('http');
const express = require('express');

const webpack = require('webpack');
const webpackConfig = require('../webpack.config.js');
const compiler = webpack(webpackConfig);

const app = express();
app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: webpackConfig.output.publicPath,
}));
app.use(require('webpack-hot-middleware')(compiler));
app.use(express.static('dist'));
const server = new http.Server(app);
const PORT = process.env.PORT || 3000;

server.listen(PORT);

/*
 socketio
*/
var io = require('socket.io')(server);
io.on('connection', function(socket){    
  socket.on('socketTest', function(){
    console.log('getEmmit!!!');
    socket.emit('retSocketTest');
  });
});

socket serviceの追加(/app/shared)

index.ts, socket.service.ts

index.tsの追加

export * from './sockets.component';
socket.service.tsの追加

import { Injectable, OnDestroy } from "@angular/core";
import * as io from "socket.io-client";

@Injectable()
export class SocketService implements OnDestroy{
    private socket: SocketIOClient.Socket;

    constructor() {
        this.socket = io.connect();
        this.socket.on('retSocketTest', () => {
            console.log('retSocketTest');
        })
    }
    public test(){
        this.socket.emit('socketTest');
    }
    public ngOnDestroy() {
        console.log('socketio close');
        this.socket.close();
    }
}

socketsコンポーネントの追加(/app/sockets)

index.ts, sockets.component.ts

index.tsの追加

export * from './sockets.component';
sockets.component.tsの追加

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { SocketService } from '../shared';

@Component({
  selector: 'sockets',
  providers: [ SocketService ],
  template:`
    <h1>Sockets</h1>
  `
})
export class SocketsComponent implements OnInit {
  private socketData : any;
  constructor( private socketService: SocketService ){
  }
  public ngOnInit(){
    console.log('sockets');
    this.socketService.test();    
  }
}

app.componentコンポーネントの修正(/app)

app.module.ts, app.route.ts, app.component.ts

app.module.tsの修正
SocketComponentをngModuleに追加
//追加
import { SocketComponent } from './sockets';

@NgModule({ bootstrap: [ AppComponent ],
declarations: [
...

SocketsComponent
],

赤字を追加
app.route.tsの修正
socket.componentのrouteを追加
//追加
import { SocketsComponent } from './sockets';

export const ROUTES: Routes = [ ...
{ path: 'sockets', component: SocketsComponent }, <<< 追加


//---------------
path :'**'より下に追加すると、ルーティングされない。
app.component.tsの修正
@Component({
template: `
<nav>
...
//追加
<a [routerLink]=" ['./sockets'] "
routerLinkActive="active" [routerLinkActiveOptions]= "{exact: true}">
Sockets
</a>
...
これで、socketsページを表示すると、 クライアントからサーバに'socketTest'がemitされ、 サーバから、'retSocketTest'が返送される。


ここまでで、socketioが追加できた。


サーバ側にmongodbを追加する。 socket.componentでmongodbデータを取得できるようにする。

ファイルの追加

赤字を追加、青字を編集。

  • angular2-webkit-starter
  • server
    • server.js
  • src
    • models
      • index.ts
      • sockets-item.model.ts
    • app
      • +barrel
      • +detail
      • about
      • sockets
        • index.ts
        • sockets.service.ts
      • home
      • no-content
      • app.component.css
      • app.component.spen.css
      • app.component.ts
      • app.e2d.ts
      • app.module.ts
      • app.resolver.ts
      • app.routes.ts
      • environmemt.ts
      • index.ts

npm moduleの追加

  • mongodb
npm install mongodb --save

server.jsにmongodb追加

server/server.js

socketio部にmongodbを追加して置き換え

/*
 socketio
*/
var io = require('socket.io')(server);
/*
 mongodb
*/
var Promise = require("bluebird");
var MongoDB = Promise.promisifyAll(require("mongodb"));
var MongoClient = Promise.promisifyAll(MongoDB.MongoClient);
var MONGO_URL = 'mongodb://127.0.0.1:27017/test';

io.on('connection', function(socket){    
  socket.on('socketTest', function(){
    console.log('getEmmit!!!');
    socket.emit('retSocketTest');
  });
  socket.on('mongoRead', function(){
    console.log('getEmmit!!!');
    MongoClient.connectAsync('mongodb://localhost:27017/myTest').then(function(db) {
      return db.collection("myTest").find({}).toArrayAsync();
    }).then(function(orders) {
      console.log('then1', orders);
      socket.emit('retMongoRead', orders);
    }).catch(function(err) {
      console.log('then2', err);
    });
  });
});

socket service用のmodelの追加

index.ts, socket-item.model.ts

src/modelsフォルダを作成して、ファイルを追加する。
index.tsの追加

export * from "./socket-item.model";
socket-item.model.tsの追加

export interface ISocketItem {
    action: string;
    item: any;
}

socket.service/socket.componentsの変更

index.ts, socket.service.ts

socket.onをovserveし、socket.componetsでscribeして読む。
socket.serviceの変更

import { Injectable, OnDestroy } from "@angular/core";
import { Observable } from "rxjs";
import * as io from "socket.io-client";
import { ISocketItem } from "../../models";

@Injectable()
export class SocketService implements OnDestroy{
    private socket: SocketIOClient.Socket;
    private mongoData: any;

    constructor() {
        //this.socket = io.connect();
        this.socket = io.connect();
    }
    public get(): Observable{
        return Observable.create((observer: any) => {
            this.socket.on("retSocketTest", (item: any) => observer.next({ action: "test", item: item }) );
            this.socket.on("retMongoRead", (item: any) => observer.next({ action: "read", item: item }) );
            return () => this.socket.close();
        });
    }
    public test(){
        this.socket.emit('socketTest');
    }
    public ngOnDestroy() {
        console.log('socketio close');
        this.socket.close();
    }
    public mongoRead() {
        this.socket.emit('mongoRead');
    }
}

socket-item.model.tsの追加

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { SocketService } from '../shared';
import { ISocketItem } from "../../models";
import { Observable } from "rxjs";

@Component({
  selector: 'sockets',
  providers: [ SocketService ],
  template:`
    <h1>Sockets</h1>
    <button (click)=mongoRead()>mongoRead</button>
    {{ mongoReadData | json}}
    <br><br>
  `
})
export class SocketsComponent implements OnInit {
  private socketData : any;
  private mongoReadData : any;
  constructor( private socketService: SocketService ){
    this.mongoReadData = {};
    this.socketService.get()
      .subscribe(
                (socketItem: ISocketItem) => {
                  /*
                    let message: IMessage = socketItem.item;
                    this.list = this.list.push(message);
                    this.messages.next(this.list);
                    */
                    if(socketItem.action === 'test'){
                      console.log('test', socketItem.item);
                    }
                    else if(socketItem.action === 'read'){
                      console.log('read', socketItem.item);
                      this.mongoReadData = socketItem.item;
                    }
                    //this.mongoReadData.next();
                },
                error => console.log(error)
            );
  }
  public ngOnInit(){
    console.log('sockets');
    this.socketService.test();    
  }
  private mongoRead(){
    console.log('btn click');
    this.socketService.mongoRead();
  }
}


socketsページ

socketMongoRead

こんな感じにsocketsページでmongoReadボタンを押すと、dbのmongoデータが表示される。

angular2-webpack-starterにモジュールを追加する

angular2-webpack-starterにモジュールを追加する


angular2-webpack-starter

ここに説明がある angular2 starter  /  リポジトリ repository

moduleの追加

赤字を編集、青字をコピー

  • app
  • +barrel
  • +detail
  • about <<< コピー
  • mypage <<< abautのペーストをrename
  • home
  • no-content
  • app.component.css
  • app.component.spen.css
  • app.component.ts
  • app.e2d.ts
  • app.module.ts
  • app.resolver.ts
  • app.routes.ts
  • environmemt.ts
  • index.ts

mypageフォルダ追加

file名変更
about.component.ts
about.component.spec.ts
>>>
mypage.component.ts
mypage.component.spec.ts
mypage.component.ts内の変更
@Component内編集
selector: 'about', >>> selector: 'mypage',
template:内
<h1>About</h1> >>> <h1>Mypage</h1>
コンポーネント名の変更
export class AboutComponent implements OnInit { >>> export class MypageComponent implements OnInit {
indext.ts内の変更
export * from './about.component';
>>>
export * from './mypage.component';

app.componet.ts編集

@component/templateの変更
<nav>タグ内に、
<a [routerLink]=" ['./mypage'] " routerLinkActive="active" [routerLinkActiveOptions]= "{exact: true}"> Mypage </a>
を追加。

app.module.ts編集

import追加
import { MypageComponent } from './mypage';
を追加。
@NgModule内追加
declarations:内に
MypageComponent,
を追加。

app.route.ts編集

import追加
import { MypageComponent } from './mypage';
を追加。
export const ROUTES内追加
{ path: 'mypage', component: MypageComponent },
を追加。 一番下(path: '**')より下に追加すると、リンクされなくなるので注意。

npm startで起動する。
a2_webpack_add_module

こんな感じに新ページとルーティングスイッチが追加される。

python3でhtmlをcpp関数に書き出し

python3でhtmlをcpp関数に書き出し


html,js,cssをcpp関数で書き出す

ESP8266 webserverにwebpageを書き込むのに使う

htmlサンプルソース

下のinoでつかったhtml,js,cssの元ファイル

html / my2.html

<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width initial-scale=1 user-scalable=no'>
<title>bond switcher</title>
<link rel='stylesheet' href='style.css'>
</head>
<body style="margin: 20px auto;background: linear-gradient(to bottom, rgba(100, 100, 100, 0.2) 0%, rgba(255, 255, 255, 0.5) 40%, #ffffff 100%);background-repeat: no-repeat;">
<h1 style='text-align:center;color:#4b0082;'>Bond switcher</h1>
<div id="scene" style='margin-top:180px;'>
  <div class="wrapper">
    <ul class="ball">
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
      <li class="ring"></li>
    </ul>
  </div>
</div>
<script src='script.js'></script>
</body>
</html>

        
        
        
javascriipt / script.js

    //touch event
document.addEventListener('touchstart', handleTouchStart, false);        
document.addEventListener('touchmove', handleTouchMove, false);

var position = 0;	/* -1 left:0%, 0 left:50%, 1 left:100% */




/*
 touchの利用可能判別
*/
var supportTouch = 'ontouchend' in document;
console.log('supportTouch:', supportTouch);


var position = 0;   // ball position

/*
 PUT 
*/
var xmlHttp=createXmlHttpObject();
function createXmlHttpObject(){
 if(window.XMLHttpRequest){
    xmlHttp=new XMLHttpRequest();
 }else{
    xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
 }
 return xmlHttp;
};
function process(){
 if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
   xmlHttp.open('PUT','xml',true);
   xmlHttp.onreadystatechange=handleServerResponse;
   xmlHttp.send('');
 }
 setTimeout('process()',1000);
};
function positionChnageRequest(updown){
 if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
   xmlHttp.open('PUT','xml',true);
   xmlHttp.onreadystatechange=handleServerResponse;
   xmlHttp.send('position='+ updown);
 }
};
function handleServerResponse(){
 if(xmlHttp.readyState==4 && xmlHttp.status==200){
   xmlResponse=xmlHttp.responseXML;
   //console.log(xmlResponse);
   xmldoc = xmlResponse.getElementsByTagName('position');
   message = xmldoc[0].firstChild.nodeValue;
   //document.getElementById('runtime').innerHTML=message;
   var newPosition = parseInt(message, 10);
   if(position === newPosition) return;
   else if(position < newPosition){
       position = newPosition;
       rightMove();
   }else {
       position = newPosition;
       leftMove();
   }
 }
};


var xDown = null;                                                        
var yDown = null;                                                        
/*
touch
*/
function handleTouchStart(evt) {                                         
    xDown = evt.touches[0].clientX;                                      
    yDown = evt.touches[0].clientY;                                      
};                                                

var leftPos = '10%';
var centerPos = '50%';
var rightPos = '90%';

function leftMove(){
            var elem = document.getElementById('scene');
            if (position === -1){
	            elem.style.animationName = 'move_left2';
	            elem.style.left = leftPos;
            }else if(position === 0){
	            elem.style.animationName = 'move_left1';
	            elem.style.left = centerPos;
	        } 
};
function rightMove(){
            var elem = document.getElementById('scene');
            if (position === 1){
	            elem.style.animationName = 'move_right2';
	            elem.style.left = rightPos;
            }else if(position === 0){
	            elem.style.animationName = 'move_right1';
	            elem.style.left = centerPos;
	        }  
};

function handleTouchMove(evt) {
    if ( ! xDown || ! yDown ) {
        return;
    }

    var xUp = evt.touches[0].clientX;                                    
    var yUp = evt.touches[0].clientY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {
            /* left swipe */ 
            console.log('left!!!!!');
			positionChnageRequest('down');
        } else {
            /* right swipe */
            console.log('right!!!!!');
			positionChnageRequest('up');
        }                       
    } else {
        if ( yDiff > 0 ) {
            /* up swipe */ 
        } else { 
            /* down swipe */
        }                                                                 
    }
    /* reset values */
    xDown = null;
    yDown = null;                                             
};



/*
mouse
*/
document.addEventListener('mousedown', handleMouseDown, false);        
//document.addEventListener('mousemove', handleOnMouseMove, false);
document.addEventListener('mouseup', handleMouseUp, false);
// mouse
var mouseMoveStart = 0;
function handleOnMouseMove(evt) {
    if ( ! xDown || ! yDown ) {
        return;
    }
	if(mouseMoveStart === 1){
		mouseMoveStart = 0;
		return;
	}
    var xUp = evt.pageX;                                    
    var yUp = evt.pageY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {
            /* left swipe */ 
            console.log('left!!!!!');
			positionChnageRequest('down');
        } else {
            /* right swipe */
            console.log('right!!!!!');
			positionChnageRequest('up');
        }                       
    } else {
        if ( yDiff > 0 ) {
            /* up swipe */ 
        } else { 
            /* down swipe */
        }                                                                 
    }
    /* reset values */
    xDown = null;
    yDown = null;           
    //mouseClickOn = 0;                                  
};
function handleMouseDown(evt) {                                         
    xDown = evt.pageX;                                      
    yDown = evt.pageY;
    mouseMoveStart = 1;
    document.addEventListener('mousemove', handleOnMouseMove, false);
};   
function handleMouseUp(evt){
	handleOnMouseMove = null;
    document.removeEventListener('mousemove', handleOnMouseMove, false);	
};

process();	// start process

    
css / style.css

    @keyframes roundandround {
   to {transform: rotateX(360deg) rotateY(360deg);}
 }
 @keyframes show {
   to {opacity: 1;}
 }
 #scene {
   width:600px;
   height:600px;
   margin: 100px auto;
   perspective: 1000px;
   zoom: 0.2;   // 大きくするとswipeがもたつく
    animation-name: start;
   animation-duration: 1s;
   display: inline-block;
   position: relative;
     margin-left: -300px;
   left: 50%;
 }
 .wrapper {
   width:100%;
   height:100%;
   transform: rotateX(45deg) rotateY(45deg);
 -webkit-transform-style: preserve-3d;
 -moz-transform-style: preserve-3d;
 }
 .ball {
   position: relative;
   width: 100%;
   height: 100%;
   margin:0 auto;
 -webkit-transform-style: preserve-3d;
 -moz-transform-style: preserve-3d;
   animation: roundandround 7.5s 1.3s infinite linear;
 }
 .ball .ring {
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   border:20px;
  border-style: dotted;
   border-radius: 50%;
   opacity: 0.0;
   animation: show 0.75s forwards ease-in-out;
 display:block;
}

.ring:nth-child(0) {   color:#b00083;   transform: rotateY(0deg);   animation-delay: 0s; }
.ring:nth-child(1) {   color:#b20185;   transform: rotateY(4deg);   animation-delay: 0s; }
.ring:nth-child(2) {   color:#b30286;   transform: rotateY(8deg);   animation-delay: 0s; }
.ring:nth-child(3) {   color:#b50388;   transform: rotateY(12deg);   animation-delay: 0s; }
.ring:nth-child(4) {   color:#b70589;   transform: rotateY(16deg);   animation-delay: 0s; }
.ring:nth-child(5) {   color:#b9068b;   transform: rotateY(20deg);   animation-delay: 0s; }
.ring:nth-child(6) {   color:#ba078d;   transform: rotateY(24deg);   animation-delay: 0s; }
.ring:nth-child(7) {   color:#bc088e;   transform: rotateY(28deg);   animation-delay: 0s; }
.ring:nth-child(8) {   color:#be0990;   transform: rotateY(32deg);   animation-delay: 0s; }
.ring:nth-child(9) {   color:#bf0a91;   transform: rotateY(36deg);   animation-delay: 0s; }
.ring:nth-child(10) {   color:#c10c93;   transform: rotateY(40deg);   animation-delay: 0s; }
.ring:nth-child(11) {   color:#c30d94;   transform: rotateY(44deg);   animation-delay: 0s; }
.ring:nth-child(12) {   color:#c50e96;   transform: rotateY(48deg);   animation-delay: 0s; }
.ring:nth-child(13) {   color:#c60f98;   transform: rotateY(52deg);   animation-delay: 0s; }
.ring:nth-child(14) {   color:#c81099;   transform: rotateY(56deg);   animation-delay: 0s; }
.ring:nth-child(15) {   color:#ca119b;   transform: rotateY(60deg);   animation-delay: 0s; }
.ring:nth-child(16) {   color:#cb129c;   transform: rotateY(64deg);   animation-delay: 0s; }
.ring:nth-child(17) {   color:#cd149e;   transform: rotateY(68deg);   animation-delay: 0s; }
.ring:nth-child(18) {   color:#cf15a0;   transform: rotateY(72deg);   animation-delay: 0s; }
.ring:nth-child(19) {   color:#d116a1;   transform: rotateY(76deg);   animation-delay: 0s; }
.ring:nth-child(20) {   color:#d217a3;   transform: rotateY(80deg);   animation-delay: 0s; }
.ring:nth-child(21) {   color:#d418a4;   transform: rotateY(84deg);   animation-delay: 0s; }
.ring:nth-child(22) {   color:#d619a6;   transform: rotateY(88deg);   animation-delay: 0s; }
.ring:nth-child(23) {   color:#d81ba8;   transform: rotateY(92deg);   animation-delay: 0s; }
.ring:nth-child(24) {   color:#d91ca9;   transform: rotateY(96deg);   animation-delay: 0s; }
.ring:nth-child(25) {   color:#db1dab;   transform: rotateY(100deg);   animation-delay: 0s; }
.ring:nth-child(26) {   color:#dd1eac;   transform: rotateY(104deg);   animation-delay: 0s; }
.ring:nth-child(27) {   color:#de1fae;   transform: rotateY(108deg);   animation-delay: 0s; }
.ring:nth-child(28) {   color:#e020af;   transform: rotateY(112deg);   animation-delay: 0s; }
.ring:nth-child(29) {   color:#e221b1;   transform: rotateY(116deg);   animation-delay: 0s; }
.ring:nth-child(30) {   color:#e423b3;   transform: rotateY(120deg);   animation-delay: 0s; }
.ring:nth-child(31) {   color:#e524b4;   transform: rotateY(124deg);   animation-delay: 0s; }
.ring:nth-child(32) {   color:#e725b6;   transform: rotateY(128deg);   animation-delay: 0s; }
.ring:nth-child(33) {   color:#e926b7;   transform: rotateY(132deg);   animation-delay: 0s; }
.ring:nth-child(34) {   color:#ea27b9;   transform: rotateY(136deg);   animation-delay: 0s; }
.ring:nth-child(35) {   color:#ec28bb;   transform: rotateY(140deg);   animation-delay: 0s; }
.ring:nth-child(36) {   color:#ee29bc;   transform: rotateY(144deg);   animation-delay: 0s; }
.ring:nth-child(37) {   color:#f02bbe;   transform: rotateY(148deg);   animation-delay: 0s; }
.ring:nth-child(38) {   color:#f12cbf;   transform: rotateY(152deg);   animation-delay: 0s; }
.ring:nth-child(39) {   color:#f32dc1;   transform: rotateY(156deg);   animation-delay: 0s; }
.ring:nth-child(40) {   color:#f52ec2;   transform: rotateY(160deg);   animation-delay: 0s; }
.ring:nth-child(41) {   color:#f62fc4;   transform: rotateY(164deg);   animation-delay: 0s; }
.ring:nth-child(42) {   color:#f830c6;   transform: rotateY(168deg);   animation-delay: 0s; }
.ring:nth-child(43) {   color:#fa32c7;   transform: rotateY(172deg);   animation-delay: 0s; }
.ring:nth-child(44) {   color:#fc33c9;   transform: rotateY(176deg);   animation-delay: 0s; }
.ring:nth-child(45) {   color:#fd34ca;   transform: rotateY(180deg);   animation-delay: 0s; }
/*
この下は左右スワイプのアニメーション
*/
@keyframes start {
     0%   {}
     100% {}
}
@keyframes move_right1 {
     0%   {left: 10%;}
     100% {left: 50%;}
}
@keyframes move_right2 {
     0%   {left: 50%;}
     100% {left: 90%;}
}
@keyframes move_left1 {
     0%   {left: 90%;}
     100% {left: 50%;}
}
@keyframes move_left2 {
     0%   {left: 50%;}
     100% {left: 10%;}
}

    

python3でcpp関数にして出力

<link の部分にsytle.cssが<style>タグで書き出される。

<script の部分にscript.jsが<script>タグで書き出される。


#
#
#
import os
import codecs

base = os.path.dirname(os.path.realpath(__file__)) + '\\'

with open(base + 'my2.html', 'r') as f:
    htmls = f.read()
#print(htmls)
sources = []
sources.append('String webSite,javaScript,css,XML;')
sources.append('void buildWebsite(){')
sources.append('buildJavascript();')
sources.append('buildCss();')
sources.append('webSite = "";')
lines = htmls.split('\n')
for line in lines:
    if line == '':
        continue
    line = line.replace('"', "'")
    sources.append('webSite+="' + line + '\\n";')
sources.append('}')
for index, s in enumerate(sources):
    if s.find('<link') != -1:
        style = []
        style.append('webSite+="<style>\\n";')        
        style.append('webSite+=css;')
        style.append('webSite+="</style>\\n";')
        stylestr = '\n'.join(style)
        sources[index] = stylestr
    if s.find('<script') != -1:
        script = []
        script.append('webSite+="<script>\\n";')        
        script.append('webSite+=javaScript;')
        script.append('webSite+="</script>\\n";')
        scriptstr = '\n'.join(script)
        sources[index] = scriptstr
sstr = '\n'.join(sources)
print(sstr)
#
# gen javascript
#
sources.append('void buildJavascript(){')
sources.append('javaScript = "";')
with open(base + 'script.js', 'r') as f:
    js = f.read()
lines = js.split('\n')
for line in lines:
    if line == '':
        continue
    line = line.strip()
    sources.append('javaScript+="' + line + '\\n";')
sources.append('}')
#sstr = '\n'.join(sources)
#print(sstr)
#
# gen css
#
sources.append('void buildCss(){')
sources.append('css = "";')
with codecs.open(base + 'style.css', 'r', 'utf-8') as f:
    styles = f.read()
lines = styles.split('\n')
for line in lines:
    if line == '':
        continue
    line = line.strip()
    sources.append('css+="' + line + '\\n";')
sources.append('}')
sstr = '\n'.join(sources)
print(sstr)
#
# gen xml
#
sources.append('void buildXML(){')
sources.append('XML="<?xml version=\'1.0\'?>";')
sources.append('XML+="<position>";')
sources.append('XML+=getPosition();')
sources.append('XML+="</position>";')
sources.append('}')
sstr = '\n'.join(sources)
print(sstr)
with codecs.open('result.c', 'w', 'utf-8') as f:
    f.write(sstr)

どうということはないのですが、使用する元ファイルがBOM付きになっていて、ゴミがはいっていた。

html,js,cssはBOMなしを使用する

出力

result.c


String webSite,javaScript,css,XML;
void buildWebsite(){
buildJavascript();
buildCss();
webSite = "";
webSite+="<!doctype html>\n";
webSite+="<html>\n";
webSite+="<head>\n";
webSite+="<meta charset='utf-8'>\n";
webSite+="<meta name='viewport' content='width=device-width initial-scale=1 user-scalable=no'>\n";
webSite+="<title>bond switcher</title>\n";
webSite+="<style>\n";
webSite+=css;
webSite+="</style>\n";
webSite+="</head>\n";
webSite+="<body style='margin: 20px auto;background: linear-gradient(to bottom, rgba(100, 100, 100, 0.2) 0%, rgba(255, 255, 255, 0.5) 40%, #ffffff 100%);background-repeat: no-repeat;'>\n";
webSite+="<h1 style='text-align:center;color:#4b0082;'>Bond switcher</h1>\n";
webSite+="<div id='scene' style='margin-top:180px;'>\n";
webSite+="  <div class='wrapper'>\n";
webSite+="    <ul class='ball'>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="      <li class='ring'></li>\n";
webSite+="    </ul>\n";
webSite+="  </div>\n";
webSite+="</div>\n";
webSite+="<script>\n";
webSite+=javaScript;
webSite+="</script>\n";
webSite+="</body>\n";
webSite+="</html>\n";
}
void buildJavascript(){
javaScript = "";
javaScript+="//touch event\n";
javaScript+="document.addEventListener('touchstart', handleTouchStart, false);\n";
javaScript+="document.addEventListener('touchmove', handleTouchMove, false);\n";
javaScript+="var position = 0;	/* -1 left:0%, 0 left:50%, 1 left:100% */\n";
javaScript+="/*\n";
javaScript+="touch縺ョ蛻ゥ逕ィ蜿ッ閭ス蛻、蛻・\n";
javaScript+="*/\n";
javaScript+="var supportTouch = 'ontouchend' in document;\n";
javaScript+="console.log('supportTouch:', supportTouch);\n";
javaScript+="var position = 0;   // ball position\n";
javaScript+="/*\n";
javaScript+="PUT\n";
javaScript+="*/\n";
javaScript+="var xmlHttp=createXmlHttpObject();\n";
javaScript+="function createXmlHttpObject(){\n";
javaScript+="if(window.XMLHttpRequest){\n";
javaScript+="xmlHttp=new XMLHttpRequest();\n";
javaScript+="}else{\n";
javaScript+="xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');\n";
javaScript+="}\n";
javaScript+="return xmlHttp;\n";
javaScript+="};\n";
javaScript+="function process(){\n";
javaScript+="if(xmlHttp.readyState==0 || xmlHttp.readyState==4){\n";
javaScript+="xmlHttp.open('PUT','xml',true);\n";
javaScript+="xmlHttp.onreadystatechange=handleServerResponse;\n";
javaScript+="xmlHttp.send('');\n";
javaScript+="}\n";
javaScript+="setTimeout('process()',1000);\n";
javaScript+="};\n";
javaScript+="function positionChnageRequest(updown){\n";
javaScript+="if(xmlHttp.readyState==0 || xmlHttp.readyState==4){\n";
javaScript+="xmlHttp.open('PUT','xml',true);\n";
javaScript+="xmlHttp.onreadystatechange=handleServerResponse;\n";
javaScript+="xmlHttp.send('position='+ updown);\n";
javaScript+="}\n";
javaScript+="};\n";
javaScript+="function handleServerResponse(){\n";
javaScript+="if(xmlHttp.readyState==4 && xmlHttp.status==200){\n";
javaScript+="xmlResponse=xmlHttp.responseXML;\n";
javaScript+="//console.log(xmlResponse);\n";
javaScript+="xmldoc = xmlResponse.getElementsByTagName('position');\n";
javaScript+="message = xmldoc[0].firstChild.nodeValue;\n";
javaScript+="//document.getElementById('runtime').innerHTML=message;\n";
javaScript+="var newPosition = parseInt(message, 10);\n";
javaScript+="if(position === newPosition) return;\n";
javaScript+="else if(position < newPosition){\n";
javaScript+="position = newPosition;\n";
javaScript+="rightMove();\n";
javaScript+="}else {\n";
javaScript+="position = newPosition;\n";
javaScript+="leftMove();\n";
javaScript+="}\n";
javaScript+="}\n";
javaScript+="};\n";
javaScript+="var xDown = null;\n";
javaScript+="var yDown = null;\n";
javaScript+="/*\n";
javaScript+="touch\n";
javaScript+="*/\n";
javaScript+="function handleTouchStart(evt) {\n";
javaScript+="xDown = evt.touches[0].clientX;\n";
javaScript+="yDown = evt.touches[0].clientY;\n";
javaScript+="};\n";
javaScript+="var leftPos = '10%';\n";
javaScript+="var centerPos = '50%';\n";
javaScript+="var rightPos = '90%';\n";
javaScript+="function leftMove(){\n";
javaScript+="var elem = document.getElementById('scene');\n";
javaScript+="if (position === -1){\n";
javaScript+="elem.style.animationName = 'move_left2';\n";
javaScript+="elem.style.left = leftPos;\n";
javaScript+="}else if(position === 0){\n";
javaScript+="elem.style.animationName = 'move_left1';\n";
javaScript+="elem.style.left = centerPos;\n";
javaScript+="}\n";
javaScript+="};\n";
javaScript+="function rightMove(){\n";
javaScript+="var elem = document.getElementById('scene');\n";
javaScript+="if (position === 1){\n";
javaScript+="elem.style.animationName = 'move_right2';\n";
javaScript+="elem.style.left = rightPos;\n";
javaScript+="}else if(position === 0){\n";
javaScript+="elem.style.animationName = 'move_right1';\n";
javaScript+="elem.style.left = centerPos;\n";
javaScript+="}\n";
javaScript+="};\n";
javaScript+="function handleTouchMove(evt) {\n";
javaScript+="if ( ! xDown || ! yDown ) {\n";
javaScript+="return;\n";
javaScript+="}\n";
javaScript+="var xUp = evt.touches[0].clientX;\n";
javaScript+="var yUp = evt.touches[0].clientY;\n";
javaScript+="var xDiff = xDown - xUp;\n";
javaScript+="var yDiff = yDown - yUp;\n";
javaScript+="if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/\n";
javaScript+="if ( xDiff > 0 ) {\n";
javaScript+="/* left swipe */\n";
javaScript+="console.log('left!!!!!');\n";
javaScript+="positionChnageRequest('down');\n";
javaScript+="} else {\n";
javaScript+="/* right swipe */\n";
javaScript+="console.log('right!!!!!');\n";
javaScript+="positionChnageRequest('up');\n";
javaScript+="}\n";
javaScript+="} else {\n";
javaScript+="if ( yDiff > 0 ) {\n";
javaScript+="/* up swipe */\n";
javaScript+="} else {\n";
javaScript+="/* down swipe */\n";
javaScript+="}\n";
javaScript+="}\n";
javaScript+="/* reset values */\n";
javaScript+="xDown = null;\n";
javaScript+="yDown = null;\n";
javaScript+="};\n";
javaScript+="/*\n";
javaScript+="mouse\n";
javaScript+="*/\n";
javaScript+="document.addEventListener('mousedown', handleMouseDown, false);\n";
javaScript+="//document.addEventListener('mousemove', handleOnMouseMove, false);\n";
javaScript+="document.addEventListener('mouseup', handleMouseUp, false);\n";
javaScript+="// mouse\n";
javaScript+="var mouseMoveStart = 0;\n";
javaScript+="function handleOnMouseMove(evt) {\n";
javaScript+="if ( ! xDown || ! yDown ) {\n";
javaScript+="return;\n";
javaScript+="}\n";
javaScript+="if(mouseMoveStart === 1){\n";
javaScript+="mouseMoveStart = 0;\n";
javaScript+="return;\n";
javaScript+="}\n";
javaScript+="var xUp = evt.pageX;\n";
javaScript+="var yUp = evt.pageY;\n";
javaScript+="var xDiff = xDown - xUp;\n";
javaScript+="var yDiff = yDown - yUp;\n";
javaScript+="if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/\n";
javaScript+="if ( xDiff > 0 ) {\n";
javaScript+="/* left swipe */\n";
javaScript+="console.log('left!!!!!');\n";
javaScript+="positionChnageRequest('down');\n";
javaScript+="} else {\n";
javaScript+="/* right swipe */\n";
javaScript+="console.log('right!!!!!');\n";
javaScript+="positionChnageRequest('up');\n";
javaScript+="}\n";
javaScript+="} else {\n";
javaScript+="if ( yDiff > 0 ) {\n";
javaScript+="/* up swipe */\n";
javaScript+="} else {\n";
javaScript+="/* down swipe */\n";
javaScript+="}\n";
javaScript+="}\n";
javaScript+="/* reset values */\n";
javaScript+="xDown = null;\n";
javaScript+="yDown = null;\n";
javaScript+="//mouseClickOn = 0;\n";
javaScript+="};\n";
javaScript+="function handleMouseDown(evt) {\n";
javaScript+="xDown = evt.pageX;\n";
javaScript+="yDown = evt.pageY;\n";
javaScript+="mouseMoveStart = 1;\n";
javaScript+="document.addEventListener('mousemove', handleOnMouseMove, false);\n";
javaScript+="};\n";
javaScript+="function handleMouseUp(evt){\n";
javaScript+="handleOnMouseMove = null;\n";
javaScript+="document.removeEventListener('mousemove', handleOnMouseMove, false);\n";
javaScript+="};\n";
javaScript+="process();	// start process\n";
}
void buildCss(){
css = "";
css+="@keyframes roundandround {\n";
css+="to {transform: rotateX(360deg) rotateY(360deg);}\n";
css+="}\n";
css+="@keyframes show {\n";
css+="to {opacity: 1;}\n";
css+="}\n";
css+="#scene {\n";
css+="width:600px;\n";
css+="height:600px;\n";
css+="margin: 100px auto;\n";
css+="perspective: 1000px;\n";
css+="zoom: 0.2;   // 大きくするとswipeがもたつく\n";
css+="animation-name: start;\n";
css+="animation-duration: 1s;\n";
css+="display: inline-block;\n";
css+="position: relative;\n";
css+="margin-left: -300px;\n";
css+="left: 50%;\n";
css+="}\n";
css+=".wrapper {\n";
css+="width:100%;\n";
css+="height:100%;\n";
css+="transform: rotateX(45deg) rotateY(45deg);\n";
css+="-webkit-transform-style: preserve-3d;\n";
css+="-moz-transform-style: preserve-3d;\n";
css+="}\n";
css+=".ball {\n";
css+="position: relative;\n";
css+="width: 100%;\n";
css+="height: 100%;\n";
css+="margin:0 auto;\n";
css+="-webkit-transform-style: preserve-3d;\n";
css+="-moz-transform-style: preserve-3d;\n";
css+="animation: roundandround 7.5s 1.3s infinite linear;\n";
css+="}\n";
css+=".ball .ring {\n";
css+="position: absolute;\n";
css+="top: 0;\n";
css+="left: 0;\n";
css+="width: 100%;\n";
css+="height: 100%;\n";
css+="border:20px;\n";
css+="border-style: dotted;\n";
css+="border-radius: 50%;\n";
css+="opacity: 0.0;\n";
css+="animation: show 0.75s forwards ease-in-out;\n";
css+="display:block;\n";
css+="}\n";
css+="\n";
css+=".ring:nth-child(0) {   color:#b00083;   transform: rotateY(0deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(1) {   color:#b20185;   transform: rotateY(4deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(2) {   color:#b30286;   transform: rotateY(8deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(3) {   color:#b50388;   transform: rotateY(12deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(4) {   color:#b70589;   transform: rotateY(16deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(5) {   color:#b9068b;   transform: rotateY(20deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(6) {   color:#ba078d;   transform: rotateY(24deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(7) {   color:#bc088e;   transform: rotateY(28deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(8) {   color:#be0990;   transform: rotateY(32deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(9) {   color:#bf0a91;   transform: rotateY(36deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(10) {   color:#c10c93;   transform: rotateY(40deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(11) {   color:#c30d94;   transform: rotateY(44deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(12) {   color:#c50e96;   transform: rotateY(48deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(13) {   color:#c60f98;   transform: rotateY(52deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(14) {   color:#c81099;   transform: rotateY(56deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(15) {   color:#ca119b;   transform: rotateY(60deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(16) {   color:#cb129c;   transform: rotateY(64deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(17) {   color:#cd149e;   transform: rotateY(68deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(18) {   color:#cf15a0;   transform: rotateY(72deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(19) {   color:#d116a1;   transform: rotateY(76deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(20) {   color:#d217a3;   transform: rotateY(80deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(21) {   color:#d418a4;   transform: rotateY(84deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(22) {   color:#d619a6;   transform: rotateY(88deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(23) {   color:#d81ba8;   transform: rotateY(92deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(24) {   color:#d91ca9;   transform: rotateY(96deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(25) {   color:#db1dab;   transform: rotateY(100deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(26) {   color:#dd1eac;   transform: rotateY(104deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(27) {   color:#de1fae;   transform: rotateY(108deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(28) {   color:#e020af;   transform: rotateY(112deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(29) {   color:#e221b1;   transform: rotateY(116deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(30) {   color:#e423b3;   transform: rotateY(120deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(31) {   color:#e524b4;   transform: rotateY(124deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(32) {   color:#e725b6;   transform: rotateY(128deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(33) {   color:#e926b7;   transform: rotateY(132deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(34) {   color:#ea27b9;   transform: rotateY(136deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(35) {   color:#ec28bb;   transform: rotateY(140deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(36) {   color:#ee29bc;   transform: rotateY(144deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(37) {   color:#f02bbe;   transform: rotateY(148deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(38) {   color:#f12cbf;   transform: rotateY(152deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(39) {   color:#f32dc1;   transform: rotateY(156deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(40) {   color:#f52ec2;   transform: rotateY(160deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(41) {   color:#f62fc4;   transform: rotateY(164deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(42) {   color:#f830c6;   transform: rotateY(168deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(43) {   color:#fa32c7;   transform: rotateY(172deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(44) {   color:#fc33c9;   transform: rotateY(176deg);   animation-delay: 0s; }\n";
css+=".ring:nth-child(45) {   color:#fd34ca;   transform: rotateY(180deg);   animation-delay: 0s; }\n";
css+="/*\n";
css+="この下は左右スワイプのアニメーション\n";
css+="*/\n";
css+="@keyframes start {\n";
css+="0%   {}\n";
css+="100% {}\n";
css+="}\n";
css+="@keyframes move_right1 {\n";
css+="0%   {left: 10%;}\n";
css+="100% {left: 50%;}\n";
css+="}\n";
css+="@keyframes move_right2 {\n";
css+="0%   {left: 50%;}\n";
css+="100% {left: 90%;}\n";
css+="}\n";
css+="@keyframes move_left1 {\n";
css+="0%   {left: 90%;}\n";
css+="100% {left: 50%;}\n";
css+="}\n";
css+="@keyframes move_left2 {\n";
css+="0%   {left: 50%;}\n";
css+="100% {left: 10%;}\n";
css+="}\n";
}
void buildXML(){
XML="<?xml version='1.0'?>";
XML+="<position>";
XML+=getPosition();
XML+="</position>";

buildWebsite()を呼ぶと、htmlがwebSiteにStringとしてセットされる。

ちょっと巨大だけど、inoに張り付けて動かすと動作はOK

xmlはclientでxmlで受け取る用のデータ

ESP8266に書き込んだ記事

ESP8266WebServerでballのswipeでポート制御
androider
アンドロイダー公認デベロッパー認証
google play/easycalc
ケイデザイン
ギャラリー
  • angular2-webpack-starterにsocketioを追加してみる
  • angular2-webpack-starterにモジュールを追加する
  • vscodeでpython3, javascriptを走らせる設定 / ubuntu16.04
  • vscodeでpython3, javascriptを走らせる設定 / ubuntu16.04
  • raspberrypi2のgpioをpython3で制御
  • expressにangular2のquickstartを組込んでみる
  • ubuntu14.04でネットワークに繋がらなくなる >>> 固定IPにすると繋がった
  • ubuntu14.04でネットワークに繋がらなくなる >>> 固定IPにすると繋がった
  • ubuntu14.04でネットワークに繋がらなくなる >>> 固定IPにすると繋がった