I can't handle this Error TypeError: can't concat str to bytes - serial-port

import time
import serial
import sys
SCREEN_DISPLAY=True
SAVE_TO_FILE=True
txtfile = open('datafile.csv','rb')
serialport = serial.Serial('COM5',timeout=20,baudrate=9600)
while True:
sensordata = serialport.readline().decode('ascii')
timenow = time.strftime("Date: %Y-%m-%d // Time: %H:%M:%S // Temperature: ")
if SCREEN_DISPLAY: print(str.encode(timenow)+sensordata)
time.sleep(0.05)
if SAVE_TO_FILE: txtfile.write(str.encode(timenow)+sensordata)
serialport.close()
txtfile.close()

Related

How to use gstreamer to output rtsp stream for multiple clients to access

I used the solution of< https://stackoverflow.com/questions/47396372/write-opencv-frames-into-gstreamer-rtsp-server-pipeline/60580247#60580247>, but when I use multiple clients to access the rtsp stream , The error of Assertion fctx->async_lock failed at libavcodec/pthread_frame.c:155 appeared.
I am new to gstreamer, Here is the complete Python code (copied from WisdomPill's answer):
import cv2
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstRtspServer', '1.0')
from gi.repository import Gst, GstRtspServer, GObject, GLib
class SensorFactory(GstRtspServer.RTSPMediaFactory):
def __init__(self, **properties):
super(SensorFactory, self).__init__(**properties)
self.cap = cv2.VideoCapture("http://192.168.2.153/video/mjpg.cgi")
self.number_frames = 0
self.fps = 10
self.duration = 1 / self.fps * Gst.SECOND # duration of a frame in nanoseconds
self.launch_string = 'appsrc name=source is-live=true block=true format=GST_FORMAT_TIME ' \
'caps=video/x-raw,format=BGR,width=640,height=480,framerate={}/1 ' \
'! videoconvert ! video/x-raw,format=I420 ' \
'! x264enc speed-preset=ultrafast tune=zerolatency ' \
'! rtph264pay config-interval=1 name=pay0 pt=96'.format(self.fps)
def on_need_data(self, src, lenght):
if self.cap.isOpened():
ret, frame = self.cap.read()
if ret:
data = frame.tobytes()
buf = Gst.Buffer.new_allocate(None, len(data), None)
buf.fill(0, data)
buf.duration = self.duration
timestamp = self.number_frames * self.duration
buf.pts = buf.dts = int(timestamp)
buf.offset = timestamp
self.number_frames += 1
retval = src.emit('push-buffer', buf)
print ('pushed buffer, frame {}, duration {} ns, durations {} s'.format(self.number_frames, self.duration, self.duration / Gst.SECOND))
if retval != Gst.FlowReturn.OK:
print(retval)
def do_create_element(self, url):
return Gst.parse_launch(self.launch_string)
def do_configure(self, rtsp_media):
self.number_frames = 0
appsrc = rtsp_media.get_element().get_child_by_name('source')
appsrc.connect('need-data', self.on_need_data)
class GstServer(GstRtspServer.RTSPServer):
def __init__(self, **properties):
super(GstServer, self).__init__(**properties)
self.factory = SensorFactory()
self.factory.set_shared(True)
self.get_mount_points().add_factory("/test", self.factory)
self.set_service('9999')
self.attach(None)
Gst.init(None)
server = GstServer()
loop = GLib.MainLoop()
loop.run()
if you have any suggestions, I would appreciate it

Date and Time in Kotlin

I am new to kotlin. And I got a problem.
I have this code:
val sdf = SimpleDateFormat("dd.MM.yyyy")
val currentDate = sdf.format(Date())
println(currentDate)
val stringDate = "12.03.2015"
val dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH)
val millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli()
println(millisecondsSinceEpoch)
val time = currentDate - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)
But on the line:
val time = currentDate - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)
I get the error:
java.lang.IllegalArgumentException: Cannot format given Object as a Date
Please help me how you can fix this. I need to subtract the current date from the date that is in string.
UPDATE:
How to subtract one date from another correctly and get the difference in days?
I suggest you switch from the outdated java.util date/time API to the modern date/time API. Given below is the Java code for your requirement and I hope you should be able to convert the same into Kotlin. However, if you face any issue, I can convert the same into Kotlin code for you.
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Define format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH);
// Given date-time
ZonedDateTime givenDateTime = LocalDateTime.of(LocalDate.parse("12.03.2015", formatter), LocalTime.of(0, 0))
.atZone(ZoneId.of("Etc/UTC"));
// Now
ZonedDateTime zdtNow = ZonedDateTime.now(ZoneId.of("Etc/UTC"));
// Period between the two dates
Period period = Period.between(givenDateTime.toLocalDate(), zdtNow.toLocalDate());
// Given date-time with current year, month and day
ZonedDateTime adjusted = givenDateTime.with(LocalDate.now(ZoneId.of("Etc/UTC")));
// Duration between the two times
Duration duration = Duration.between(adjusted, zdtNow);
// Display each part of the period and duration
System.out.printf("%d years %d month %d days %d hours %d minutes %d seconds %d nanoseconds", period.getYears(),
period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(),
duration.toSecondsPart(), duration.toNanosPart());
}
}
Output:
5 years 4 month 7 days 19 hours 30 minutes 37 seconds 507058000 nanoseconds
Using OffsetDateTime:
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Define format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH);
// Given date-time
OffsetDateTime givenDateTime = LocalDateTime.of(LocalDate.parse("12.03.2015", formatter), LocalTime.of(0, 0))
.atOffset(ZoneOffset.UTC);
// Now
OffsetDateTime odtNow = OffsetDateTime.now(ZoneOffset.UTC);
// Period between the two dates
Period period = Period.between(givenDateTime.toLocalDate(), odtNow.toLocalDate());
// Given date-time with current year, month and day
OffsetDateTime adjusted = givenDateTime.with(LocalDate.now(ZoneOffset.UTC));
// Duration between the two times
Duration duration = Duration.between(adjusted, odtNow);
// Display each part of the period and duration
System.out.printf("%d years %d month %d days %d hours %d minutes %d seconds %d nanoseconds", period.getYears(),
period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(),
duration.toSecondsPart(), duration.toNanosPart());
}
}
Following is the corrected version of your initial program. However as others pointed out it is advisable to use new java Time API.
There is nice article highlighting problem with old Java Date and Calendar API
https://programminghints.com/2017/05/still-using-java-util-date-dont/
import java.util.Date
import java.util.Locale
import java.time.Instant
import java.time.LocalDateTime
import java.time.LocalDate
import java.time.ZoneOffset
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
val sdf = SimpleDateFormat("dd.MM.yyyy")
val currentDate = Date()
val currentFormattedDate = sdf.format(currentDate)
println(currentFormattedDate)
val now = currentDate.getTime();
val stringDate = "12.03.2015"
val dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH)
val millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli()
println(millisecondsSinceEpoch)
val time = now - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)
}
Thanks everyone. But I decided to do this. And it seems like everything works)
fun daysString(dataend: String):String{
val dateFormat = SimpleDateFormat("dd.MM.yyyy")
val endDate = dateFormat.parse(dataend)
val currentDate = Date()
val time = endDate.time - currentDate.time
val days = time / 1000 / 3600 / 24
val strtoday = days.toString()
return strtoday
}
Now in the code I am using:
val data_end = "10.10.2020"
daysString(data_end)
and I get strtoday
Get your required Date and then can do this:
val sdf = SimpleDateFormat("dd/MM/yyyy",Locale.ENGLISH)
val theDate = sdf.parse(selectedDate)
val selectedDate = theDate!!.time/86400000 //.time gives milliseconds
val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))
val currentDate = currentDate!!.time/86400000 //86400000 milliseconds in a day
val diff = currentDate - selectedDate
println(diffInMinutes.toString()) //set it to any view or use as needed

"Parser must be a string or character stream, not datetime" error in lambda aws function - can't figure out how to fix it

I am getting a very annoying error when trying to save/test this Lambda Boto3 function. There are other threads here on this issue, but i have spent about 2 hours trying to debug this and can't figure out what i'm doing wrong (it's probably something obvious). Any help would be appreciated!
{
"errorMessage": "Parser must be a string or character stream, not datetime",
"errorType": "TypeError",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 35, in lambda_handler\n a = dateutil.parser.parse(instance.launch_time)\n",
" File \"/var/runtime/dateutil/parser/_parser.py\", line 1358, in parse\n return DEFAULTPARSER.parse(timestr, **kwargs)\n",
" File \"/var/runtime/dateutil/parser/_parser.py\", line 646, in parse\n res, skipped_tokens = self._parse(timestr, **kwargs)\n",
" File \"/var/runtime/dateutil/parser/_parser.py\", line 722, in _parse\n l = _timelex.split(timestr) # Splits the timestr into tokens\n",
" File \"/var/runtime/dateutil/parser/_parser.py\", line 207, in split\n return list(cls(s))\n",
" File \"/var/runtime/dateutil/parser/_parser.py\", line 76, in __init__\n '{itype}'.format(itype=instream.__class__.__name__))\n"
]
}
import json
import boto3
import time
import datetime
import dateutil
from dateutil.parser import parse
def lambda_handler(event, context):
detailDict = event["detail"]
ec2 = boto3.resource('ec2')
instanceId = str(detailDict["instance-id"])
instance = ec2.Instance(instanceId)
instanceState = instance.state
a = dateutil.parser.parse(instance.launch_time)
b = current_time = datetime.datetime.now(launch_time.tzinfo)
# returns a timedelta object
c = a-b
print('Difference: ', c)
minutes = c.seconds / 60
print('Difference in minutes: ', minutes)
Message=str(instanceId)+" is "+str(instanceState["Name"])
return {
'statusCode': 200,
'body': Message
}
The launch-time property is already a datetime property. You do not need to parse it.
Reference:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html

Match datetime property value in response value array list using groovy

I am trying to match if my datetime variable present in array of multiple dates but error popup displayed.
Error :
assert responseStartDateTime.contains(requestStartDateTime) | | | | false 2018-01-16T04:30:00 [2018-01-16T04:30:00, 2018-01-16T06:00:00]
Groovy code :
import groovy.json.JsonSlurper
import java.text.SimpleDateFormat
//request local time
def StartDateTime = context.expand('${#Project#StartDateTime}')
log.info 'Request StartTime : ' + StartDateTime
def EndDateTime = context.expand('${#Project#EndDateTime}')
log.info 'Request EndTime : ' + EndDateTime
//Remove Z from the request time
def outputDateFormat = "yyyy-MM-dd'T'HH:mm:ss"
start = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(StartDateTime)
end = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(EndDateTime)
def requestStartDateTime = "${start.format(outputDateFormat)}"
log.info 'Request StartTime : ' + requestStartDateTime
def requestEndDateTime = "${end.format(outputDateFormat)}"
log.info 'Request EndTime : ' + requestEndDateTime
def ResponseMessage = messageExchange.response.responseContent
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
//Store response local time result to variable
def responseStartDateTime = jsonSlurper.MeetingItems.TimeFrom
log.info 'Response StartTime : ' + responseStartDateTime
def responseEndDateTime = jsonSlurper.MeetingItems.TimeTo
log.info 'Response EndTime : ' + responseEndDateTime
//Assert request local time with response local time
assert responseStartDateTime.contains(requestStartDateTime)
assert responseEndDateTime.contains(requestEndDateTime)
Property values :
StartDateTime - 2018-01-16T04:30:00.000Z
EndDateTime - 2018-01-16T04:45:00.000Z

Parse date to "yyyy-MM-dd'T'00:00:00" using Groovy

I am trying to parse date format '2017-12-18T20:41:06.136Z' into "2017-12-18'T'00:00:00"
Date date = new Date();
def dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
dateformat.setTimeZone(TimeZone.getTimeZone(TimeZoneCode));
def currentDate = dateformat.format(date)
log.info "Current Date : " + currentDate
date1 = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00").parse(currentDate)
log.info "Current Date : " + date1
Error displayed :
java.text.ParseException: Unparseable date: "2017-12-18T20:46:06:234Z" error at line: 16
This line gives error :
date1 = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00").parse(currentDate)
Running Groovy on Java 8 gives you access to the much better Date/Time classes... You can just do:
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
String result = ZonedDateTime.parse("2017-12-18T20:41:06.136Z")
.truncatedTo(ChronoUnit.DAYS)
.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
In order to avoid the mentioned error, use below statement Date.parse(..):
def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def dateString = "2017-12-18T20:41:06.136Z"
def date = Date.parse(dateFormat, dateString)
You should be able to achieve what you are trying to using below script.
//Change timezone if needed
def tz = 'IST'
TimeZone.setDefault(TimeZone.getTimeZone(tz))
def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def dateString = "2017-12-18T20:41:06.136Z"
Calendar calendar = Calendar.getInstance()
calendar.with {
time = Date.parse(dateFormat,dateString)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
log.info calendar.time.format(dateFormat)
You can quickly try the same online demo
if you need to parse only part of date, use the following syntax:
Date.parse("yyyy-MM-dd'T'HH:mm:ss",'2017-12-18T16:05:58bla-bla')

Resources