-
Notifications
You must be signed in to change notification settings - Fork 1
/
dappserver.py
executable file
·402 lines (351 loc) · 15 KB
/
dappserver.py
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# Copyright 2017 Google Inc. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Sample device that consumes configuration from Google Cloud IoT.
This example represents a simple device with a temperature sensor and a fan
(simulated with software). When the device's fan is turned on, its temperature
decreases by one degree per second, and when the device's fan is turned off,
its temperature increases by one degree per second.
Every second, the device publishes its temperature reading to Google Cloud IoT
Core. The server meanwhile receives these temperature readings, and decides
whether to re-configure the device to turn its fan on or off. The server will
instruct the device to turn the fan on when the device's temperature exceeds 10
degrees, and to turn it off when the device's temperature is less than 0
degrees. In a real system, one could use the cloud to compute the optimal
thresholds for turning on and off the fan, but for illustrative purposes we use
a simple threshold model.
To connect the device you must have downloaded Google's CA root certificates,
and a copy of your private key file. See cloud.google.com/iot for instructions
on how to do this. Run this script with the corresponding algorithm flag.
$ python cloudiot_pubsub_example_mqtt_device.py \
--project_id=my-project-id \
--registry_id=example-my-registry-id \
--device_id=my-device-id \
--private_key_file=rsa_private.pem \
--algorithm=RS256
With a single server, you can run multiple instances of the device with
different device ids, and the server will distinguish them. Try creating a few
devices and running them all at the same time.
"""
from web3 import Web3, HTTPProvider
import argparse
import datetime
import json
import os
import ssl
import time
from threading import Lock
import jwt
import paho.mqtt.client as mqtt
import glob
import random
import base64
import io
import boto3
from google.cloud import pubsub
from google.cloud import pubsub_v1
from google.oauth2 import service_account
from googleapiclient import discovery
v_count = 0
device_list = list()
API_SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
API_VERSION = 'v1'
DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest'
SERVICE_NAME = 'cloudiot'
def create_jwt(project_id, private_key_file, algorithm):
"""Create a JWT (https://jwt.io) to establish an MQTT connection."""
token = {
'iat': datetime.datetime.utcnow(),
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
'aud': project_id
}
with open(private_key_file, 'r') as f:
private_key = f.read()
print('Creating JWT using {} from private key file {}'.format(
algorithm, private_key_file))
return jwt.encode(token, private_key, algorithm=algorithm)
def error_str(rc):
"""Convert a Paho error to a human readable string."""
return '{}: {}'.format(rc, mqtt.error_string(rc))
class Device(object):
"""Represents the state of a single device."""
def __init__(self, dev_id, service_account_json, project_id, registry_id, region):
self.temperature = 0
self.fan_on = False
self.connected = False
self.id = dev_id
self.project_id = project_id
self.registry_id = registry_id
self.cloud_region = region
self.central_topic = 'projects/project2-277316/topics/my-topic'
credentials = service_account.Credentials.from_service_account_file(
service_account_json).with_scopes(API_SCOPES)
if not credentials:
sys.exit('Could not load service account credential '
'from {}'.format(service_account_json))
discovery_url = '{}?version={}'.format(DISCOVERY_API, API_VERSION)
self._service = discovery.build(
SERVICE_NAME,
API_VERSION,
discoveryServiceUrl=discovery_url,
credentials=credentials,
cache_discovery=False)
# Used to serialize the calls to the
# modifyCloudToDeviceConfig REST method. This is needed
# because the google-api-python-client library is built on top
# of the httplib2 library, which is not thread-safe. For more
# details, see: https://developers.google.com/
# api-client-library/python/guide/thread_safety
self._update_config_mutex = Lock()
def _update_device_config(self, project_id, region, registry_id, device_id, data):
"""Push the data to the given device as configuration."""
body = {
'version_to_update': 0,
'binary_data': base64.b64encode(
data.encode('utf-8')).decode('ascii')
}
device_name = ('projects/{}/locations/{}/registries/{}/'
'devices/{}'.format(
project_id,
region,
registry_id,
device_id))
request = self._service.projects().locations().registries().devices(
).modifyCloudToDeviceConfig(name=device_name, body=body)
time.sleep(20)
# The http call for the device config change is thread-locked so
# that there aren't competing threads simultaneously using the
# httplib2 library, which is not thread-safe.
self._update_config_mutex.acquire()
try:
request.execute()
time.sleep(5)
except HttpError as e:
# If the server responds with a HtppError, log it here, but
# continue so that the message does not stay NACK'ed on the
# pubsub channel.
print('Error executing ModifyCloudToDeviceConfig: {}'.format(e))
finally:
self._update_config_mutex.release()
def get_id(self):
return self.id
def update_sensor_data(self):
"""Pretend to read the device's sensor data.
If the fan is on, assume the temperature decreased one degree,
otherwise assume that it increased one degree.
"""
if self.fan_on:
self.temperature -= 1
else:
self.temperature += 1
def wait_for_connection(self, timeout):
"""Wait for the device to become connected."""
total_time = 0
while not self.connected and total_time < timeout:
time.sleep(1)
total_time += 1
if not self.connected:
raise RuntimeError('Could not connect to MQTT bridge.')
def on_connect(self, unused_client, unused_userdata, unused_flags, rc):
"""Callback for when a device connects."""
print('Connection Result:', error_str(rc))
self.connected = True
def on_disconnect(self, unused_client, unused_userdata, rc):
"""Callback for when a device disconnects."""
print('Disconnected:', error_str(rc))
self.connected = False
def on_publish(self, unused_client, unused_userdata, unused_mid):
"""Callback when the device receives a PUBACK from the MQTT bridge."""
print('Published message acked.')
def on_subscribe(self, unused_client, unused_userdata, unused_mid, granted_qos):
"""Callback when the device receives a SUBACK from the MQTT bridge."""
print('Subscribed: ', granted_qos)
if granted_qos[0] == 128:
print('Subscription failed.')
def on_message(self, unused_client, unused_userdata, message):
"""Callback when the device receives a message on a subscription."""
payload = message.payload.decode('utf-8')
# print('Received message \'{}\' on topic \'{}\' with Qos {}'.format(
# payload, message.topic, str(message.qos)))
# The device will receive its latest config when it subscribes to the
# config topic. If there is no configuration for the device, the device
# will receive a config with an empty payload.
if not payload:
return
# The config is passed in the payload of the message. In this example,
# the server sends a serialized JSON string.
try:
try:
data = json.loads(payload)
except ValueError as e:
print('Loading Payload ({}) threw an Exception: {}.'.format(
message.data, e))
message.ack()
return
dev_id = data['id']
key = data['key']
addr = data['address']
if(authenticate(addr, key)):
mqtt_config_topic = '/devices/{}/config/'.format(dev_id)
payload_json = {'status':'authorized', 'topic': self.central_topic}
payload = json.dumps(payload_json)
device_project_id = self.project_id
device_registry_id = self.registry_id
device_id = dev_id
device_region = self.cloud_region
print("Device " + dev_id + "authorized" + "\n\n\n")
# Send the config to the device.
self._update_device_config(
device_project_id,
device_region,
device_registry_id,
device_id,
payload)
time.sleep(1)
else:
mqtt_config_topic = '/devices/{}/config/'.format(dev_id)
payload_json = {'status':'unauthorized'}
payload = json.dumps(payload_json)
device_project_id = self.project_id
device_registry_id = self.registry_id
device_id = dev_id
device_region = self.cloud_region
print("Device " + dev_id + "not authorized" + "\n\n\n")
# Send the config to the device.
self._update_device_config(
device_project_id,
device_region,
device_registry_id,
device_id,
payload)
time.sleep(1)
message.ack()
except binascii.Error:
message.ack() # To move forward if a message can't be processed
def parse_command_line_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description='Example Google Cloud IoT MQTT device connection code.')
parser.add_argument(
'--project_id',
default=os.environ.get("GOOGLE_CLOUD_PROJECT"),
required=True,
help='GCP cloud project name.')
parser.add_argument(
'--registry_id', required=True, help='Cloud IoT registry id')
parser.add_argument(
'--device_id',
required=True,
help='Cloud IoT device id')
parser.add_argument(
'--private_key_file', required=True, help='Path to private key file.')
parser.add_argument(
'--algorithm',
choices=('RS256', 'ES256'),
required=True,
help='Which encryption algorithm to use to generate the JWT.')
parser.add_argument(
'--cloud_region', default='us-central1', help='GCP cloud region')
parser.add_argument(
'--ca_certs',
default='roots.pem',
help='CA root certificate. Get from https://pki.google.com/roots.pem')
parser.add_argument(
'--num_messages',
type=int,
default=100,
help='Number of messages to publish.')
parser.add_argument(
'--mqtt_bridge_hostname',
default='mqtt.googleapis.com',
help='MQTT bridge hostname.')
parser.add_argument(
'--mqtt_bridge_port', type=int, default=8883, help='MQTT bridge port.')
parser.add_argument(
'--message_type', choices=('event', 'state'),
default='event',
help=('Indicates whether the message to be published is a '
'telemetry event or a device state message.'))
parser.add_argument(
'--service_account_json',
required=True,
help='Path to service account json file.')
return parser.parse_args()
#Added code to encode image
def authenticate(addr, cred):
print("address and credential is")
print(addr)
print(cred)
with open('paymentABI.json') as f:
paymentabi = json.load(f)
w3 = Web3(HTTPProvider("https://ropsten.infura.io/v3/f9c884008XXXXXXXXX6e5"))
unicorns = w3.eth.contract(address="0xfB6916095ca1dXXXXXXXXXXXXXXX74c37c5d359", abi=paymentabi)
nonce = w3.eth.getTransactionCount(addr)
# user account
# Build a transaction that invokes this contract's function, called transfer
unicorn_txn = unicorns.functions.pay().buildTransaction({
'chainId': 3,
'gas': 70000,
'gasPrice': w3.toWei('1', 'gwei'),
'nonce': nonce,
'value': w3.toWei('0.02', 'ether')
})
# user private key
private_key = cred
signed_txn = w3.eth.account.sign_transaction(unicorn_txn, private_key=private_key)
try:
w3.eth.sendRawTransaction(signed_txn.rawTransaction)
# w3.toHex(w3.keccak(signed_txn.rawTransaction))
except Exception as e:
print('Transaction failed', e)
return False
return True
def main():
args = parse_command_line_args()
# subscriber = pubsub.SubscriberClient()
# subscription_path = subscriber.subscription_path(
# args.project_id,
# args.pubsub_subscription)
# publisher = pubsub_v1.PublisherClient()
# Create the MQTT client and connect to Cloud IoT.
client = mqtt.Client(
client_id='projects/{}/locations/{}/registries/{}/devices/{}'.format(
args.project_id,
args.cloud_region,
args.registry_id,
args.device_id))
client.username_pw_set(
username='unused',
password=create_jwt(
args.project_id,
args.private_key_file,
args.algorithm))
client.tls_set(ca_certs=args.ca_certs, tls_version=ssl.PROTOCOL_TLSv1_2)
device = Device(args.device_id, args.service_account_json, args.project_id, args.registry_id, args.cloud_region)
client.on_connect = device.on_connect
client.on_publish = device.on_publish
client.on_disconnect = device.on_disconnect
client.on_subscribe = device.on_subscribe
client.on_message = device.on_message
client.connect(args.mqtt_bridge_hostname, args.mqtt_bridge_port)
client.loop_start()
mqtt_config_topic = '/devices/{}/config'.format(args.device_id)
# Wait up to 5 seconds for the device to connect.
device.wait_for_connection(5)
# Subscribe to the config topic.
client.subscribe(mqtt_config_topic, qos=1)
time.sleep(2000000)
client.disconnect()
client.loop_stop()
print('Finished loop successfully. Goodbye!')
if __name__ == '__main__':
main()