clazz, Bundle args) {
40 | T fragment = null;
41 | try {
42 | fragment = clazz.newInstance();
43 | fragment.setArguments(args);
44 | } catch (java.lang.InstantiationException e) {
45 | e.printStackTrace();
46 | } catch (IllegalAccessException e) {
47 | e.printStackTrace();
48 | }
49 | return fragment;
50 | }
51 |
52 | @Override
53 | public void onCreate(Bundle savedInstanceState) {
54 | super.onCreate(savedInstanceState);
55 | if (getArguments() != null) {
56 | mParam1 = getArguments().getString(ARG_PARAM1);
57 | mParam2 = getArguments().getString(ARG_PARAM2);
58 | }
59 | }
60 |
61 | // TODO: Rename method, update argument and hook method into UI event
62 | public void onButtonPressed(Uri uri) {
63 | if (mListener != null) {
64 | mListener.onFragmentInteraction(uri);
65 | }
66 | }
67 |
68 | @Override
69 | public void onAttach(Context context) {
70 | super.onAttach(context);
71 | if (context instanceof OnFragmentInteractionListener) {
72 | mListener = (OnFragmentInteractionListener) context;
73 | } else {
74 | throw new RuntimeException(context.toString()
75 | + " must implement OnFragmentInteractionListener");
76 | }
77 | }
78 |
79 | @Override
80 | public void onDetach() {
81 | super.onDetach();
82 | mListener = null;
83 | }
84 |
85 | /**
86 | * This interface must be implemented by activities that contain this
87 | * fragment to allow an interaction in this fragment to be communicated
88 | * to the activity and potentially other fragments contained in that
89 | * activity.
90 | *
91 | * See the Android Training lesson Communicating with Other Fragments for more information.
94 | */
95 | public interface OnFragmentInteractionListener {
96 | // TODO: Update argument type and name
97 | void onFragmentInteraction(Uri uri);
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/docs/code/TSDB/http_push.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 |
3 | import httplib, urllib
4 | from datetime import datetime
5 | from urllib import urlencode
6 | from sign_sample import *
7 | import time
8 | import json
9 | import random
10 |
11 | # output send data
12 | def patch_send():
13 | old_send= httplib.HTTPConnection.send
14 | def new_send( self, data ):
15 | print data
16 | return old_send(self, data) #return is not necessary, but never hurts, in case the library is changed
17 | httplib.HTTPConnection.send= new_send
18 |
19 | patch_send()
20 |
21 | # generate sign
22 | credentials = BceCredentials("5c5b5ea289ed4c6db75c131e7eaf5715", "ca49ed4d426541e79f7da83fde4b9e28")
23 | http_method = "GET"
24 | path = "/v1/metric"
25 | headers = {"host": "zengjf.tsdb.iot.gz.baidubce.com"
26 | # "content-type":"application/json; charset=utf-8",
27 | # "content-length":"0"
28 | }
29 | params = {}
30 | timestamp = 0 # int(time.time())
31 | headers_to_sign = {"host"}
32 | # 这里一定要注意这里的headers_to_sign,不写会导致
33 | # 403 Forbidden
34 | # {"requestId":"e5218a3e-1c8d-422c-ae2d-547c3ddfb01a","code":"AccessDenied","message":"Verify access forbidden"}
35 | result = sign(credentials, http_method, path, headers, params, timestamp, 1800, headers_to_sign)
36 | print result
37 | print
38 |
39 | # send request
40 | hdrs = {
41 | "Content-type": "application/json; charset=utf-8",
42 | "Authorization": result,
43 | 'Host': 'zengjf.tsdb.iot.gz.baidubce.com'
44 | # "content-length":"0",
45 | # "x-bce-date": '%sT%sZ' % (datetime.datetime.utcfromtimestamp(timestamp).strftime("%Y%m%d"), datetime.datetime.utcfromtimestamp(timestamp).strftime("%H%M%S"))
46 | }
47 | conn = httplib.HTTPConnection("zengjf.tsdb.iot.gz.baidubce.com")
48 | conn.request("GET", "/v1/metric", headers = hdrs)
49 | response = conn.getresponse()
50 | print response.status, response.reason
51 | data = response.read()
52 | print data
53 | conn.close()
54 |
55 | metrics = json.loads(data)
56 | print metrics["metrics"][0]
57 | print
58 |
59 | # generate sign
60 | credentials = BceCredentials("5c5b5ea289ed4c6db75c131e7eaf5715", "ca49ed4d426541e79f7da83fde4b9e28")
61 | http_method = "POST"
62 | path = "/v1/datapoint"
63 | print path
64 | headers = {"host": "zengjf.tsdb.iot.gz.baidubce.com"
65 | # "content-type":"application/json; charset=utf-8",
66 | # "content-length":"0"
67 | }
68 |
69 | params = {
70 | }
71 |
72 | timestamp = 0 # int(time.time())
73 | headers_to_sign = {"host"}
74 | # 这里一定要注意这里的headers_to_sign,不写会导致
75 | # 403 Forbidden
76 | # {"requestId":"e5218a3e-1c8d-422c-ae2d-547c3ddfb01a","code":"AccessDenied","message":"Verify access forbidden"}
77 | result = sign(credentials, http_method, path, headers, params, timestamp, 1800, headers_to_sign)
78 | print result
79 | print
80 |
81 | # send request
82 | query_data = json.dumps(
83 | {
84 | "datapoints": [{
85 | "metric": metrics["metrics"][0],
86 | "tags": {
87 | "host": "zengjf.tsdb.iot.gz.baidubce.com",
88 | },
89 | "timestamp": int(time.time()),
90 | "value": random.randint(1, 30),
91 | "id": "70:00:83:24:38:85",
92 | "machine": "arm",
93 | "os": "linux",
94 | "categories": "data"
95 | }]
96 | }
97 | )
98 | hdrs = {
99 | "Content-type": "application/json; charset=utf-8",
100 | "Authorization": result,
101 | 'Host': 'zengjf.tsdb.iot.gz.baidubce.com'
102 | # "content-length":"0",
103 | # "x-bce-date": '%sT%sZ' % (datetime.datetime.utcfromtimestamp(timestamp).strftime("%Y%m%d"), datetime.datetime.utcfromtimestamp(timestamp).strftime("%H%M%S"))
104 | }
105 | conn = httplib.HTTPConnection("zengjf.tsdb.iot.gz.baidubce.com")
106 | print
107 | print path, query_data
108 | print
109 |
110 | conn.request("POST", path, query_data, headers = hdrs)
111 | response = conn.getresponse()
112 | print
113 | print response.status, response.reason
114 | print
115 |
116 | data = response.read()
117 | print data
118 | conn.close()
119 |
--------------------------------------------------------------------------------
/docs/code/TSDB/http_tag.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 |
3 | import httplib, urllib
4 | from datetime import datetime
5 | from urllib import urlencode
6 | from sign_sample import *
7 | import time
8 | import json
9 |
10 | # output send data
11 | def patch_send():
12 | old_send= httplib.HTTPConnection.send
13 | def new_send( self, data ):
14 | print data
15 | return old_send(self, data) #return is not necessary, but never hurts, in case the library is changed
16 | httplib.HTTPConnection.send= new_send
17 |
18 | patch_send()
19 |
20 | # generate sign
21 | credentials = BceCredentials("5c5b5ea289ed4c6db75c131e7eaf5715", "ca49ed4d426541e79f7da83fde4b9e28")
22 | http_method = "GET"
23 | path = "/v1/metric"
24 | headers = {"host": "zengjf.tsdb.iot.gz.baidubce.com"
25 | # "content-type":"application/json; charset=utf-8",
26 | # "content-length":"0"
27 | }
28 | params = {}
29 | timestamp = 0 # int(time.time())
30 | headers_to_sign = {"host"}
31 | # 这里一定要注意这里的headers_to_sign,不写会导致
32 | # 403 Forbidden
33 | # {"requestId":"e5218a3e-1c8d-422c-ae2d-547c3ddfb01a","code":"AccessDenied","message":"Verify access forbidden"}
34 | result = sign(credentials, http_method, path, headers, params, timestamp, 1800, headers_to_sign)
35 | print result
36 | print
37 |
38 | # send request
39 | hdrs = {
40 | "Content-type": "application/json; charset=utf-8",
41 | "Authorization": result,
42 | 'Host': 'zengjf.tsdb.iot.gz.baidubce.com'
43 | # "content-length":"0",
44 | # "x-bce-date": '%sT%sZ' % (datetime.datetime.utcfromtimestamp(timestamp).strftime("%Y%m%d"), datetime.datetime.utcfromtimestamp(timestamp).strftime("%H%M%S"))
45 | }
46 | conn = httplib.HTTPConnection("zengjf.tsdb.iot.gz.baidubce.com")
47 | conn.request("GET", "/v1/metric", headers = hdrs)
48 | response = conn.getresponse()
49 | print response.status, response.reason
50 | data = response.read()
51 | print data
52 | conn.close()
53 |
54 | metrics = json.loads(data)
55 | print metrics["metrics"][0]
56 | print
57 |
58 | # generate sign
59 | credentials = BceCredentials("5c5b5ea289ed4c6db75c131e7eaf5715", "ca49ed4d426541e79f7da83fde4b9e28")
60 | http_method = "GET"
61 | path = "/v1/metric/" + metrics["metrics"][0] + "/tag"
62 | print path
63 | headers = {"host": "zengjf.tsdb.iot.gz.baidubce.com"
64 | # "content-type":"application/json; charset=utf-8",
65 | # "content-length":"0"
66 | }
67 | params = {}
68 | timestamp = 0 # int(time.time())
69 | headers_to_sign = {"host"}
70 | # 这里一定要注意这里的headers_to_sign,不写会导致
71 | # 403 Forbidden
72 | # {"requestId":"e5218a3e-1c8d-422c-ae2d-547c3ddfb01a","code":"AccessDenied","message":"Verify access forbidden"}
73 | result = sign(credentials, http_method, path, headers, params, timestamp, 1800, headers_to_sign)
74 | print result
75 | print
76 |
77 | # send request
78 | hdrs = {
79 | "Content-type": "application/json; charset=utf-8",
80 | "Authorization": result,
81 | 'Host': 'zengjf.tsdb.iot.gz.baidubce.com'
82 | # "content-length":"0",
83 | # "x-bce-date": '%sT%sZ' % (datetime.datetime.utcfromtimestamp(timestamp).strftime("%Y%m%d"), datetime.datetime.utcfromtimestamp(timestamp).strftime("%H%M%S"))
84 | }
85 | conn = httplib.HTTPConnection("zengjf.tsdb.iot.gz.baidubce.com")
86 | print path
87 | conn.request("GET", path, headers = hdrs)
88 | response = conn.getresponse()
89 | print response.status, response.reason
90 | data = response.read()
91 | print data
92 | conn.close()
93 |
94 | '''
95 | >>> ================================ RESTART ================================
96 | >>>
97 | bce-auth-v1/5c5b5ea289ed4c6db75c131e7eaf5715/2017-12-04T00:28:52Z/1800/host/52e4ca905caaff48bde728eaf42c9c6d39868ea12a20399164c9a10b57242b09
98 |
99 | GET /v1/metric HTTP/1.1
100 |
101 | Accept-Encoding: identity
102 |
103 | Host: zengjf.tsdb.iot.gz.baidubce.com
104 |
105 | Content-type: application/json; charset=utf-8
106 |
107 | Authorization: bce-auth-v1/5c5b5ea289ed4c6db75c131e7eaf5715/2017-12-04T00:28:52Z/1800/host/52e4ca905caaff48bde728eaf42c9c6d39868ea12a20399164c9a10b57242b09
108 |
109 |
110 |
111 |
112 | 200 OK
113 | {"metrics":["report"]}
114 | >>>
115 | '''
116 |
--------------------------------------------------------------------------------
/docs/code/TSDB/http_field.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 |
3 | import httplib, urllib
4 | from datetime import datetime
5 | from urllib import urlencode
6 | from sign_sample import *
7 | import time
8 | import json
9 |
10 | # output send data
11 | def patch_send():
12 | old_send= httplib.HTTPConnection.send
13 | def new_send( self, data ):
14 | print data
15 | return old_send(self, data) #return is not necessary, but never hurts, in case the library is changed
16 | httplib.HTTPConnection.send= new_send
17 |
18 | patch_send()
19 |
20 | # generate sign
21 | credentials = BceCredentials("5c5b5ea289ed4c6db75c131e7eaf5715", "ca49ed4d426541e79f7da83fde4b9e28")
22 | http_method = "GET"
23 | path = "/v1/metric"
24 | headers = {"host": "zengjf.tsdb.iot.gz.baidubce.com"
25 | # "content-type":"application/json; charset=utf-8",
26 | # "content-length":"0"
27 | }
28 | params = {}
29 | timestamp = 0 # int(time.time())
30 | headers_to_sign = {"host"}
31 | # 这里一定要注意这里的headers_to_sign,不写会导致
32 | # 403 Forbidden
33 | # {"requestId":"e5218a3e-1c8d-422c-ae2d-547c3ddfb01a","code":"AccessDenied","message":"Verify access forbidden"}
34 | result = sign(credentials, http_method, path, headers, params, timestamp, 1800, headers_to_sign)
35 | print result
36 | print
37 |
38 | # send request
39 | hdrs = {
40 | "Content-type": "application/json; charset=utf-8",
41 | "Authorization": result,
42 | 'Host': 'zengjf.tsdb.iot.gz.baidubce.com'
43 | # "content-length":"0",
44 | # "x-bce-date": '%sT%sZ' % (datetime.datetime.utcfromtimestamp(timestamp).strftime("%Y%m%d"), datetime.datetime.utcfromtimestamp(timestamp).strftime("%H%M%S"))
45 | }
46 | conn = httplib.HTTPConnection("zengjf.tsdb.iot.gz.baidubce.com")
47 | conn.request("GET", "/v1/metric", headers = hdrs)
48 | response = conn.getresponse()
49 | print response.status, response.reason
50 | data = response.read()
51 | print data
52 | conn.close()
53 |
54 | metrics = json.loads(data)
55 | print metrics["metrics"][0]
56 | print
57 |
58 | # generate sign
59 | credentials = BceCredentials("5c5b5ea289ed4c6db75c131e7eaf5715", "ca49ed4d426541e79f7da83fde4b9e28")
60 | http_method = "GET"
61 | path = "/v1/metric/" + metrics["metrics"][0] + "/field"
62 | print path
63 | headers = {"host": "zengjf.tsdb.iot.gz.baidubce.com"
64 | # "content-type":"application/json; charset=utf-8",
65 | # "content-length":"0"
66 | }
67 | params = {}
68 | timestamp = 0 # int(time.time())
69 | headers_to_sign = {"host"}
70 | # 这里一定要注意这里的headers_to_sign,不写会导致
71 | # 403 Forbidden
72 | # {"requestId":"e5218a3e-1c8d-422c-ae2d-547c3ddfb01a","code":"AccessDenied","message":"Verify access forbidden"}
73 | result = sign(credentials, http_method, path, headers, params, timestamp, 1800, headers_to_sign)
74 | print result
75 | print
76 |
77 | # send request
78 | hdrs = {
79 | "Content-type": "application/json; charset=utf-8",
80 | "Authorization": result,
81 | 'Host': 'zengjf.tsdb.iot.gz.baidubce.com'
82 | # "content-length":"0",
83 | # "x-bce-date": '%sT%sZ' % (datetime.datetime.utcfromtimestamp(timestamp).strftime("%Y%m%d"), datetime.datetime.utcfromtimestamp(timestamp).strftime("%H%M%S"))
84 | }
85 | conn = httplib.HTTPConnection("zengjf.tsdb.iot.gz.baidubce.com")
86 | print path
87 | conn.request("GET", path, headers = hdrs)
88 | response = conn.getresponse()
89 | print response.status, response.reason
90 | data = response.read()
91 | print data
92 | conn.close()
93 |
94 | '''
95 | >>> ================================ RESTART ================================
96 | >>>
97 | bce-auth-v1/5c5b5ea289ed4c6db75c131e7eaf5715/2017-12-04T00:28:52Z/1800/host/52e4ca905caaff48bde728eaf42c9c6d39868ea12a20399164c9a10b57242b09
98 |
99 | GET /v1/metric HTTP/1.1
100 |
101 | Accept-Encoding: identity
102 |
103 | Host: zengjf.tsdb.iot.gz.baidubce.com
104 |
105 | Content-type: application/json; charset=utf-8
106 |
107 | Authorization: bce-auth-v1/5c5b5ea289ed4c6db75c131e7eaf5715/2017-12-04T00:28:52Z/1800/host/52e4ca905caaff48bde728eaf42c9c6d39868ea12a20399164c9a10b57242b09
108 |
109 |
110 |
111 |
112 | 200 OK
113 | {"metrics":["report"]}
114 | >>>
115 | '''
116 |
--------------------------------------------------------------------------------
/docs/code/html/index_iot_hub_demo_xuli.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Start Page
5 |
6 |
7 |
8 |
9 |
10 |
16 |
17 |
18 |
21 |
22 |
STM8 Temperature Data
23 |
24 |
25 |
26 |
27 |
28 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/docs/code/TSDB/http_query.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 |
3 | import httplib, urllib
4 | from datetime import datetime
5 | from urllib import urlencode
6 | from sign_sample import *
7 | import time
8 | import json
9 |
10 | # output send data
11 | def patch_send():
12 | old_send= httplib.HTTPConnection.send
13 | def new_send( self, data ):
14 | print data
15 | return old_send(self, data) #return is not necessary, but never hurts, in case the library is changed
16 | httplib.HTTPConnection.send= new_send
17 |
18 | patch_send()
19 |
20 | # generate sign
21 | credentials = BceCredentials("5c5b5ea289ed4c6db75c131e7eaf5715", "ca49ed4d426541e79f7da83fde4b9e28")
22 | http_method = "GET"
23 | path = "/v1/metric"
24 | headers = {"host": "zengjf.tsdb.iot.gz.baidubce.com"
25 | # "content-type":"application/json; charset=utf-8",
26 | # "content-length":"0"
27 | }
28 | params = {}
29 | timestamp = 0 # int(time.time())
30 | headers_to_sign = {"host"}
31 | # 这里一定要注意这里的headers_to_sign,不写会导致
32 | # 403 Forbidden
33 | # {"requestId":"e5218a3e-1c8d-422c-ae2d-547c3ddfb01a","code":"AccessDenied","message":"Verify access forbidden"}
34 | result = sign(credentials, http_method, path, headers, params, timestamp, 1800, headers_to_sign)
35 | print result
36 | print
37 |
38 | # send request
39 | hdrs = {
40 | "Content-type": "application/json; charset=utf-8",
41 | "Authorization": result,
42 | 'Host': 'zengjf.tsdb.iot.gz.baidubce.com'
43 | # "content-length":"0",
44 | # "x-bce-date": '%sT%sZ' % (datetime.datetime.utcfromtimestamp(timestamp).strftime("%Y%m%d"), datetime.datetime.utcfromtimestamp(timestamp).strftime("%H%M%S"))
45 | }
46 | conn = httplib.HTTPConnection("zengjf.tsdb.iot.gz.baidubce.com")
47 | conn.request("GET", "/v1/metric", headers = hdrs)
48 | response = conn.getresponse()
49 | print response.status, response.reason
50 | data = response.read()
51 | print data
52 | conn.close()
53 |
54 | metrics = json.loads(data)
55 | print metrics["metrics"][0]
56 | print
57 |
58 | # generate sign
59 | credentials = BceCredentials("5c5b5ea289ed4c6db75c131e7eaf5715", "ca49ed4d426541e79f7da83fde4b9e28")
60 | http_method = "PUT"
61 | path = "/v1/datapoint"
62 | print path
63 | headers = {"host": "zengjf.tsdb.iot.gz.baidubce.com"
64 | # "content-type":"application/json; charset=utf-8",
65 | # "content-length":"0"
66 | }
67 |
68 | params = {
69 | "query": ""
70 | }
71 |
72 | timestamp = 0 # int(time.time())
73 | headers_to_sign = {"host"}
74 | # 这里一定要注意这里的headers_to_sign,不写会导致
75 | # 403 Forbidden
76 | # {"requestId":"e5218a3e-1c8d-422c-ae2d-547c3ddfb01a","code":"AccessDenied","message":"Verify access forbidden"}
77 | result = sign(credentials, http_method, path, headers, params, timestamp, 1800, headers_to_sign)
78 | print result
79 | print
80 |
81 | # send request
82 | '''
83 | query_data = json.dumps(
84 | {
85 | "queries": [{
86 | "metric": metrics["metrics"][0],
87 | "field": "value",
88 | "filters": {
89 | "start": "1 hour ago",
90 | "value": ">= 10"
91 | },
92 | "limit": 1000
93 | }]
94 | }
95 | )
96 | '''
97 | query_data = json.dumps(
98 | {
99 | "queries": [{
100 | "metric": metrics["metrics"][0],
101 | "field": "value",
102 | "filters": {
103 | "start": "72 hour ago",
104 | "value": ">= 10"
105 | },
106 | "limit": 1000
107 | }]
108 | }
109 | )
110 | hdrs = {
111 | "Content-type": "application/json; charset=utf-8",
112 | "Authorization": result,
113 | 'Host': 'zengjf.tsdb.iot.gz.baidubce.com'
114 | # "content-length":"0",
115 | # "x-bce-date": '%sT%sZ' % (datetime.datetime.utcfromtimestamp(timestamp).strftime("%Y%m%d"), datetime.datetime.utcfromtimestamp(timestamp).strftime("%H%M%S"))
116 | }
117 | conn = httplib.HTTPConnection("zengjf.tsdb.iot.gz.baidubce.com")
118 | print
119 | print path, query_data
120 | print
121 |
122 | conn.request("PUT", path + "?query", query_data, headers = hdrs)
123 | response = conn.getresponse()
124 | print
125 | print response.status, response.reason
126 | print
127 |
128 | data = response.read()
129 | print data
130 | conn.close()
131 |
--------------------------------------------------------------------------------
/docs/code/html/ShowTime/Temperature.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Start Page
5 |
6 |
7 |
8 |
9 |
10 |
16 |
17 |
18 |
21 |
22 |
STM8 Temperature Data
23 |
24 |
25 |
26 |
27 |
28 |
101 |
102 |
103 |
--------------------------------------------------------------------------------
/.idea/markdown-navigator.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/docs/docs/0008_baidu_IoT_Hub_SIM800C.md:
--------------------------------------------------------------------------------
1 | # baidu IoT Hub SIM800C
2 |
3 | [SIM800C Reference](../refers/SIM800_Series_AT_Command_Manual_V1.09.pdf)
4 |
5 | 在测试TCP连接的时候可以TCP连接以后,发送0x1000两个字节数据(请看MQTT协议,理解两个字节代表的意思)给服务器,一般来说,由于没有提供认证信息,服务器会关闭TCP连接,SIM800C会反馈TCP连接中断,这样就知道服务器连接是否正常了。
6 |
7 | 如下是SIM800C连接串口线连线图:
8 |
9 | 
10 |
11 | ## SIM800C Data Formate
12 |
13 | 在发送数据给SIM800C的时候,看到很多地方都发送`\r\n`,貌似也不会有错,但是站在Datasheet的角度只要发送`\r`就行了,已经验证了。
14 |
15 | 
16 |
17 | ## WireShark Capture Data
18 |
19 | * Excute Python3 Script: [../code/IoT_Hub/publish.py](../code/IoT_Hub/publish.py)
20 | * `pip3 install paho-mqtt`
21 | * Connect Data:
22 | 
23 | connect data: `106300044d51545404c2003c001144657669636549642d6278396e6476653200167a656e676a662f737a5f6d6f6e69746f725f726f6f6d002c51453042484676466e496b425249614a7450597a6f336d2f363345737635667a7a4d72397459564f73486f3d`
24 | send data:`106300044d51545404c2003c001144657669636549642d6278396e6476653200167a656e676a662f737a5f6d6f6e69746f725f726f6f6d002c51453042484676466e496b425249614a7450597a6f336d2f363345737635667a7a4d72397459564f73486f3d1a`
25 | * Connect ACK Data:
26 | 
27 | connect ack data: `20020000`
28 | * Publish Data:
29 | 
30 | publish data: `302a0010746573742d696f742d736572766963657b2270696e223a2031372c202276616c7565223a2031307d`
31 | send data: `302a0010746573742d696f742d736572766963657b2270696e223a2031372c202276616c7565223a2031307d1a`
32 |
33 | ## SIM800C Test
34 |
35 | * SIM800C Connect And Connect ACK:
36 | 
37 | * UART Send Data Command:
38 | 
39 | ```
40 | AT+CSQ
41 | +CSQ: 17,0
42 |
43 | OK
44 | AT+CREG?
45 | +CREG: 0,2
46 |
47 | OK
48 | AT+CGATT?
49 | +CGATT: 0
50 |
51 | OK
52 | AT+CSTT
53 | OK
54 | AT+CIICR
55 | OK
56 | AT+CIFSR
57 | 10.18.178.70
58 |
59 | Call Ready
60 |
61 | SMS Ready
62 | AT+CIPSTART="TCP","zengjf.mqtt.iot.gz.baidubce.com",1883
63 | OK
64 |
65 | CONNECT OK
66 | AT+CIPSEND
67 | > cMQTT?<DeviceId-bx9ndve2zengjf/sz_monitor_room,QE0BHFvFnIkBRIaJtPYzo3m/63Esv5fzzMr9tYVOsHo=
68 | SEND OK
69 | AT+CIPSEND
70 | > 0*test-iot-service{"pin": 17, "value": 10}
71 | SEND OK
72 | AT+CIPSEND
73 | > 0*test-iot-service{"pin": 17, "value": 10}
74 | SEND OK
75 | AT+CIPCLOSE
76 | CLOSE OK
77 | ```
78 | * IoT Hub Receive Data Panel:
79 | 
80 | * 至于里面的命令,可以参考:
81 | ```
82 | AT+CSQ //查询网络信号质量
83 | AT+CREG? //查询网络注册情况 其中第二个参数为1或5则说明已经注册成功
84 | AT+CGATT? //查询模块是否附着 GPRS 网络
85 | AT+CSTT //设置APN
86 | AT+CIICR //激活移动场景
87 | AT+CIFSR //获得本地IP地址
88 | # AT+CIPSTART="TCP","tcp.tlink.io",8647 //建立TCP/IP连接
89 | AT+CIPSTART="TCP","zengjf.mqtt.iot.gz.baidubce.com",1883
90 | AT+CIPSEND //模块向服务器发送数据
91 | CM1Y7DU46G2I8919 //不发送新行
92 | AT+CIPSEND
93 | @,34# //不发送新行
94 |
95 | AT+CIPGSMLOC=1,1 //获取定位信息
96 |
97 | SIM800 系列 LBS(基站定位)使用
98 | AT+SAPBR=3,1,"Contype","GPRS"
99 | // 设置选择 GPRS 服务模式
100 | OK
101 | AT+SAPBR=3,1,"APN","CMNET"
102 | // 设置 APN
103 | OK
104 | AT+SAPBR=1,1
105 | // PDP 激活,这个和 TCP/IP 同时使用不冲突
106 | OK
107 | AT+SAPBR=2,1
108 | // 获取 IP 地址
109 | +SAPBR: 1,1,"10.144.156.178"
110 | OK
111 | AT+CLBSCFG=0,3
112 | // 查询目前使用 LBS 功能默认选择的地址信息
113 | +CLBSCFG: 0,3,"www.c4a.com.cn:3002"
114 | // 这个地址是完全免费的
115 | OK
116 | AT+CLBS=1,1
117 | +CLBS: 0,121.358585,31.219023,550
118 | // 获取经纬度
119 | OK
120 | AT+CLBS=4,1
121 | +CLBS: 0,121.358599,31.219034,550,17/02/25,09:33:01 // 获取信
122 | 息详细些,包括时间信息,需要+8
123 | OK
124 | AT+SAPBR=0,1
125 | OK
126 |
127 | UDP:
128 | AT+CGATT?
129 | AT+CSTT="CMNET"
130 | AT+CIICR
131 | AT+CIFSR
132 | AT+CIPSTART="UDP","23.106.155.16","9098"
133 |
134 | AT+CIPSEND //发送数据
135 |
136 | AT+CIPCLOSE或AT+CIPSHUT 关闭TCP连接
137 | ```
138 |
--------------------------------------------------------------------------------
/docs/code/html/index_iot_hub.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Start Page
5 |
6 |
7 |
8 |
9 |
10 |
11 |
14 |
15 |
16 |
17 |
101 |
102 |
103 |
--------------------------------------------------------------------------------
/docs/code/html/index_iot_hub_map.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | 地图展示
16 |
17 |
18 |
19 |
20 |
21 |
106 |
107 |
--------------------------------------------------------------------------------
/docs/docs/0007_baidu_IoT_Hub_HTML5_MQTT.md:
--------------------------------------------------------------------------------
1 | # Baidu IoT Hub MTML5 MQTT
2 |
3 | ## Baidu IoT Hub在线测试Connect分析
4 |
5 | * 查看请求地址:
6 | 
7 | * 查看链接数据:
8 | 
9 | * 加入调试信息:
10 | 
11 | * Connect代码:
12 | ```
13 | n.prototype.connect = function() {
14 | var e = this.view.getFormData(),
15 | t = e.host,
16 | i = e.clientId,
17 | a = e.username,
18 | n = e.password,
19 | r = e.lwTopic,
20 | o = e.lwQos,
21 | s = e.lwMessage,
22 | l = parseInt(e.port, 10),
23 | d = parseInt(e.keepAlive, 10),
24 | u = !!e.cleanSession,
25 | c = !!e.lastWillRetain;
26 | this.client = new v["default"].Client(t, l, i),
27 | this.client.onConnectionLost = f["default"].bind(this.onConnectionLost, this),
28 | this.client.onMessageArrived = f["default"].bind(this.onMessageArrived, this);
29 | console.log(e);
30 | var p = {
31 | timeout: 3,
32 | keepAliveInterval: d,
33 | cleanSession: u,
34 | useSSL: !0,
35 | onSuccess: f["default"].bind(this.onConnect, this),
36 | onFailure: f["default"].bind(this.onFail, this)
37 | };
38 | if (a.length > 0 && (p.userName = a), n.length > 0 && (p.password = n), r.length > 0) {
39 | var m = new v["default"].Message(s);
40 | m.qos = o,
41 | m.destinationName = r,
42 | m.retained = c,
43 | p.willMessage = m
44 | }
45 | try {
46 | this.client.connect(p)
47 | } catch(h) {
48 | this.view.showToast("连接失败", {
49 | messageType: "error"
50 | })
51 | }
52 | },
53 | ```
54 | * [../code/IoT_Hub/startup.js](../code/IoT_Hub/startup.js)
55 |
56 | ## 个人测试用例代码:
57 |
58 | [../code/html/index_iot_hub.html](../code/html/index_iot_hub.html)
59 |
60 | ```html
61 |
62 |
63 |
64 | Start Page
65 |
66 |
67 |
68 |
69 |
70 |
74 |
75 |
118 |
119 |
120 | ```
121 |
--------------------------------------------------------------------------------
/docs/code/html/ShowTime/Baidu_Map.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | 地图展示
16 |
17 |
18 |
19 |
20 |
21 |
108 |
109 |
--------------------------------------------------------------------------------
/docs/code/paho.mqtt.embedded-c/pub0sub1.c:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright (c) 2014 IBM Corp.
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Eclipse Distribution License v1.0 which accompany this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | * and the Eclipse Distribution License is available at
11 | * http://www.eclipse.org/org/documents/edl-v10.php.
12 | *
13 | * Contributors:
14 | * Ian Craggs - initial API and implementation and/or initial documentation
15 | * Sergio R. Caprile - clarifications and/or documentation extension
16 | *******************************************************************************/
17 |
18 | #include
19 | #include
20 | #include
21 |
22 | #include "MQTTPacket.h"
23 | #include "transport.h"
24 |
25 | /* This is in order to get an asynchronous signal to stop the sample,
26 | as the code loops waiting for msgs on the subscribed topic.
27 | Your actual code will depend on your hw and approach*/
28 | #include
29 |
30 | int toStop = 0;
31 |
32 | void cfinish(int sig)
33 | {
34 | signal(SIGINT, NULL);
35 | toStop = 1;
36 | }
37 |
38 | void stop_init(void)
39 | {
40 | signal(SIGINT, cfinish);
41 | signal(SIGTERM, cfinish);
42 | }
43 | /* */
44 |
45 | int main(int argc, char *argv[])
46 | {
47 | MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
48 | int rc = 0;
49 | int mysock = 0;
50 | unsigned char buf[512];
51 | int buflen = sizeof(buf);
52 | int msgid = 1;
53 | MQTTString topicString = MQTTString_initializer;
54 | int req_qos = 0;
55 | char* payload = "{\"zengjf\": 1}";
56 | int payloadlen = strlen(payload);
57 | int len = 0;
58 | char *host = "zengjf.mqtt.iot.gz.baidubce.com";
59 | int port = 1883;
60 |
61 | stop_init();
62 | if (argc > 1)
63 | host = argv[1];
64 |
65 | if (argc > 2)
66 | port = atoi(argv[2]);
67 |
68 | mysock = transport_open(host, port);
69 | if(mysock < 0)
70 | return mysock;
71 |
72 | printf("Sending to hostname %s port %d\n", host, port);
73 |
74 | data.clientID.cstring = "me";
75 | data.keepAliveInterval = 20;
76 | data.cleansession = 1;
77 | data.username.cstring = "zengjf/sz_monitor_room";
78 | data.password.cstring = "QE0BHFvFnIkBRIaJtPYzo3m/63Esv5fzzMr9tYVOsHo=";
79 |
80 | len = MQTTSerialize_connect(buf, buflen, &data);
81 | rc = transport_sendPacketBuffer(mysock, buf, len);
82 |
83 | /* wait for connack */
84 | if (MQTTPacket_read(buf, buflen, transport_getdata) == CONNACK)
85 | {
86 | unsigned char sessionPresent, connack_rc;
87 |
88 | if (MQTTDeserialize_connack(&sessionPresent, &connack_rc, buf, buflen) != 1 || connack_rc != 0)
89 | {
90 | printf("Unable to connect, return code %d\n", connack_rc);
91 | goto exit;
92 | }
93 | }
94 | else
95 | goto exit;
96 |
97 | /* subscribe */
98 | topicString.cstring = "test-iot-service";
99 | len = MQTTSerialize_subscribe(buf, buflen, 0, msgid, 1, &topicString, &req_qos);
100 |
101 | rc = transport_sendPacketBuffer(mysock, buf, len);
102 | if (MQTTPacket_read(buf, buflen, transport_getdata) == SUBACK) /* wait for suback */
103 | {
104 | unsigned short submsgid;
105 | int subcount;
106 | int granted_qos;
107 |
108 | rc = MQTTDeserialize_suback(&submsgid, 1, &subcount, &granted_qos, buf, buflen);
109 | if (granted_qos != 0)
110 | {
111 | printf("granted qos != 0, %d\n", granted_qos);
112 | goto exit;
113 | }
114 | }
115 | else
116 | goto exit;
117 |
118 | /* loop getting msgs on subscribed topic */
119 | topicString.cstring = "test-iot-service";
120 |
121 | MQTTPacket_read(buf, buflen, transport_getdata);
122 | unsigned char dup;
123 | int qos;
124 | unsigned char retained;
125 | unsigned short msgid;
126 | int payloadlen_in;
127 | unsigned char* payload_in;
128 | int rc;
129 | MQTTString receivedTopic;
130 |
131 | rc = MQTTDeserialize_publish(&dup, &qos, &retained, &msgid, &receivedTopic,
132 | &payload_in, &payloadlen_in, buf, buflen);
133 | printf("message arrived %.*s\n", payloadlen_in, payload_in);
134 |
135 | printf("publishing reading\n");
136 | len = MQTTSerialize_publish(buf, buflen, 0, 0, 0, 0, topicString, (unsigned char*)payload, payloadlen);
137 | rc = transport_sendPacketBuffer(mysock, buf, len);
138 |
139 | printf("disconnecting\n");
140 | len = MQTTSerialize_disconnect(buf, buflen);
141 | rc = transport_sendPacketBuffer(mysock, buf, len);
142 |
143 | exit:
144 | transport_close(mysock);
145 |
146 | return 0;
147 | }
148 |
--------------------------------------------------------------------------------
/docs/docs/0011_baidu_IoT_Visualization.md:
--------------------------------------------------------------------------------
1 | # baidu IoT Hub IoT Visualization sign-aas
2 |
3 | ## 参考文档
4 |
5 | * [部署](https://cloud.baidu.com/doc/IOTVIZ/GettingStarted.html#.E5.90.8E.E7.AB.AF.E9.9B.86.E6.88.90)
6 | * [集成到 React 应用中](https://cloud.baidu.com/doc/IOTVIZ/BestPractise.html#.E4.BF.AE.E6.94.B9.E4.BB.A3.E7.A0.81)
7 | * 这里一定要理解文中的**将Token写入Cookie**这部分;
8 |
9 | ## Token Tool Download
10 |
11 | * [sign-aas Python3版本](http://iot-dv.cdn.bcebos.com/v2/sdk/sign-aas.jar)
12 |
13 | ## sign-aas help
14 |
15 | ```
16 | C:\Users\aplex\Desktop\mqtt\docs\refers>java -jar sign-aas.jar
17 | 2017-12-13 09:16:46.781:INFO::main: Logging initialized @7282ms
18 | 使用方法:java -jar 文件名.jar [options] [配置文件.json]
19 |
20 | options 选项列表:
21 | --ak AccessKey 指定AccessKey,结合默认配置使用
22 | --sk SecretAccessKey 指定SecretAccessKey,结合默认配置使用
23 | -p, --port PORT 监听的端口号,默认8080
24 | -h, --host HOST 监听的机器名/IP地址,默认为localhost
25 | -s, --sync 指定服务以同步方式运行,默认为false
26 | --max-threads NUM 最大线程数量,同步(sync)方式时无效,默认为50
27 | --min-threads NUM 最小线程数量,同步(sync)方式时无效,默认为8
28 |
29 | 基本使用方法:
30 | java -jar sign-aas.jar --ak 你的AK --sk 你的SK服务会根据默认配置提供 /tokens endpoint,用以获取物可视的访问token。
31 |
32 | 高级使用方法:
33 | java -jar sign-aas.jar [options] 配置文件.json
34 | 自定义配置内容为一个JSON数组,数组元素为JSON对象,格式如下:
35 | {
36 | "path": "本地路径通配符, 例如 /tokens**",
37 | "target": {
38 | "url": "目标服务地址,例如 https://viz.baidubce.com/",
39 | "path": "目标服务的路径,替换本地路径通配符中的具体路径,例如 /v2/tokens
40 | "
41 | },
42 | "ak": "你的 AccessKey",
43 | "sk": "你 的SecretAccessKey"
44 | }
45 | 如上配置会将发至 /tokens 路径下的请求加上Ak+Sk签名,转发至 https://viz.baidubce.com/v2/tokens。
46 | ```
47 |
48 | ## 运行sign-ass
49 |
50 | ```
51 | C:\Users\aplex\Desktop\mqtt\docs\refers>java -jar sign-aas.jar --ak=5c5b5ea289ed4c6db75c131e7eaf5715 --sk=ca49ed4d426541e79f7da83fde4b9e28
52 | 2017-12-13 09:46:41.731:INFO::main: Logging initialized @1155ms
53 | 2017-12-13 09:46:43.597:INFO:oejs.Server:main: jetty-9.2.z-SNAPSHOT
54 | 2017-12-13 09:46:44.063:INFO:oejs.ServerConnector:main: Started ServerConnector@1bd13f0c{HTTP/1.1}{localhost:8080}
55 | 2017-12-13 09:46:44.065:INFO:oejs.Server:main: Started @3490ms
56 | ```
57 |
58 | ## 获取Token的两种处理方式
59 |
60 | * [../code/IoT_Visualization/sign-ass.py](../code/IoT_Visualization/sign-ass.py)
61 | * [../code/IoT_Visualization/bce_tokens.py](../code/IoT_Visualization/bce_tokens.py)
62 |
63 | ## 布局示例
64 |
65 | 
66 |
67 | ## 网页独立部署方法
68 |
69 | * 下载[xampp](https://www.apachefriends.org/zh_cn/index.html)作为Web Server;
70 | * 设计UI界面,获取设计好的网页生成代码;
71 | ```HTML
72 |
73 |
74 |
75 |
76 |
91 |
92 |
93 |
94 |
95 |
96 |
111 |
112 |
113 | ```
114 | * 通过[sign-ass.py](../code/IoT_Visualization/sign-ass.py)获取Token;
115 | ```
116 | D:\zengjf\SourceCode\Android\as\MQTT\docs\code\IoT_Visualization>sign-ass.py
117 |
118 | ('/tokens', '{"ttl": 36000}')
119 |
120 | POST /tokens HTTP/1.1
121 | Host: 127.0.0.1:8080
122 | Accept-Encoding: identity
123 | Content-Length: 14
124 | Content-type: application/json; charset=utf-8
125 |
126 | {"ttl": 36000}
127 |
128 | (200, 'OK')
129 |
130 | {"token":"bce_iot_viz_tokenC2NK9PMDNXETCTTDJFH0JJCPZW8WZ2GMGJLB8S2MIGCODSI7PZ5IILNI3OH3KIFB"}
131 | ```
132 | * [HTML index.html 示例](../code/IoT_Visualization/index.html);
133 | * 将上面sign-ass.py获取的Token替换掉HTML的Cookie中作为认证依据,主要是下面这行代码;
134 | `TOKEN_COOKIES_VALUE = "bce_iot_viz_tokenC2NK9PMDNXETCTTDJFH0JJCPZW8WZ2GMGJLB8S2MIGCODSI7PZ5IILNI3OH3KIFB";`
135 | * 将修改后的[index.html](../code/IoT_Visualization/index.html)部署与xampp Web Server中,使用浏览器(推荐Chrome)如下所示:
136 | 
137 |
--------------------------------------------------------------------------------
/app/src/main/java/com/android/aplex/mqtt/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.android.aplex.mqtt;
2 |
3 | import android.net.Uri;
4 | import android.support.v4.app.Fragment;
5 | import android.support.v4.app.FragmentManager;
6 | import android.support.v4.app.FragmentPagerAdapter;
7 | import android.support.v4.view.ViewPager;
8 | import android.support.v7.app.AppCompatActivity;
9 | import android.os.Bundle;
10 | import android.util.Log;
11 |
12 | import com.android.aplex.mqtt.fragment.Show;
13 | import com.android.aplex.mqtt.fragment.BaseBlankFragment;
14 | import com.android.aplex.mqtt.fragment.Publish;
15 | import com.android.aplex.mqtt.fragment.Settings;
16 | import com.android.aplex.mqtt.fragment.Subscribe;
17 | import com.android.aplex.mqtt.tools.SPUtils;
18 | import com.lzy.widget.AlphaIndicator;
19 |
20 | import org.eclipse.paho.android.service.MqttAndroidClient;
21 | import org.eclipse.paho.client.mqttv3.IMqttActionListener;
22 | import org.eclipse.paho.client.mqttv3.IMqttToken;
23 | import org.eclipse.paho.client.mqttv3.MqttClient;
24 | import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
25 | import org.eclipse.paho.client.mqttv3.MqttException;
26 | import org.eclipse.paho.client.mqttv3.MqttMessage;
27 | import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
28 |
29 | import java.util.ArrayList;
30 | import java.util.List;
31 |
32 | public class MainActivity extends AppCompatActivity implements BaseBlankFragment.OnFragmentInteractionListener{
33 |
34 | public boolean connect_success = false;
35 |
36 | @Override
37 | protected void onCreate(Bundle savedInstanceState) {
38 | super.onCreate(savedInstanceState);
39 | setContentView(R.layout.activity_main);
40 |
41 | SPUtils.setApplication(this);
42 |
43 | getSupportActionBar().setCustomView(R.layout.mainactivity_actionbar);
44 | getSupportActionBar().setDisplayShowCustomEnabled(true);
45 |
46 | ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
47 | viewPager.setAdapter(new MainAdapter(getSupportFragmentManager()));
48 | AlphaIndicator alphaIndicator = (AlphaIndicator) findViewById(R.id.alphaIndicator);
49 | alphaIndicator.setViewPager(viewPager);
50 |
51 | Thread thread = new Thread(new Runnable() {
52 | @Override
53 | public void run() {
54 | // refer: http://www.eclipse.org/paho/files/android-javadoc/org/eclipse/paho/android/service/MqttAndroidClient.html
55 | MemoryPersistence memPer = new MemoryPersistence();
56 | MqttClient client = null;
57 | try {
58 | client = new MqttClient("tcp://zengjf.mqtt.iot.gz.baidubce.com:1883", "DeviceId-bx9n", memPer);
59 | } catch (MqttException e) {
60 | e.printStackTrace();
61 | }
62 | MqttConnectOptions options = new MqttConnectOptions();
63 | options.setUserName("zengjf/sz_monitor_room");
64 | options.setPassword("QE0BHFvFnIkBRIaJtPYzo3m/63Esv5fzzMr9tYVOsHo=".toCharArray());
65 |
66 | try {
67 |
68 | try {
69 | client.connect(options);
70 | } catch (MqttException e1) {
71 | e1.printStackTrace();
72 | }
73 |
74 | MqttMessage message = new MqttMessage();
75 | message.setQos(0);
76 | message.setPayload("{\"zengjf\": \"Android\"}".getBytes());
77 | try {
78 | client.publish("test-iot-service", message);
79 | client.disconnect();
80 | } catch (MqttException e) {
81 | e.printStackTrace();
82 | }
83 |
84 | } catch (Exception e) {
85 | e.printStackTrace();
86 | }
87 |
88 | }
89 | });
90 | thread.start();
91 |
92 | }
93 |
94 | @Override
95 | public void onFragmentInteraction(Uri uri) {
96 | Log.e("MainActivity", uri.toString());
97 | }
98 |
99 | private class MainAdapter extends FragmentPagerAdapter {
100 |
101 | private List fragments = new ArrayList<>();
102 |
103 | public MainAdapter(FragmentManager fm) {
104 | super(fm);
105 | try {
106 | fragments.add(BaseBlankFragment.newInstance(Settings.class, null));
107 | fragments.add(BaseBlankFragment.newInstance(Publish.class, null));
108 | fragments.add(BaseBlankFragment.newInstance(Subscribe.class, null));
109 | fragments.add(BaseBlankFragment.newInstance(Show.class, null));
110 | } catch (Exception e) {
111 | e.printStackTrace();
112 | }
113 | }
114 |
115 | @Override
116 | public Fragment getItem(int position) {
117 | return fragments.get(position);
118 | }
119 |
120 | @Override
121 | public int getCount() {
122 | return fragments.size();
123 | }
124 | }
125 |
126 | }
127 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/docs/code/TSDB/sign_sample.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | import hashlib
3 | import hmac
4 | import string
5 | import datetime
6 | from urllib import quote_plus
7 |
8 |
9 | AUTHORIZATION = "authorization"
10 | BCE_PREFIX = "x-bce-"
11 | DEFAULT_ENCODING = 'UTF-8'
12 |
13 |
14 | # 保存AK/SK的类
15 | class BceCredentials(object):
16 | def __init__(self, access_key_id, secret_access_key):
17 | self.access_key_id = access_key_id
18 | self.secret_access_key = secret_access_key
19 |
20 |
21 | # 根据RFC 3986,除了:
22 | # 1.大小写英文字符
23 | # 2.阿拉伯数字
24 | # 3.点'.'、波浪线'~'、减号'-'以及下划线'_'
25 | # 以外都要编码
26 | RESERVED_CHAR_SET = set(string.ascii_letters + string.digits + '.~-_')
27 | def get_normalized_char(i):
28 | char = chr(i)
29 | if char in RESERVED_CHAR_SET:
30 | return char
31 | else:
32 | return '%%%02X' % i
33 | NORMALIZED_CHAR_LIST = [get_normalized_char(i) for i in range(256)]
34 |
35 |
36 | # 正规化字符串
37 | def normalize_string(in_str, encoding_slash=True):
38 | if in_str is None:
39 | return ''
40 |
41 | # 如果输入是unicode,则先使用UTF8编码之后再编码
42 | in_str = in_str.encode(DEFAULT_ENCODING) if isinstance(in_str, unicode) else str(in_str)
43 |
44 | # 在生成规范URI时。不需要对斜杠'/'进行编码,其他情况下都需要
45 | if encoding_slash:
46 | encode_f = lambda c: NORMALIZED_CHAR_LIST[ord(c)]
47 | else:
48 | # 仅仅在生成规范URI时。不需要对斜杠'/'进行编码
49 | encode_f = lambda c: NORMALIZED_CHAR_LIST[ord(c)] if c != '/' else c
50 |
51 | # 按照RFC 3986进行编码
52 | return ''.join([encode_f(ch) for ch in in_str])
53 |
54 |
55 | # 生成规范时间戳
56 | def get_canonical_time(timestamp=0):
57 | # 不使用任何参数调用的时候返回当前时间
58 | if timestamp == 0:
59 | utctime = datetime.datetime.utcnow()
60 | else:
61 | utctime = datetime.datetime.utcfromtimestamp(timestamp)
62 |
63 | # 时间戳格式:[year]-[month]-[day]T[hour]:[minute]:[second]Z
64 | return "%04d-%02d-%02dT%02d:%02d:%02dZ" % (
65 | utctime.year, utctime.month, utctime.day,
66 | utctime.hour, utctime.minute, utctime.second)
67 |
68 |
69 | # 生成规范URI
70 | def get_canonical_uri(path):
71 | # 规范化URI的格式为:/{bucket}/{object},并且要对除了斜杠"/"之外的所有字符编码
72 | return normalize_string(path, False)
73 |
74 |
75 | # 生成规范query string
76 | def get_canonical_querystring(params):
77 | if params is None:
78 | return ''
79 |
80 | # 除了authorization之外,所有的query string全部加入编码
81 | result = ['%s=%s' % (k, normalize_string(v)) for k, v in params.items() if k.lower != AUTHORIZATION]
82 |
83 | # 按字典序排序
84 | result.sort()
85 |
86 | # 使用&符号连接所有字符串并返回
87 | return '&'.join(result)
88 |
89 |
90 | # 生成规范header
91 | def get_canonical_headers(headers, headers_to_sign=None):
92 | headers = headers or {}
93 |
94 | # 没有指定header_to_sign的情况下,默认使用:
95 | # 1.host
96 | # 2.content-md5
97 | # 3.content-length
98 | # 4.content-type
99 | # 5.所有以x-bce-开头的header项
100 | # 生成规范header
101 | if headers_to_sign is None or len(headers_to_sign) == 0:
102 | headers_to_sign = {"host", "content-md5", "content-length", "content-type"}
103 |
104 | # 对于header中的key,去掉前后的空白之后需要转化为小写
105 | # 对于header中的value,转化为str之后去掉前后的空白
106 | f = lambda (key, value): (key.strip().lower(), str(value).strip())
107 |
108 | result = []
109 | for k, v in map(f, headers.iteritems()):
110 | # 无论何种情况,以x-bce-开头的header项都需要被添加到规范header中
111 | if k.startswith(BCE_PREFIX) or k in headers_to_sign:
112 | result.append("%s:%s" % (normalize_string(k), normalize_string(v)))
113 |
114 | # 按照字典序排序
115 | result.sort()
116 |
117 | # 使用\n符号连接所有字符串并返回
118 | return '\n'.join(result)
119 |
120 |
121 | # 签名主算法
122 | def sign(credentials, http_method, path, headers, params,
123 | timestamp=0, expiration_in_seconds=1800, headers_to_sign=None):
124 | headers = headers or {}
125 | params = params or {}
126 |
127 | # 1.生成sign key
128 | # 1.1.生成auth-string,格式为:bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}
129 | sign_key_info = 'bce-auth-v1/%s/%s/%d' % (
130 | credentials.access_key_id,
131 | get_canonical_time(timestamp),
132 | expiration_in_seconds)
133 | # 1.2.使用auth-string加上SK,用SHA-256生成sign key
134 | sign_key = hmac.new(
135 | credentials.secret_access_key,
136 | sign_key_info,
137 | hashlib.sha256).hexdigest()
138 |
139 | # 2.生成规范化uri
140 | canonical_uri = get_canonical_uri(path)
141 |
142 | # 3.生成规范化query string
143 | canonical_querystring = get_canonical_querystring(params)
144 |
145 | # 4.生成规范化header
146 | canonical_headers = get_canonical_headers(headers, headers_to_sign)
147 |
148 | # 5.使用'\n'将HTTP METHOD和2、3、4中的结果连接起来,成为一个大字符串
149 | string_to_sign = '\n'.join(
150 | [http_method, canonical_uri, canonical_querystring, canonical_headers])
151 |
152 | # 6.使用5中生成的签名串和1中生成的sign key,用SHA-256算法生成签名结果
153 | sign_result = hmac.new(sign_key, string_to_sign, hashlib.sha256).hexdigest()
154 |
155 | # 7.拼接最终签名结果串
156 | if headers_to_sign:
157 | # 指定header to sign
158 | result = '%s/%s/%s' % (sign_key_info, ';'.join(headers_to_sign), sign_result)
159 | else:
160 | # 不指定header to sign情况下的默认签名结果串
161 | result = '%s//%s' % (sign_key_info, sign_result)
162 |
163 | return result
164 |
165 | if __name__ == "__main__":
166 | credentials = BceCredentials("5c5b5ea289ed4c6db75c131e7eaf5715","ca49ed4d426541e79f7da83fde4b9e28")
167 | http_method = "GET"
168 | path = "/v1/metric"
169 | headers = {"host": "zengjf.tsdb.iot.gz.baidubce.com",
170 | "content-type":"application/json; charset=utf-8"}
171 | params = {}
172 | timestamp = 1511995554
173 | result = sign(credentials, http_method, path, headers, None, timestamp)
174 | print result
175 | print '----------------------------------'
176 | print quote_plus(result)
177 |
--------------------------------------------------------------------------------
/docs/code/IoT_Visualization/sign_sample.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | import hashlib
3 | import hmac
4 | import string
5 | import datetime
6 | from urllib import quote_plus
7 |
8 |
9 | AUTHORIZATION = "authorization"
10 | BCE_PREFIX = "x-bce-"
11 | DEFAULT_ENCODING = 'UTF-8'
12 |
13 |
14 | # 保存AK/SK的类
15 | class BceCredentials(object):
16 | def __init__(self, access_key_id, secret_access_key):
17 | self.access_key_id = access_key_id
18 | self.secret_access_key = secret_access_key
19 |
20 |
21 | # 根据RFC 3986,除了:
22 | # 1.大小写英文字符
23 | # 2.阿拉伯数字
24 | # 3.点'.'、波浪线'~'、减号'-'以及下划线'_'
25 | # 以外都要编码
26 | RESERVED_CHAR_SET = set(string.ascii_letters + string.digits + '.~-_')
27 | def get_normalized_char(i):
28 | char = chr(i)
29 | if char in RESERVED_CHAR_SET:
30 | return char
31 | else:
32 | return '%%%02X' % i
33 | NORMALIZED_CHAR_LIST = [get_normalized_char(i) for i in range(256)]
34 |
35 |
36 | # 正规化字符串
37 | def normalize_string(in_str, encoding_slash=True):
38 | if in_str is None:
39 | return ''
40 |
41 | # 如果输入是unicode,则先使用UTF8编码之后再编码
42 | in_str = in_str.encode(DEFAULT_ENCODING) if isinstance(in_str, unicode) else str(in_str)
43 |
44 | # 在生成规范URI时。不需要对斜杠'/'进行编码,其他情况下都需要
45 | if encoding_slash:
46 | encode_f = lambda c: NORMALIZED_CHAR_LIST[ord(c)]
47 | else:
48 | # 仅仅在生成规范URI时。不需要对斜杠'/'进行编码
49 | encode_f = lambda c: NORMALIZED_CHAR_LIST[ord(c)] if c != '/' else c
50 |
51 | # 按照RFC 3986进行编码
52 | return ''.join([encode_f(ch) for ch in in_str])
53 |
54 |
55 | # 生成规范时间戳
56 | def get_canonical_time(timestamp=0):
57 | # 不使用任何参数调用的时候返回当前时间
58 | if timestamp == 0:
59 | utctime = datetime.datetime.utcnow()
60 | else:
61 | utctime = datetime.datetime.utcfromtimestamp(timestamp)
62 |
63 | # 时间戳格式:[year]-[month]-[day]T[hour]:[minute]:[second]Z
64 | return "%04d-%02d-%02dT%02d:%02d:%02dZ" % (
65 | utctime.year, utctime.month, utctime.day,
66 | utctime.hour, utctime.minute, utctime.second)
67 |
68 |
69 | # 生成规范URI
70 | def get_canonical_uri(path):
71 | # 规范化URI的格式为:/{bucket}/{object},并且要对除了斜杠"/"之外的所有字符编码
72 | return normalize_string(path, False)
73 |
74 |
75 | # 生成规范query string
76 | def get_canonical_querystring(params):
77 | if params is None:
78 | return ''
79 |
80 | # 除了authorization之外,所有的query string全部加入编码
81 | result = ['%s=%s' % (k, normalize_string(v)) for k, v in params.items() if k.lower != AUTHORIZATION]
82 |
83 | # 按字典序排序
84 | result.sort()
85 |
86 | # 使用&符号连接所有字符串并返回
87 | return '&'.join(result)
88 |
89 |
90 | # 生成规范header
91 | def get_canonical_headers(headers, headers_to_sign=None):
92 | headers = headers or {}
93 |
94 | # 没有指定header_to_sign的情况下,默认使用:
95 | # 1.host
96 | # 2.content-md5
97 | # 3.content-length
98 | # 4.content-type
99 | # 5.所有以x-bce-开头的header项
100 | # 生成规范header
101 | if headers_to_sign is None or len(headers_to_sign) == 0:
102 | headers_to_sign = {"host", "content-md5", "content-length", "content-type"}
103 |
104 | # 对于header中的key,去掉前后的空白之后需要转化为小写
105 | # 对于header中的value,转化为str之后去掉前后的空白
106 | f = lambda (key, value): (key.strip().lower(), str(value).strip())
107 |
108 | result = []
109 | for k, v in map(f, headers.iteritems()):
110 | # 无论何种情况,以x-bce-开头的header项都需要被添加到规范header中
111 | if k.startswith(BCE_PREFIX) or k in headers_to_sign:
112 | result.append("%s:%s" % (normalize_string(k), normalize_string(v)))
113 |
114 | # 按照字典序排序
115 | result.sort()
116 |
117 | # 使用\n符号连接所有字符串并返回
118 | return '\n'.join(result)
119 |
120 |
121 | # 签名主算法
122 | def sign(credentials, http_method, path, headers, params,
123 | timestamp=0, expiration_in_seconds=1800, headers_to_sign=None):
124 | headers = headers or {}
125 | params = params or {}
126 |
127 | # 1.生成sign key
128 | # 1.1.生成auth-string,格式为:bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}
129 | sign_key_info = 'bce-auth-v1/%s/%s/%d' % (
130 | credentials.access_key_id,
131 | get_canonical_time(timestamp),
132 | expiration_in_seconds)
133 | # 1.2.使用auth-string加上SK,用SHA-256生成sign key
134 | sign_key = hmac.new(
135 | credentials.secret_access_key,
136 | sign_key_info,
137 | hashlib.sha256).hexdigest()
138 |
139 | # 2.生成规范化uri
140 | canonical_uri = get_canonical_uri(path)
141 |
142 | # 3.生成规范化query string
143 | canonical_querystring = get_canonical_querystring(params)
144 |
145 | # 4.生成规范化header
146 | canonical_headers = get_canonical_headers(headers, headers_to_sign)
147 |
148 | # 5.使用'\n'将HTTP METHOD和2、3、4中的结果连接起来,成为一个大字符串
149 | string_to_sign = '\n'.join(
150 | [http_method, canonical_uri, canonical_querystring, canonical_headers])
151 |
152 | # 6.使用5中生成的签名串和1中生成的sign key,用SHA-256算法生成签名结果
153 | sign_result = hmac.new(sign_key, string_to_sign, hashlib.sha256).hexdigest()
154 |
155 | # 7.拼接最终签名结果串
156 | if headers_to_sign:
157 | # 指定header to sign
158 | result = '%s/%s/%s' % (sign_key_info, ';'.join(headers_to_sign), sign_result)
159 | else:
160 | # 不指定header to sign情况下的默认签名结果串
161 | result = '%s//%s' % (sign_key_info, sign_result)
162 |
163 | return result
164 |
165 | if __name__ == "__main__":
166 | credentials = BceCredentials("5c5b5ea289ed4c6db75c131e7eaf5715","ca49ed4d426541e79f7da83fde4b9e28")
167 | http_method = "GET"
168 | path = "/v1/metric"
169 | headers = {"host": "zengjf.tsdb.iot.gz.baidubce.com",
170 | "content-type":"application/json; charset=utf-8"}
171 | params = {}
172 | timestamp = 1511995554
173 | result = sign(credentials, http_method, path, headers, None, timestamp)
174 | print result
175 | print '----------------------------------'
176 | print quote_plus(result)
177 |
--------------------------------------------------------------------------------
/docs/code/paho.mqtt.embedded-c/transport.c:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright (c) 2014 IBM Corp.
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Eclipse Distribution License v1.0 which accompany this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | * and the Eclipse Distribution License is available at
11 | * http://www.eclipse.org/org/documents/edl-v10.php.
12 | *
13 | * Contributors:
14 | * Ian Craggs - initial API and implementation and/or initial documentation
15 | * Sergio R. Caprile - "commonalization" from prior samples and/or documentation extension
16 | *******************************************************************************/
17 |
18 | #include
19 |
20 | #if !defined(SOCKET_ERROR)
21 | /** error in socket operation */
22 | #define SOCKET_ERROR -1
23 | #endif
24 |
25 | #if defined(WIN32)
26 | /* default on Windows is 64 - increase to make Linux and Windows the same */
27 | #define FD_SETSIZE 1024
28 | #include
29 | #include
30 | #define MAXHOSTNAMELEN 256
31 | #define EAGAIN WSAEWOULDBLOCK
32 | #define EINTR WSAEINTR
33 | #define EINVAL WSAEINVAL
34 | #define EINPROGRESS WSAEINPROGRESS
35 | #define EWOULDBLOCK WSAEWOULDBLOCK
36 | #define ENOTCONN WSAENOTCONN
37 | #define ECONNRESET WSAECONNRESET
38 | #define ioctl ioctlsocket
39 | #define socklen_t int
40 | #else
41 | #define INVALID_SOCKET SOCKET_ERROR
42 | #include
43 | #include
44 | #include
45 | #include
46 | #include
47 | #include
48 | #include
49 | #include
50 | #include
51 | #include
52 | #include
53 | #include
54 | #include
55 | #endif
56 |
57 | #if defined(WIN32)
58 | #include
59 | #else
60 | #include
61 | #include
62 | #endif
63 |
64 | /**
65 | This simple low-level implementation assumes a single connection for a single thread. Thus, a static
66 | variable is used for that connection.
67 | On other scenarios, the user must solve this by taking into account that the current implementation of
68 | MQTTPacket_read() has a function pointer for a function call to get the data to a buffer, but no provisions
69 | to know the caller or other indicator (the socket id): int (*getfn)(unsigned char*, int)
70 | */
71 | static int mysock = INVALID_SOCKET;
72 |
73 |
74 | int transport_sendPacketBuffer(int sock, unsigned char* buf, int buflen)
75 | {
76 | int rc = 0;
77 | rc = write(sock, buf, buflen);
78 | return rc;
79 | }
80 |
81 |
82 | int transport_getdata(unsigned char* buf, int count)
83 | {
84 | int rc = recv(mysock, buf, count, 0);
85 | //printf("received %d bytes count %d\n", rc, (int)count);
86 | return rc;
87 | }
88 |
89 | int transport_getdatanb(void *sck, unsigned char* buf, int count)
90 | {
91 | int sock = *((int *)sck); /* sck: pointer to whatever the system may use to identify the transport */
92 | /* this call will return after the timeout set on initialization if no bytes;
93 | in your system you will use whatever you use to get whichever outstanding
94 | bytes your socket equivalent has ready to be extracted right now, if any,
95 | or return immediately */
96 | int rc = recv(sock, buf, count, 0);
97 | if (rc == -1) {
98 | /* check error conditions from your system here, and return -1 */
99 | return 0;
100 | }
101 | return rc;
102 | }
103 |
104 | /**
105 | return >=0 for a socket descriptor, <0 for an error code
106 | @todo Basically moved from the sample without changes, should accomodate same usage for 'sock' for clarity,
107 | removing indirections
108 | */
109 | int transport_open(char* addr, int port)
110 | {
111 | int* sock = &mysock;
112 | int type = SOCK_STREAM;
113 | struct sockaddr_in address;
114 | #if defined(AF_INET6)
115 | struct sockaddr_in6 address6;
116 | #endif
117 | int rc = -1;
118 | #if defined(WIN32)
119 | short family;
120 | #else
121 | sa_family_t family = AF_INET;
122 | #endif
123 | struct addrinfo *result = NULL;
124 | struct addrinfo hints = {0, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL, NULL};
125 | static struct timeval tv;
126 |
127 | *sock = -1;
128 | if (addr[0] == '[')
129 | ++addr;
130 |
131 | if ((rc = getaddrinfo(addr, NULL, &hints, &result)) == 0)
132 | {
133 | struct addrinfo* res = result;
134 |
135 | /* prefer ip4 addresses */
136 | while (res)
137 | {
138 | if (res->ai_family == AF_INET)
139 | {
140 | result = res;
141 | break;
142 | }
143 | res = res->ai_next;
144 | }
145 |
146 | #if defined(AF_INET6)
147 | if (result->ai_family == AF_INET6)
148 | {
149 | address6.sin6_port = htons(port);
150 | address6.sin6_family = family = AF_INET6;
151 | address6.sin6_addr = ((struct sockaddr_in6*)(result->ai_addr))->sin6_addr;
152 | }
153 | else
154 | #endif
155 | if (result->ai_family == AF_INET)
156 | {
157 | address.sin_port = htons(port);
158 | address.sin_family = family = AF_INET;
159 | address.sin_addr = ((struct sockaddr_in*)(result->ai_addr))->sin_addr;
160 | }
161 | else
162 | rc = -1;
163 |
164 | freeaddrinfo(result);
165 | }
166 |
167 | if (rc == 0)
168 | {
169 | *sock = socket(family, type, 0);
170 | if (*sock != -1)
171 | {
172 | #if defined(NOSIGPIPE)
173 | int opt = 1;
174 |
175 | if (setsockopt(*sock, SOL_SOCKET, SO_NOSIGPIPE, (void*)&opt, sizeof(opt)) != 0)
176 | Log(TRACE_MIN, -1, "Could not set SO_NOSIGPIPE for socket %d", *sock);
177 | #endif
178 |
179 | if (family == AF_INET)
180 | rc = connect(*sock, (struct sockaddr*)&address, sizeof(address));
181 | #if defined(AF_INET6)
182 | else
183 | rc = connect(*sock, (struct sockaddr*)&address6, sizeof(address6));
184 | #endif
185 | }
186 | }
187 | if (mysock == INVALID_SOCKET)
188 | return rc;
189 |
190 | tv.tv_sec = 1; /* 1 second Timeout */
191 | tv.tv_usec = 0;
192 | // setsockopt(mysock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval));
193 | return mysock;
194 | }
195 |
196 | int transport_close(int sock)
197 | {
198 | int rc;
199 |
200 | rc = shutdown(sock, SHUT_WR);
201 | rc = recv(sock, NULL, (size_t)0, 0);
202 | rc = close(sock);
203 |
204 | return rc;
205 | }
206 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_settings.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
10 |
13 |
14 |
18 |
19 |
28 |
29 |
38 |
39 |
48 |
49 |
55 |
56 |
62 |
63 |
72 |
73 |
82 |
83 |
88 |
89 |
93 |
94 |
104 |
105 |
114 |
115 |
116 |
117 |
118 |
119 |
128 |
129 |
138 |
139 |
140 |
141 |
147 |
148 |
149 |
150 |
151 |
--------------------------------------------------------------------------------
/docs/docs/0004_mosquitto_SSL_single_CA.md:
--------------------------------------------------------------------------------
1 | # mosquitto SSL single CA
2 |
3 | ## 参考文档
4 |
5 | * [单向和双向 SSL 认证](https://www.ibm.com/support/knowledgecenter/zh/SSRMWJ_7.0.1/com.ibm.isim.doc/securing/cpt/cpt_ic_security_ssl_scenario.htm)
6 | * [Wrapping MQTT data in SSL certificate while sending it to MQTT broker](https://stackoverflow.com/questions/24637763/wrapping-mqtt-data-in-ssl-certificate-while-sending-it-to-mqtt-broker)
7 | * [那些证书相关的玩意儿(SSL,X.509,PEM,DER,CRT,CER,KEY,CSR,P12等)](http://www.cnblogs.com/guogangj/p/4118605.html)
8 | * [Mosquito使用SSL/TLS进行安全通信时的使用方法](http://blog.csdn.net/houjixin/article/details/24305613)
9 | * [[12]MQTT mosquitto 单向SSL认证的配置方式](http://blog.csdn.net/chancein007/article/details/46293031)
10 | * [MQTT安全篇](http://dataguild.org/?p=6866)
11 | * [mosquitto-tls-7](https://mosquitto.org/man/mosquitto-tls-7.html)
12 |
13 | ## SSL/TLS
14 |
15 | SSL - Secure Sockets Layer,现在应该叫"TLS",但由于习惯问题,我们还是叫"SSL"比较多。
16 |
17 | OpenSSL是SSL的一个实现,SSL只是一种规范。OpenSSL提供了一大堆强大的工具软件,强大到90%我们都用不到。
18 |
19 | ## 证书标准
20 |
21 | X.509 - 这是一种证书标准,主要定义了证书中应该包含哪些内容.其详情可以参考RFC5280,SSL使用的就是这种证书标准.
22 |
23 | ## 编码格式
24 |
25 | 同样的X.509证书,可能有不同的编码格式,目前有以下两种编码格式.
26 |
27 | * PEM - Privacy Enhanced Mail,打开看文本格式,以"-----BEGIN..."开头, "-----END..."结尾,内容是BASE64编码.
28 | * 查看PEM格式证书的信息:openssl x509 -in certificate.pem -text -noout
29 | * Apache和*NIX服务器偏向于使用这种编码格式.
30 | * DER - Distinguished Encoding Rules,打开看是二进制格式,不可读。
31 | * 查看DER格式证书的信息:openssl x509 -in certificate.der -inform der -text -noout
32 | * Java和Windows服务器偏向于使用这种编码格式。
33 |
34 | ## 相关的文件扩展名
35 |
36 | 这是比较误导人的地方,虽然我们已经知道有PEM和DER这两种编码格式,但文件扩展名并不一定就叫"PEM"或者"DER",常见的扩展名除了PEM和DER还有以下这些,它们除了编码格式可能不同之外,内容也有差别,但大多数都能相互转换编码格式。
37 |
38 | * CRT - CRT应该是certificate的三个字母,其实还是证书的意思,常见于*NIX系统,有可能是PEM编码,也有可能是DER编码,大多数应该是PEM编码,相信你已经知道怎么辨别。
39 | * CER - 还是certificate,还是证书,常见于Windows系统,同样的,可能是PEM编码,也可能是DER编码,大多数应该是DER编码。
40 | * KEY - 通常用来存放一个公钥或者私钥,并非X.509证书,编码同样的,可能是PEM,也可能是DER。
41 | * CSR - Certificate Signing Request,即证书签名请求,这个并不是证书,而是向权威证书颁发机构获得签名证书的申请,其核心内容是一个公钥(当然还附带了一些别的信息),在生成这个申请的时候,同时也会生成一个私钥,私钥要自己保管好。
42 |
43 | ## 证书编码的转换
44 |
45 | * PEM转为DER openssl x509 -in cert.crt -outform der -out cert.der
46 | * DER转为PEM openssl x509 -in cert.crt -inform der -outform pem -out cert.pem
47 |
48 | ## 获得证书
49 |
50 | SSL在身份认证过程中需要有一个双方都信任的CA签发的证书,CA签发证书是需要收费的,但是在测试过程中,可以自己产生一个CA,然后用自己产生的CA签发证书。
51 |
52 | ### 向权威证书颁发机构申请证书
53 |
54 | `openssl req -newkey rsa:2048 -new -nodes -keyout my.key -out my.csr`
55 |
56 | 把csr交给权威证书颁发机构,权威证书颁发机构对此进行签名,完成。保留好csr,当权威证书颁发机构颁发的证书过期的时候,你还可以用同样的csr来申请新的证书,key保持不变。
57 |
58 | ### 生成自签名的证书
59 |
60 | `openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem`
61 |
62 | 在生成证书的过程中会要你填一堆的东西,其实真正要填的只有Common Name,通常填写你服务器的域名,如"yourcompany.com",或者你服务器的IP地址,其它都可以留空的。
63 |
64 | 生产环境中还是不要使用自签的证书,否则浏览器会不认,或者如果你是企业应用的话能够强制让用户的浏览器接受你的自签证书也行.向权威机构要证书通常是要钱的,但现在也有免费的,仅仅需要一个简单的域名验证即可。有兴趣的话查查"沃通数字证书"。
65 |
66 | ## 命令解析
67 |
68 | * openssl req -new -x509 -days 36500 -extensions v3_ca -keyout ca.key -out ca.crt
69 | * 产生CA认证的key和证书文件;
70 | * 产生一个名字为"ca.key"的key文件和一个名字为"ca.crt"的证书文件,这个crt就是CA认证自己给自己签名的证书文件;
71 | * 命令中选项“-x509”表示该条命令将产生自签名的证书,一般都是测试的时候采用。
72 | * openssl genrsa -out server.key 2048
73 | * 产生一个不加密的RSA私钥,其中参数"2048"表示私钥的长度,这里产生的私钥文件"server.key"将在下一步使用,同时在mosquitto程序的配置文件中也需要使用。
74 | * openssl req -out server.csr -key server.key -new
75 | * 使用上一步产生的"server.key"文件为server产生一个签发证书所需要的请求文件:server.csr,使用该文件向CA发送请求才会得到CA签发的证书。
76 | * openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 36500
77 | * 使用CA的密钥文件ca.key,CA的证书文件ca.crt和上一步为mosquitto server产生证书请求文件server.csr文件这三个文件向CA请求产生一个证书文件,证书文件的名字为:server.crt。该命令中的36500可以修改为自己定义的时间值。
78 | * openssl genrsa -out client.key 2048
79 | * 为mosquitto的客户端程序产生私钥文件"client.key"和证书文件"client.crt"
80 | * openssl req -out client.csr -key client.key -new
81 | * 为mosquitto客户端产生一个签发证书的请求文件"client.csr";
82 | * 产生证书请求文件时需要第一步产生的私钥文件client.key作为输入。
83 | * openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 36500
84 | * CA为mosquitto客户端产生一个证书文件"client.crt"
85 |
86 | **注意事项**
87 |
88 | * 制作签发证书的请求文件时,需要输入Common Name参数,此参数一定为当前主机的IP地址;
89 | * 如果不想SSL在身份认证的时候检查主机名(也即上面不检查第1条中Common Name参数),则需要在启动订阅端的时候,加上“--insecure”参数;
90 | * 自测过程中,server端与所有客户端所使用的证书必须由一个CA签发,否则,将会提示CA不识别的问题。
91 |
92 | ## 用户名、密码
93 |
94 | * `sudo mosquitto_passwd -c /etc/mosquitto/passwd zengjf`
95 | * `sudo nano /etc/mosquitto/conf.d/default.conf`
96 | ```
97 | allow_anonymous false
98 | password_file /etc/mosquitto/passwd
99 | ```
100 | * `sudo systemctl restart mosquitto`
101 | * `mosquitto_sub -h localhost -t test -u "zengjf" -P "password"`
102 | * `mosquitto_pub -h localhost -t "test" -m "hello world" -u "zengjf" -P "password"`
103 |
104 | ## 测试方法
105 |
106 | * 参考[《Enable Secure Communication with TLS and the Mosquitto Broker》](https://mcuoneclipse.com/2017/04/14/enable-secure-communication-with-tls-and-the-mosquitto-broker/)中的方法进行测试;
107 | * 测试工具下载:[MQTT.fx](http://mqttfx.jensd.de/index.php/download);
108 | * MQTT.fx连接配置如下:
109 | 
110 | * Subscribe:
111 | 
112 | * Publish:
113 | 
114 | * mosquitto Server Message:
115 | ```
116 | root@localhost:/etc/mosquitto/tls# /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf -v
117 | 1510471514: mosquitto version 1.4.8 (build date Mon, 26 Jun 2017 09:31:02 +0100) starting
118 | 1510471514: Config loaded from /etc/mosquitto/mosquitto.conf.
119 | 1510471514: Opening ipv4 listen socket on port 8883.
120 | 1510471514: Opening ipv6 listen socket on port 8883.
121 | 1510471521: New connection from 219.133.225.171 on port 8883.
122 | 1510471522: New client connected from 219.133.225.171 as zengjf (c1, k60, u'zengjf').
123 | 1510471522: Sending CONNACK to zengjf (0, 0)
124 | 1510471526: Received SUBSCRIBE from zengjf
125 | 1510471526: zengjf/index.html (QoS 2)
126 | 1510471526: zengjf 2 zengjf/index.html
127 | 1510471526: Sending SUBACK to zengjf
128 | 1510471533: Received PUBLISH from zengjf (d0, q2, r0, m2, 'zengjf/index.html', ... (34 bytes))
129 | 1510471533: Sending PUBREC to zengjf (Mid: 2)
130 | 1510471533: Received PUBREL from zengjf (Mid: 2)
131 | 1510471533: Sending PUBCOMP to zengjf (Mid: 2)
132 | 1510471533: Sending PUBLISH to zengjf (d0, q2, r0, m1, 'zengjf/index.html', ... (34 bytes))
133 | 1510471534: Received PUBREC from zengjf (Mid: 1)
134 | 1510471534: Sending PUBREL to zengjf (Mid: 1)
135 | 1510471534: Received PUBCOMP from zengjf (Mid: 1)
136 | ```
137 | * Server上测试:[../code/py3/server_tls_srv.py](../code/py3/server_tls_srv.py)
138 | * i.MX6上测试:[../code/py3/server_tls_ca.py](../code/py3/server_tls_ca.py)
139 |
140 | **注意事项**
141 |
142 | 不知道为什么,我用同样的方式,直接在VPS服务器上进行相关测试,总是说证书不对,用server的crt就是能够正常连接。
143 |
144 | 不过根据当前的测试情况来看,如果想要看SSL配置是否成功了,可以直接将上面的ca.crt证书换成server的.crt证书。
145 |
--------------------------------------------------------------------------------
/docs/docs/0001_paho-mqtt_Apache_Apllo.md:
--------------------------------------------------------------------------------
1 | # paho-mqtt + Apache Apllo
2 |
3 | ## 一、Apllo Download
4 |
5 | `wget http://apache.website-solution.net/activemq/activemq-apollo/1.7.1/apache-apollo-1.7.1-unix-distro.tar.gz`
6 |
7 | ## 二、help
8 |
9 | ```
10 | root@localhost:~/apache-apollo-1.7.1/bin# ./apollo
11 | usage: apollo [--log ] []
12 |
13 | The most commonly used apollo commands are:
14 | create creates a new broker instance
15 | disk-benchmark Benchmarks your disk's speed
16 | help Display help information
17 | version Displays the broker version
18 |
19 | See 'apollo help ' for more information on a specific command.
20 | ```
21 |
22 | ## 三、create broker
23 |
24 | ```
25 | root@localhost:~/apache-apollo-1.7.1/bin# ./apollo create mybroker
26 | Creating apollo instance at: mybroker
27 | Generating ssl keystore...
28 |
29 | You can now start the broker by executing:
30 |
31 | "/root/apache-apollo-1.7.1/bin/mybroker/bin/apollo-broker" run
32 |
33 | Or you can setup the broker as system service and run it in the background:
34 |
35 | sudo ln -s "/root/apache-apollo-1.7.1/bin/mybroker/bin/apollo-broker-service" /etc/init.d/
36 | /etc/init.d/apollo-broker-service start
37 |
38 | root@localhost:~/apache-apollo-1.7.1/bin#
39 | ```
40 |
41 | ## 四、run broker
42 |
43 | ```
44 | root@localhost:~/apache-apollo-1.7.1/bin# ./mybroker/bin/apollo-broker run
45 |
46 | _____ .__ .__
47 | / _ \ ______ ____ | | | | ____
48 | / /_\ \\____ \ / _ \| | | | / _ \
49 | / | \ |_> > <_> ) |_| |_( <_> )
50 | \____|__ / __/ \____/|____/____/\____/
51 | \/|__| Apache Apollo (1.7.1)
52 |
53 |
54 | Loading configuration file '/root/apache-apollo-1.7.1/bin/mybroker/etc/apollo.xml'.
55 | INFO | OS : Linux 2.6.32-042stab123.3 (Ubuntu 16.04 LTS)
56 | INFO | JVM : OpenJDK 64-Bit Server VM 1.8.0_131 (Oracle Corporation)
57 | INFO | Apollo : 1.7.1 (at: /root/apache-apollo-1.7.1)
58 | INFO | OS is restricting the open file limit to: 100000
59 | INFO | Accepting connections at: tcp://0.0.0.0:61613
60 | INFO | Accepting connections at: tls://0.0.0.0:61614
61 | INFO | Starting store: leveldb store at /root/apache-apollo-1.7.1/bin/mybroker/data
62 | INFO | Accepting connections at: ws://0.0.0.0:61623/
63 | INFO | Accepting connections at: wss://0.0.0.0:61624/
64 | INFO | Administration interface available at: https://127.0.0.1:61681/
65 | INFO | Administration interface available at: http://127.0.0.1:61680/
66 | ...
67 | ```
68 |
69 | ## 五、Administration interface for remote
70 |
71 | If you want to disable the web the interface then you should remove the web_admin configuration elements. If you want to allow remote administration, you should update the configuration so it bind either the 0.0.0.0 or [::] address.
72 |
73 | * cat mybroker/etc/apollo.xml
74 | ```
75 | ...
76 |
80 |
81 |
82 | ...
83 | ```
84 | * **login passwd**: etc/users.properties
85 | ```
86 | ...
87 | admin=123456
88 | zengjf = 123456
89 | ```
90 | * **groups**: etc/groups.properties
91 | ```
92 | ...
93 | admins=admin|zengjf
94 | ```
95 | * Web access from browser:
96 | 
97 |
98 | ## 六、Example Code
99 |
100 | * 6.1 Test Code
101 | ```Python
102 | #!/usr/bin/env python
103 | # -*- coding: utf-8 -*-
104 |
105 | import paho.mqtt.client as mqtt
106 | import time
107 |
108 | def on_connect(client, userdata, flags, rc):
109 | print("Connected with result code "+str(rc)+'\n')
110 |
111 | def on_message(client, userdata, msg):
112 | print(msg.topic+" "+str(msg.payload)+'\n')
113 |
114 | client1 = mqtt.Client()
115 | client1.username_pw_set("zengjf", "123456") #username: marshal | password: 123456
116 | client1.on_connect = on_connect
117 | client1.on_message = on_message
118 |
119 | client2 = mqtt.Client()
120 | client2.username_pw_set("admin", "123456") #username: admin | password: password
121 | client2.on_connect = on_connect
122 | client2.on_message = on_message
123 |
124 | HOST = "127.0.0.1" #IP address of broker
125 |
126 | client1.connect_async(HOST,61613,60)
127 | client2.connect_async(HOST,61613,60)
128 | client1.loop_start() #client1 runs a thread at background
129 | client2.loop_start() #client2 runs a thread at background
130 |
131 | for i in range(30):
132 | time1 = time.time()
133 | client1.subscribe('manipulated') #client1 subcribes a topic 'manipulated'
134 | client2.subscribe('position') #client2 subcribes a topic 'position'
135 |
136 | client2.publish('manipulated',i*0.02) #client2 publishes topic 'manipulated' with content 'i*0.02'
137 | client1.publish('position',i) #client1 publishes topic 'position' with content 'i'
138 | time2 = time.time()
139 | interval = time2-time1 #interval in each data exchange
140 | print 'Interval '+str(i)+': '+str(interval)+'\n'
141 | time.sleep(1)
142 |
143 | #stop threads in background
144 | client1.loop_stop()
145 | client2.loop_start()
146 | ```
147 | * 6.2 测试输出信息
148 | ```Shell
149 | root@localhost:~/mqtt# python apollo.py
150 | [Errno 104] Connection reset by peer
151 | Interval 0: 0.000136852264404
152 |
153 | [Errno 104] Connection reset by peer
154 | Interval 1: 0.000112056732178
155 |
156 | [Errno 104] Connection reset by peer
157 | [Errno 104] Connection reset by peer
158 | Interval 2: 0.000102996826172
159 |
160 | Interval 3: 0.000102043151855
161 |
162 | [Errno 104] Connection reset by peer
163 | [Errno 104] Connection reset by peer
164 | Interval 4: 0.000112056732178
165 | ...
166 | ```
167 | * 6.3 log日志报错(log/connection.log)
168 | ```
169 | ...
170 | 2017-11-06 02:47:01,655 MQTT connection '/23.106.155.16:38924' error: Internal Server Error: java.lang.NullPointerException
171 | 2017-11-06 02:47:01,656 disconnected: local:/23.106.155.16:61613, remote:/23.106.155.16:38924
172 | 2017-11-06 02:47:01,658 connected: local:/23.106.155.16:61613, remote:/23.106.155.16:38594
173 | 2017-11-06 02:47:01,659 connected: local:/23.106.155.16:61613, remote:/23.106.155.16:38594
174 | 2017-11-06 02:47:01,660 MQTT connection '/23.106.155.16:38594' error: Internal Server Error: java.lang.NullPointerException
175 | 2017-11-06 02:47:01,660 disconnected: local:/23.106.155.16:61613, remote:/23.106.155.16:38594
176 | ```
177 | * 6.4 [Apache Apollo on Ubuntu 14.04 - Can not connect to Websocket (Thread issue?)](https://stackoverflow.com/questions/35863107/apache-apollo-on-ubuntu-14-04-can-not-connect-to-websocket-thread-issue)
178 | * 6.5 Windows上遇到同样的问题:`WARN | Internal Server Error: java.lang.NullPointerException`
179 | * 6.6 针对以上的问题,不再进行解决。
180 |
181 |
--------------------------------------------------------------------------------
/docs/code/html/ShowTime/DI_DO.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Start Page
7 |
8 |
9 |
10 |
11 |
12 |
13 |
19 |
20 |
21 |
24 |
25 |
STM8 DI DO Data
26 |
27 |
28 |
29 |
30 |
31 | |
32 | DO
33 | |
34 |
35 |
36 | |
37 |
48 |
49 |
50 |
82 |
83 |
84 |
85 |
86 |
87 |
88 | |
89 | DI
90 | |
91 |
105 |
106 |
107 |
108 |
109 |
110 | |
111 |
122 |
123 |
124 |
141 |
142 |
143 |
144 |
266 |
267 |
268 |
--------------------------------------------------------------------------------