Skip to content

Commit

Permalink
style: 💄 add flag for black and remove comment
Browse files Browse the repository at this point in the history
skip-string-normalization can ignore quote normalization
  • Loading branch information
david30907d committed Sep 12, 2020
1 parent 05d8f20 commit f3d3c08
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 102 deletions.
193 changes: 92 additions & 101 deletions berrynet/client/camera.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
#!/usr/bin/python3
"""
Copyright 2018 DT42
This file is part of BerryNet.
BerryNet is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
BerryNet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with BerryNet. If not, see <http://www.gnu.org/licenses/>.
"""
#
# Copyright 2018 DT42
#
# This file is part of BerryNet.
#
# BerryNet is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# BerryNet is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with BerryNet. If not, see <http://www.gnu.org/licenses/>.

import time
import logging
Expand All @@ -30,95 +29,87 @@


def parse_args():
"""
args
"""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
"--mode",
default="stream",
help="Camera creates frame(s) from stream or file. (default: stream)",
ap = argparse.ArgumentParser()
ap.add_argument(
'--mode',
default='stream',
help='Camera creates frame(s) from stream or file. (default: stream)',
)
arg_parser.add_argument(
"--stream-src",
ap.add_argument(
'--stream-src',
type=str,
default="0",
default='0',
help=(
"Camera stream source. "
"It can be device node ID or RTSP URL. "
"(default: 0)"
'Camera stream source. '
'It can be device node ID or RTSP URL. '
'(default: 0)'
),
)
arg_parser.add_argument(
"--fps",
ap.add_argument(
'--fps',
type=float,
default=1,
help="Frame per second in streaming mode. (default: 1)",
)
arg_parser.add_argument(
"--filepath", default="", help="Input image path in file mode. (default: empty)"
help='Frame per second in streaming mode. (default: 1)',
)
arg_parser.add_argument("--broker-ip", default="localhost", help="MQTT broker IP.")
arg_parser.add_argument(
"--broker-port", default=1883, type=int, help="MQTT broker port."
ap.add_argument(
'--filepath', default='', help='Input image path in file mode. (default: empty)'
)
arg_parser.add_argument(
"--topic",
default="berrynet/data/rgbimage",
help="The topic to send the captured frames.",
ap.add_argument('--broker-ip', default='localhost', help='MQTT broker IP.')
ap.add_argument('--broker-port', default=1883, type=int, help='MQTT broker port.')
ap.add_argument(
'--topic',
default='berrynet/data/rgbimage',
help='The topic to send the captured frames.',
)
arg_parser.add_argument(
"--display",
action="store_true",
ap.add_argument(
'--display',
action='store_true',
help=(
"Open a window and display the sent out frames. "
"This argument is only effective in stream mode."
'Open a window and display the sent out frames. '
'This argument is only effective in stream mode.'
),
)
arg_parser.add_argument(
"--hash",
action="store_true",
help="Add md5sum of a captured frame into the result.",
ap.add_argument(
'--hash',
action='store_true',
help='Add md5sum of a captured frame into the result.',
)
arg_parser.add_argument("--debug", action="store_true", help="Debug mode toggle")
return vars(arg_parser.parse_args())
ap.add_argument('--debug', action='store_true', help='Debug mode toggle')
return vars(ap.parse_args())


def main():
"""
main
"""
args = parse_args()
if args["debug"]:
if args['debug']:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)

comm_config = {
"subscribe": {},
"broker": {"address": args["broker_ip"], "port": args["broker_port"]},
'subscribe': {},
'broker': {'address': args['broker_ip'], 'port': args['broker_port']},
}
comm = Communicator(comm_config, debug=True)

duration = lambda t: (datetime.now() - t).microseconds / 1000

if args["mode"] == "stream":
if args['mode'] == 'stream':
counter = 0
fail_counter = 0

# Check input stream source
if args["stream_src"].isdigit():
if args['stream_src'].isdigit():
# source is a physically connected camera
stream_source = int(args["stream_src"])
stream_source = int(args['stream_src'])
else:
# source is an IP camera
stream_source = args["stream_src"]
stream_source = args['stream_src']
capture = cv2.VideoCapture(stream_source)
cam_fps = capture.get(cv2.CAP_PROP_FPS)
if cam_fps > 30 or cam_fps < 1:
logger.warning("Camera FPS is %s (>30 or <1). Set it to 30.", cam_fps)
logger.warn('Camera FPS is %s (>30 or <1). Set it to 30.' % cam_fps)
cam_fps = 30
out_fps = args["fps"]
out_fps = args['fps']
interval = int(cam_fps / out_fps)

# warmup
Expand All @@ -130,21 +121,21 @@ def main():
# warmup_counter += 1
# t_warmup_now = time.time()

logger.debug("===== VideoCapture Information =====")
logger.debug('===== VideoCapture Information =====')
if stream_source.isdigit():
stream_source_uri = "/dev/video{}", stream_source
stream_source_uri = '/dev/video{}'.format(stream_source)
else:
stream_source_uri = stream_source
logger.debug("Stream Source: %s", stream_source_uri)
logger.debug("Camera FPS: %s", cam_fps)
logger.debug("Output FPS: %s", out_fps)
logger.debug("Interval: %s", interval)
logger.debug("Send MQTT Topic: %s", args["topic"])
# logger.debug('Warmup Counter: %s', warmup_counter)
logger.debug("====================================")
logger.debug('Stream Source: %s' % stream_source_uri)
logger.debug('Camera FPS: %s' % cam_fps)
logger.debug('Output FPS: %s' % out_fps)
logger.debug('Interval: %s' % interval)
logger.debug('Send MQTT Topic: %s' % args['topic'])
# logger.debug('Warmup Counter: %s' % warmup_counter))
logger.debug('====================================')

while True:
status, image = capture.read()
status, im = capture.read()

# To verify whether the input source is alive, you should use the
# return value of capture.read(). It will not work by capturing
Expand All @@ -162,53 +153,53 @@ def main():
if status is True:
counter += 1
if counter == interval:
logger.debug("Drop frames: %s", counter - 1)
logger.debug('Drop frames: %s' % counter - 1)
counter = 0

# Open a window and display the ready-to-send frame.
# This is useful for development and debugging.
if args["display"]:
cv2.imshow("Frame", image)
if args['display']:
cv2.imshow('Frame', im)
cv2.waitKey(1)

current_time = datetime.now()
_, jpg_bytes = cv2.imencode(".jpg", image)
mqtt_payload = payload.serialize_jpg(jpg_bytes, args["hash"])
comm.send(args["topic"], mqtt_payload)
logger.debug("send: %s ms", duration(current_time))
t = datetime.now()
retval, jpg_bytes = cv2.imencode('.jpg', im)
mqtt_payload = payload.serialize_jpg(jpg_bytes, args['hash'])
comm.send(args['topic'], mqtt_payload)
logger.debug('send: %s ms' % duration(t))
else:
pass
else:
fail_counter += 1
logger.critical(
"ERROR: Failure #%s happened when reading frame", fail_counter
'ERROR: Failure #%s happened when reading frame' % fail_counter
)

# Re-create capture.
capture.release()
logger.critical(
"Re-create a capture and reconnect to %s after 5s", stream_source
'Re-create a capture and reconnect to %s after 5s' % stream_source
)
time.sleep(5)
capture = cv2.VideoCapture(stream_source)
elif args["mode"] == "file":
elif args['mode'] == 'file':
# Prepare MQTT payload
image = cv2.imread(args["filepath"])
_, jpg_bytes = cv2.imencode(".jpg", image)
im = cv2.imread(args['filepath'])
retval, jpg_bytes = cv2.imencode('.jpg', im)

current_time = datetime.now()
mqtt_payload = payload.serialize_jpg(jpg_bytes, args["hash"])
logger.debug("payload: %s ms", duration(current_time))
logger.debug("payload size: %s", len(mqtt_payload))
t = datetime.now()
mqtt_payload = payload.serialize_jpg(jpg_bytes, args['hash'])
logger.debug('payload: %s ms' % duration(t))
logger.debug('payload size: %s' % len(mqtt_payload))

# Client publishes payload
current_time = datetime.now()
comm.send(args["topic"], mqtt_payload)
logger.debug("mqtt.publish: %s ms", duration(current_time))
logger.debug("publish at %s", datetime.now().isoformat())
t = datetime.now()
comm.send(args['topic'], mqtt_payload)
logger.debug('mqtt.publish: %s ms' % duration(t))
logger.debug('publish at %s' % datetime.now().isoformat())
else:
logger.error("User assigned unknown mode %s", args["mode"])
logger.error('User assigned unknown mode {}'.format(args['mode']))


if __name__ == "__main__":
if __name__ == '__main__':
main()
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"lint-staged": {
"**/*.py": [
"isort -rc -y -ac -ls",
"black",
"black --skip-string-normalization",
"mypy --ignore-missing-imports",
"bandit",
"git add"
Expand Down

0 comments on commit f3d3c08

Please sign in to comment.